blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
327
content_id
stringlengths
40
40
detected_licenses
listlengths
0
91
license_type
stringclasses
2 values
repo_name
stringlengths
5
134
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
46 values
visit_date
timestamp[us]date
2016-08-02 22:44:29
2023-09-06 08:39:28
revision_date
timestamp[us]date
1977-08-08 00:00:00
2023-09-05 12:13:49
committer_date
timestamp[us]date
1977-08-08 00:00:00
2023-09-05 12:13:49
github_id
int64
19.4k
671M
star_events_count
int64
0
40k
fork_events_count
int64
0
32.4k
gha_license_id
stringclasses
14 values
gha_event_created_at
timestamp[us]date
2012-06-21 16:39:19
2023-09-14 21:52:42
gha_created_at
timestamp[us]date
2008-05-25 01:21:32
2023-06-28 13:19:12
gha_language
stringclasses
60 values
src_encoding
stringclasses
24 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
7
9.18M
extension
stringclasses
20 values
filename
stringlengths
1
141
content
stringlengths
7
9.18M
a3c427445f17d2b5a0200b06411d7591eb021b99
5b2f016f1298c790224d83c1e17a425640fc777d
/monod/Manuscript/MONOD_analysis_scripts/bak/S612.R
dbeab2c3beac6ab90ff47dce1c25c5bcf09eb1af
[]
no_license
Shicheng-Guo/methylation2020
b77017a1fc3629fe126bf4adbb8f21f3cc9738a0
90273b1120316864477dfcf71d0a5a273f279ef9
refs/heads/master
2023-01-15T20:07:53.853771
2020-02-28T03:48:13
2020-02-28T03:48:13
243,668,721
3
1
null
null
null
null
UTF-8
R
false
false
13,175
r
S612.R
# 2017-05-10 #source("http://www.bioconductor.org/biocLite.R") #biocLite("impute") #install.packages("gplots") #install.packages("RColorBrewer") #install.packages("grDevices") library("gplots") library("RColorBrewer") library("grDevices") library("impute") gsi<-function(data){ group=names(table(colnames(data))) index=colnames(data) GSI<-c() gmaxgroup<-c() for(i in 1:nrow(data)){ gsit<-0 gmax<-names(which.max(tapply(as.numeric(data[i,]),index,function(x) mean(x,na.rm=T)))) for(j in 1:length(group)){ tmp<-(1-10^(mean(na.omit(as.numeric(data[i,which(index==group[j])])),na.rm=T))/10^(mean(na.omit(as.numeric(data[i,which(index==gmax)])))))/(length(group)-1) gsit<-gsit+tmp } gmaxgroup<-c(gmaxgroup,gmax) GSI<-c(GSI,gsit) } rlt=data.frame(region=rownames(data),group=gmaxgroup,GSI=GSI) return(rlt) } TopGSIByCategory<-function(gsi,top=150){ GSIRlt<-c() group<-names(table(gsi$group)) rank<-c(rep(top,length(group))) for (i in 1:length(group)){ subset=gsi[which(gsi$group==group[i]),] subset=subset[order(subset[,3],decreasing=T)[1:rank[i]],] GSIRlt<-rbind(GSIRlt,subset) } return(na.omit(GSIRlt)) } CvSampling<- function(Nobs=29,K=5){ rs <- runif(Nobs) id <- seq(Nobs)[order(rs)] k <- as.integer(Nobs*seq(1,K-1)/K) k <- matrix(c(0,rep(k,each=2),Nobs),ncol=2,byrow=TRUE) k[,1] <- k[,1]+1 l <- lapply(seq.int(K),function(x,k,d) list(train=d[!(seq(d) %in% seq(k[x,1],k[x,2]))], test=d[seq(k[x,1],k[x,2])]),k=k,d=id) return(l) } topgsi2bio<-function(topgsi){ cor2bed<-function(cor){ cor<-as.character(cor) a<-unlist(lapply(strsplit(cor,split=c(":")),function(x) strsplit(x,"-"))) bed<-matrix(a,ncol=3,byrow=T) return(data.frame(bed)) } bio<-data.frame(cor2bed(topgsi[,1]),topgsi[,2:3]) rownames(bio)<-topgsi[,1] colnames(bio)<-paste("V",2:6,sep="") return(bio) } rename<-function(data){ Data=data[,grep("STL|N37|ENC|SRX|age|new|centenarian|CTT|HCT|X7.T|X6.T|X6.P|RRBS.6P|X7.P|RRBS.7P",colnames(data))] colnames(Data)[grep(".",colnames(Data))]<-unlist(lapply(colnames(Data)[grep(".",colnames(Data))],function(x) unlist(strsplit(x,".hapInfo|.sorted"))[1])) colnames(Data)<-gsub("[.]","-",colnames(Data)) colnames(Data)[grep("age|new|centenarian",colnames(Data))]<-"WBC" colnames(Data)[grep("X7.T|X6.T|SRX|CTT",colnames(Data))]<-"CT" colnames(Data)[grep("N37|STL|ENC",colnames(Data))]<-as.character(saminfo[match(colnames(Data)[grep("N37|STL|ENC",colnames(Data))],saminfo[,1]),2]) colnames(Data)[grep("X6.P|RRBS.6P",colnames(Data))]<-"CCP" colnames(Data)[grep("X7.P|RRBS.7P",colnames(Data))]<-"LCP" return(Data) } frm<-function(data){ # feature reduction (WGBS,RRBS and each caterogy missing<60,Plasma missing<50%,low variation removed) # features which are missing in whole reference samples will be omit since this will caused miss-classification (N<=4,data qualitye dependent) rm1<-which(apply(data[,grep("X7.P|X6.P|.6P|.7P|NC.P",colnames(data))],1,function(x) sum(is.na(x))/length(x)>0.5)) rm2<-which(apply(data[,grep("X6.P|.6P",colnames(data))],1,function(x) sum(is.na(x))/length(x)>0.6)) rm3<-which(apply(data[,grep("X7.P|.7P",colnames(data))],1,function(x) sum(is.na(x))/length(x)>0.6)) rm4<-which(apply(data[,grep("NC.P",colnames(data))],1,function(x) sum(is.na(x))/length(x)>0.6)) rm5<-which(apply(data,1,function(x) sum(is.na(x))/length(x)>0.6)) rm<-unique(c(rm1,rm2,rm3,rm4,rm5)) return(rm) } setwd("/home/shg047/oasis/monod/hapinfo") data<-read.table("MHL4.txt",head=T,row.names=1,sep="\t") saminfo<-read.table("/home/shg047/oasis/monod/saminfo/N37Salk.saminfo",sep="\t") load("/oasis/tscc/scratch/shg047/monod/hapinfo/MHL4.RData") #load("/oasis/tscc/scratch/shg047/monod/hapinfo/Depth4.RData") bio<-read.table("/oasis/tscc/scratch/shg047/monod/hapinfo/biomarker2.txt",head=F,row.names=1) # Download from Supplementary Table rm<-frm(data) data<-data[-rm,] #depth<-depth[-rm,] # copy our biomarker form supplementary table to: /home/sguo/Dropbox/Project/methylation/monod/Manuscript/MONOD_analysis_scripts/biomarker2.txt (download from supplementary) Data<-rename(data) colon<-subset(bio,V5=="Colon") DATA<-data[match(rownames(colon),rownames(data)),] DATA<-rename(DATA) DATA<-DATA[,colnames(DATA)=="CCP"] apply(DATA,1,function(x) sum(x>0.1,na.rm=T)) TDTD<-data[match(names(sort(apply(DATA,1,function(x) sum(x>0.3,na.rm=T)),decreasing=T)[1:10]),rownames(data)),] TDTD<-rename(TDTD) # for tissue-specific biomarkers #library("impute") #library("preprocessCore") DATA<-Data[,grep("Brain|Colon|Intestine|Kidney|Liver|Lung|Pancreas|Spleen|Stomach|WBC",colnames(Data))] DATA<-DATA[match(rownames(bio),rownames(DATA)),] colnames(DATA)<-colnames(Data)[grep("Brain|Colon|Intestine|Kidney|Liver|Lung|Pancreas|Spleen|Stomach|WBC",colnames(Data))] colnames(DATA)<-unlist(lapply(colnames(DATA),function(x) unlist(strsplit(x,"[.]"))[1])) gsirlt<-gsi(DATA) for(i in names(table(colnames(DATA)))){ } apply(DATA,1,function(x) tapply(x,colnames(DATA),function(x) mean(x,na.rm=T))) topgsi<-TopGSIByCategory(gsirlt,top=500) bio<-topgsi2bio(topgsi) Bio<-bio[sample(1:nrow(bio),0.9*nrow(bio)),] # apply parts of the tissue-specific biomarkers so that we can evalate the stability DATA<-Data[match(rownames(bio),rownames(Data)),grep("Brain|Colon|Intestine|Kidney|Liver|Lung|Pancreas|Spleen|Stomach|WBC",colnames(Data))] matchrlt<-apply(DATA,2,function(x) names(table(bio$V5))[which.max(tapply(x,bio$V5,function(x) sum(x>0.1,na.rm=T)))]) for(i in names(table(bio$V5))){ acc=sum(matchrlt[grep(i,names(matchrlt))]==i)/length(grep(i,names(matchrlt))) print(c(i,acc)) } #[1] "Brain" "1" #[1] "Colon" "1" #[1] "Intestine" "1" #[1] "Kidney" "1" #[1] "Liver" "1" #[1] "Lung" "0.8" #[1] "Pancreas" "1" #[1] "Spleen" "1" #[1] "Stomach""0.666666666666667" #[1] "WBC" "1" #### Figure 5C set.seed(2) out1<-grep(".6P|X6.P",colnames(data))[sample(1:30,5)] out2<-grep(".7P|X7.P",colnames(data))[sample(1:30,5)] out3<-grep("NC.P",colnames(data))[sample(1:75,5)] test<-data[,c(out1,out2,out3)] test<-test[match(rownames(bio),rownames(test)),] # Cross-validation process Data<-data[,-c(out1,out2,out3)] # automatically select best threshold with 5-fold cross-validation for colon plasma/lung cancer/normal plasma together. input<-Data[match(rownames(bio),rownames(Data)),] set.seed(51) k=2 # split the sample to two parts, one is for train and the other is for test. acc1<-c() acc2<-c() acc3<-c() Best<-c() Samping<-CvSampling(24,k) Lnum1<-c() Lnum2<-c() Lnum3<-c() for(i in 1:k){ Num<-c() for(j in seq(0,1,0.01)){ counts1<-apply(input[,grep(".6P|X6.P",colnames(Data))[Samping[[i]]$train]],2,function(x) tapply(x,bio$V5,function(x) sum(x>j,na.rm=T))) counts2<-apply(input[,grep(".7P|X7.P",colnames(Data))[Samping[[i]]$train]],2,function(x) tapply(x,bio$V5,function(x) sum(x>j,na.rm=T))) counts3<-apply(input[,grep("NC.P",colnames(Data))[Samping[[i]]$train]],2,function(x) tapply(x,bio$V5,function(x) sum(x>j,na.rm=T))) num<-data.frame(id=j, c1=sum(apply(counts1,2,function(x) which.max(x)==2)), c2=sum(apply(counts2,2,function(x) which.max(x)==6)), c3=sum(apply(counts3,2,function(x) which.max(x)==10))) Num<-rbind(Num,num) } best<-Num[which.max(rowSums(Num[,2:4])),1] countm1<-apply(input[,grep(".6P|X6.P",colnames(Data))[Samping[[i]]$test]],2,function(x) tapply(x,bio$V5,function(x) sum(x>best,na.rm=T))) countm2<-apply(input[,grep(".7P|X7.P",colnames(Data))[Samping[[i]]$test]],2,function(x) tapply(x,bio$V5,function(x) sum(x>best,na.rm=T))) countm3<-apply(input[,grep("NC.P",colnames(Data))[Samping[[i]]$test]],2,function(x) tapply(x,bio$V5,function(x) sum(x>best,na.rm=T))) Lnum1<-c(Lnum1,c=sum(apply(countm1,2,function(x) which.max(x)==2))) Lnum2<-c(Lnum2,c=sum(apply(countm2,2,function(x) which.max(x)==6))) Lnum3<-c(Lnum3,c=sum(apply(countm3,2,function(x) which.max(x)==10))) acc1<-rbind(acc1,c(best,sum(apply(countm1,2,function(x) which.max(x)==2))/(length(Samping[[i]]$test)))) acc2<-rbind(acc2,c(best,sum(apply(countm2,2,function(x) which.max(x)==6))/(length(Samping[[i]]$test)))) acc3<-rbind(acc3,c(best,sum(apply(countm3,2,function(x) which.max(x)==10))/(length(Samping[[i]]$test)))) Best<-c(Best,best) } Best cc1<-apply(test[,grep(".6P|X6.P",colnames(test))],2,function(x) tapply(x,bio$V5,function(x) sum(x>mean(Best),na.rm=T))) cc2<-apply(test[,grep(".7P|X7.P",colnames(test))],2,function(x) tapply(x,bio$V5,function(x) sum(x>mean(Best),na.rm=T))) cc3<-apply(test[,grep("NC.P",colnames(test))],2,function(x) tapply(x,bio$V5,function(x) sum(x>mean(Best),na.rm=T))) ccc1=sum(apply(cc1,2,function(x) which.max(x)==2))/5 ccc2=sum(apply(cc2,2,function(x) which.max(x)==6))/5 ccc3=sum(apply(cc3,2,function(x) which.max(x)==10))/5 ccc1 ccc2 ccc3 ###################################################################### ################ Model Stability #################################### ###################################################################### load("/oasis/tscc/scratch/shg047/monod/hapinfo/MHL4.RData") starlt<-stability(data,bio,rep=200) save(starlt,file="starlt.RData") # starlt # [,1] [,2] [,3] [,4] # rlt 0.3605 0.8 0.8 0.8 # rlt 0.3390 0.8 1.0 1.0 senthresplot<-function(starlt){ acc<-data.frame(x=acc[,1],y=acc[,2]) acc$bin<- cut(acc[,1], c(seq(0,1,0.01))) ggplot(acc) + geom_boxplot(aes(bin, y)) } acc=starlt[,c(1,2)] senthresplot(acc) ggsave("colon-threshold-acc.pdf") acc=starlt[,c(1,3)] senthresplot(acc) ggsave("lung-threshold-acc.pdf") acc=starlt[,c(1,4)] senthresplot(acc) ggsave("normal-threshold-acc.pdf") stability<-function(data,bio,rep){ Rlt<-c() for(loop in 1:rep){ out1<-grep(".6P|X6.P",colnames(data))[sample(1:30,5)] out2<-grep(".7P|X7.P",colnames(data))[sample(1:29,5)] out3<-grep("NC.P",colnames(data))[sample(1:75,5)] test<-data[,c(out1,out2,out3)] test<-test[match(rownames(bio),rownames(test)),] Data<-data[,-c(out1,out2,out3)] # automatically select best threshold with 5-fold cross-validation for colon plasma/lung cancer/normal plasma together. input<-Data[match(rownames(bio),rownames(Data)),] k=2 acc1<-c() acc2<-c() acc3<-c() Best<-c() Samping<-CvSampling(24,k) Lnum1<-c() Lnum2<-c() Lnum3<-c() for(i in 1:k){ Num<-c() for(j in seq(0,1,0.001)){ counts1<-apply(input[,grep(".6P|X6.P",colnames(input))[Samping[[i]]$train]],2,function(x) tapply(x,bio$V5,function(x) sum(x>j,na.rm=T))) counts2<-apply(input[,grep(".7P|X7.P",colnames(input))[Samping[[i]]$train]],2,function(x) tapply(x,bio$V5,function(x) sum(x>j,na.rm=T))) counts3<-apply(input[,grep("NC.P",colnames(input))[Samping[[i]]$train]],2,function(x) tapply(x,bio$V5,function(x) sum(x>j,na.rm=T))) num<-data.frame(id=j, c1=sum(apply(counts1,2,function(x) which.max(x)==2)), c2=sum(apply(counts2,2,function(x) which.max(x)==6)), c3=sum(apply(counts3,2,function(x) which.max(x)==10))) Num<-rbind(Num,num) } best<-Num[which.max(rowSums(Num[,2:4])),1] countm1<-apply(input[,grep(".6P|X6.P",colnames(input))[Samping[[i]]$test]],2,function(x) tapply(x,bio$V5,function(x) sum(x>best,na.rm=T))) countm2<-apply(input[,grep(".7P|X7.P",colnames(input))[Samping[[i]]$test]],2,function(x) tapply(x,bio$V5,function(x) sum(x>best,na.rm=T))) countm3<-apply(input[,grep("NC.P",colnames(input))[Samping[[i]]$test]],2,function(x) tapply(x,bio$V5,function(x) sum(x>best,na.rm=T))) Lnum1<-c(Lnum1,c=sum(apply(countm1,2,function(x) which.max(x)==2))) Lnum2<-c(Lnum2,c=sum(apply(countm2,2,function(x) which.max(x)==6))) Lnum3<-c(Lnum3,c=sum(apply(countm3,2,function(x) which.max(x)==10))) acc1<-rbind(acc1,c(best,sum(apply(countm1,2,function(x) which.max(x)==2))/(length(Samping[[i]]$test)))) acc2<-rbind(acc2,c(best,sum(apply(countm2,2,function(x) which.max(x)==6))/(length(Samping[[i]]$test)))) acc3<-rbind(acc3,c(best,sum(apply(countm3,2,function(x) which.max(x)==10))/(length(Samping[[i]]$test)))) Best<-c(Best,best) } cc1<-apply(test[,grep(".6P|X6.P",colnames(test))],2,function(x) tapply(x,bio$V5,function(x) sum(x>mean(Best),na.rm=T))) cc2<-apply(test[,grep(".7P|X7.P",colnames(test))],2,function(x) tapply(x,bio$V5,function(x) sum(x>mean(Best),na.rm=T))) cc3<-apply(test[,grep("NC.P",colnames(test))],2,function(x) tapply(x,bio$V5,function(x) sum(x>mean(Best),na.rm=T))) ccc1=sum(apply(cc1,2,function(x) which.max(x)==2))/5 ccc2=sum(apply(cc2,2,function(x) which.max(x)==6))/5 ccc3=sum(apply(cc3,2,function(x) which.max(x)==10))/5 ccc1 ccc2 ccc3 rlt<-c(mean(Best),ccc1,ccc2,ccc3) Rlt<-rbind(Rlt,rlt) } return(Rlt) }
9e0b06a392cb5a7eaaa885a7e1f264ebd7c0f0f6
9f2f9ef625d991219cd1bd22c9a9daf34cb717a7
/man/diagnostic-class.Rd
6fd413aaa5c68c685401fd3a5f6f47db8cdd6749
[ "BSD-3-Clause" ]
permissive
jan-glx/gmo
0910fe3cdf5d5506281a5bc41178464f3fde70b0
a3c466c553aaa487619b7baf7e36f0c35999e262
refs/heads/master
2021-05-12T01:11:38.900509
2018-01-15T14:53:31
2018-01-15T14:53:31
117,553,351
0
0
null
2018-01-15T14:08:02
2018-01-15T14:08:02
null
UTF-8
R
false
true
958
rd
diagnostic-class.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/util.R \docType{class} \name{diagnostic-class} \alias{Diagnostic} \alias{diagnostic-class} \title{A Reference Class for diagnosing convergence.} \description{ A Reference Class for diagnosing convergence. } \section{Fields}{ \describe{ \item{\code{par_prev}}{A numeric vector, previous checked parameter value.} \item{\code{fn_prev}}{Double, previous checked function value.} \item{\code{grad_prev}}{A numeric vector, previous checked gradient value.} \item{\code{tol_rel}}{Double, relative tolerance for signaling convergence.} }} \section{Methods}{ \describe{ \item{\code{check_converge(par, fn, grad)}}{Check if the difference in parameters, function value, or gradient values reached below tolerances.} \item{\code{initialize(tol)}}{ Initializes previous checked values at 0. @param tol Tolerance threshold used for all tolerance checks. } }}
68d2ce9b5645d16ce734e43d3f6bdd8772ca569f
2e8fcc79e61ed9f80673834834fcf2abb4b8ac75
/man/getVariableIndex.Rd
d0c19e082191337831da9a286407c3248f68703f
[ "MIT" ]
permissive
nickmckay/GeoChronR
893708e6667ee898165c208d200f002063e6d83f
f37236e1fa6616f55798bbd4e1530b5b564d0f53
refs/heads/master
2023-05-24T01:32:59.690518
2023-01-17T23:16:47
2023-01-17T23:16:47
32,468,418
30
2
MIT
2023-01-19T17:46:24
2015-03-18T15:50:12
R
UTF-8
R
false
true
1,409
rd
getVariableIndex.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/lipd.manipulation.R \name{getVariableIndex} \alias{getVariableIndex} \title{Get the index of variable list} \usage{ getVariableIndex( table, var.name = NA, alt.names = var.name, ignore = NA, always.choose = FALSE, ask = TRUE, strict.search = FALSE ) } \arguments{ \item{table}{a LiPD measurement, ensemble or summary Table} \item{var.name}{string name of the variable to extract} \item{alt.names}{A vector of strings for alternative names to search for} \item{ignore}{A vector of strings of variableNames to ignore} \item{always.choose}{Force selection of the variable from a list} \item{ask}{If there is only one option, do you want to be asked whether to use it? (default = TRUE)} \item{strict.search}{Use a strict.search to look for the ageEnsemble and depth variables. TRUE(default) or FALSE.} } \value{ An integer index } \description{ Gets the index for a LiPD "variable list" } \seealso{ Other LiPD manipulation: \code{\link{createConcatenatedEnsembleMeasurementTable}()}, \code{\link{createModel}()}, \code{\link{createMultiModelEnsemble}()}, \code{\link{createSummaryTableFromEnsembleTable}()}, \code{\link{createTSid}()}, \code{\link{estimateUncertaintyFromRange}()}, \code{\link{mapAgeEnsembleToPaleoData}()}, \code{\link{pullTsVariable}()}, \code{\link{selectData}()} } \concept{LiPD manipulation}
34d622bd1d502065fda78ba4005b6e96ab36b587
f5b7db353ee4783f15f12fbb5b8fd1b36eae8bb6
/plot1.R
081aa39bf87bbe69c610b0c0a240a6f3a26f1dc5
[]
no_license
LloydNarciso/dataScienceCourse4Week4
6faf658beb3495ed96038ea35e098afaed7da10c
33bbff65fe411983cd4830d117361d54992e1eb0
refs/heads/master
2021-01-12T07:33:47.779457
2016-12-20T18:45:53
2016-12-20T18:45:53
76,979,450
0
0
null
null
null
null
UTF-8
R
false
false
547
r
plot1.R
## This first line will likely take a few seconds. Be patient! NEI <- readRDS("summarySCC_PM25.rds") SCC <- readRDS("Source_Classification_Code.rds") totalEmissions<-with(NEI,tapply(Emissions,year,sum,na.rm=TRUE)) x<-c("1999","2002","2005","2008") png(filename="plot1.png",width=720,height=480) plot(x,totalEmissions,main=expression(paste("Total ", PM[2.5], " Emissions from 1999-2008")),xlab="Year", ylab=expression(paste(PM[2.5], " Emissions (in tons)")),pch=15,cex=2,lwd=2,col="blue") lines(x,totalEmissions,type="l",col="blue") dev.off()
2bf7130413c84761821ca3e8bd5bba2f96d93e85
7daf72d1abe4b13d1e26dc46abddfebcfc42d9e8
/man/pca_count.Rd
191fdd2adcf7ae5a99956fdec23efc949ffb6460
[ "MIT" ]
permissive
farcego/rbl
6c39a7f2e63564c75860aa6a7887b2b49ffb73fb
b1cfa946b978dae09bf4d4b79267c4269e067627
refs/heads/master
2020-03-21T15:25:49.368438
2017-06-15T09:22:11
2017-06-15T09:22:11
null
0
0
null
null
null
null
UTF-8
R
false
true
544
rd
pca_count.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/funs_behavior.r \name{pca_count} \alias{pca_count} \title{Count the number of Prey Catch Attemps (PCA)} \usage{ pca_count(x) } \arguments{ \item{x}{a logical vector indicating at each timestamp if it was associated to a PCA event.} } \description{ Count the number of Prey Catch Attemps (PCA) } \details{ A continuous succession of \code{TRUE} is considered as a single PCA. } \examples{ data(exses) btt_pca <- tdrply(pca_count, "is_pca", ty = "_", obj = exses) }
bdc0674feda68af0a1008d7be978b253a71d3b8d
05c251183d6de3e1447079da895a16e3c1d9bafa
/codes/Fig1A.R
11f6b12f7f2381b1e0b41cefb48f073b57e7eb9d
[]
no_license
joycewang914/Genomic_and_Patient_Transfer_Analyasis_of_Resistant_Bacteria
42fb7d2597a5d61372253666c5447f88c05f13c3
21e74f522a23350700a068dd2359342db233bbcd
refs/heads/master
2022-11-15T22:32:58.696067
2020-07-06T08:49:06
2020-07-06T08:49:06
277,387,877
2
0
null
null
null
null
UTF-8
R
false
false
2,329
r
Fig1A.R
# Plot Fig 1A showing the prevalence of antibiotic-resistant organisms (AROs) in regional nursing facilities due to endemic spread of epidemic lineages. # load dna matrix data (MGE removed) # Fig 1B and 1C are a sample of Supplemental Figure S6. Please refer to FigS6.R for details. library(ape) library(wesanderson) mrsa = read.dna("2019-07-19_Filtered_Pathways_MRSA", format = "interleaved") vrefm = read.dna("2019-07-19_Filtered_Pathways_VREfm", format = "interleaved") vrefc = read.dna("2019-07-19_Filtered_Pathways_VREfc", format = "interleaved") ecol = read.dna("2019-07-19_Filtered_Pathways_CipREc", format = "interleaved") path_aro_clusters = list("MRSA" = mrsa, "VREfm" = vrefm, "VREfc" = vrefc, "CipREc" = ecol) path_facils = as.character(1:6) total_enrol_pt_per_facil = structure(c(133, 82, 169, 137, 55, 76), names = 1:6) path_aro_cluster_info = sapply(names(path_aro_clusters), FUN = function(x){ t(sapply(rownames(path_aro_clusters[[x]]), FUN = function(s){ info = strsplit(as.character(s), "-")[[1]]; id = info[1] pt = info[2] fac = substr(pt, 1, 1) visit = info[3] site = substr(info[4], 1, 1) cbind(paste(id, pt, visit, site, sep = "-"), id, pt, visit, site, fac) })) }) # ARO distribution by NH aro_prev_by_fac = sapply(path_aro_clusters, FUN = function(y){ pt = sapply(rownames(y), FUN = function(x){strsplit(x, "-")[[1]][2]}) fac = substr(pt, 1, 1) table(fac)/total_enrol_pt_per_facil }) # Plot barplot showing prevalence by facility nh_cols = wes_palette(name = "Darjeeling1", length(path_aro_clusters)) nh_cols[nh_cols %in% "#F2AD00"] = "lightgrey" par(mar = c(5.1, 8, 4.1, 4.1)) barplot(t(aro_prev_by_fac), col = nh_cols, border="white", font.axis=1, cex.lab = 2, cex.axis = 2, cex.names = 2, beside= T, xlab="Nursing Facility", font.lab=1, ylab = "Percentage of\ncolonized patients", yaxt = "n", ylim = c(0, 0.3)) axis(side = 2, font = 1, at = seq(0, .3, 0.15), labels = seq(0, .3*100, 15), las = 2, cex.axis = 2, cex.lab = 2) legend("top", legend = colnames(aro_prev_by_fac), fill = nh_cols, col = nh_cols, xpd = TRUE, inset = -0.2, text.font = 2, cex = 2, bty = "n", horiz = TRUE, border = NA, text.width = 3, x.intersp = 0.25)
00777bf48e9b0cd6ca14576061ccd176537aa2e4
320bb31bba3f88ad0e940553db4f7f54e0c4c920
/R/BIOMOD_Projection.R
25740e7b38a969554d13a1f2c540160b1e2f3c7d
[]
no_license
biomodhub/biomod2
519d120381332c719fc23d1a5d0a4d1030fd2a01
ee9734d7dd9455cc8b76a000f74785512a119e2f
refs/heads/master
2023-08-31T03:29:40.910990
2023-08-28T14:10:59
2023-08-28T14:10:59
122,992,854
61
21
null
2023-09-12T12:29:52
2018-02-26T15:55:28
R
UTF-8
R
false
false
31,350
r
BIOMOD_Projection.R
################################################################################################### ##' @name BIOMOD_Projection ##' @author Wilfried Thuiller, Damien Georges ##' ##' @title Project a range of calibrated species distribution models onto new environment ##' ##' @description This function allows to project a range of models built with the ##' \code{\link{BIOMOD_Modeling}} function onto new environmental data (\emph{which can ##' represent new areas, resolution or time scales for example}). ##' ##' ##' @param bm.mod a \code{\link{BIOMOD.models.out}} object returned by the ##' \code{\link{BIOMOD_Modeling}} function ##' @param proj.name a \code{character} corresponding to the name (ID) of the projection set ##' (\emph{a new folder will be created within the simulation folder with this name}) ##' @param new.env A \code{matrix}, \code{data.frame} or ##' \code{\link[terra:rast]{SpatRaster}} object containing the new ##' explanatory variables (in columns or layers, with names matching the ##' variables names given to the \code{\link{BIOMOD_FormatingData}} function to build ##' \code{bm.mod}) that will be used to project the species distribution model(s) ##' \cr \emph{Note that old format from \pkg{raster} are still supported such as ##' \code{RasterStack} objects. } ##' ##' @param new.env.xy (\emph{optional, default} \code{NULL}) \cr ##' If \code{new.env} is a \code{matrix} or a \code{data.frame}, a 2-columns \code{matrix} or ##' \code{data.frame} containing the corresponding \code{X} and \code{Y} coordinates that will be ##' used to project the species distribution model(s) ##' @param models.chosen a \code{vector} containing model names to be kept, must be either ##' \code{all} or a sub-selection of model names that can be obtained with the ##' \code{\link{get_built_models}} function ##' ##' @param metric.binary (\emph{optional, default} \code{NULL}) \cr ##' A \code{vector} containing evaluation metric names to be used to transform prediction values ##' into binary values based on models evaluation scores obtained with the ##' \code{\link{BIOMOD_Modeling}} function. Must be among \code{all} (same evaluation metrics than ##' those of \code{bm.mod}) or \code{ROC}, \code{TSS}, \code{KAPPA}, \code{ACCURACY}, ##' \code{BIAS}, \code{POD}, \code{FAR}, \code{POFD}, \code{SR}, \code{CSI}, \code{ETS}, ##' \code{HK}, \code{HSS}, \code{OR}, \code{ORSS} ##' @param metric.filter (\emph{optional, default} \code{NULL}) \cr ##' A \code{vector} containing evaluation metric names to be used to transform prediction values ##' into filtered values based on models evaluation scores obtained with the ##' \code{\link{BIOMOD_Modeling}} function. Must be among \code{all} (same evaluation metrics than ##' those of \code{bm.mod}) or \code{ROC}, \code{TSS}, \code{KAPPA}, \code{ACCURACY}, ##' \code{BIAS}, \code{POD}, \code{FAR}, \code{POFD}, \code{SR}, \code{CSI}, \code{ETS}, ##' \code{HK}, \code{HSS}, \code{OR}, \code{ORSS} ##' ##' @param compress (\emph{optional, default} \code{TRUE}) \cr ##' A \code{logical} or a \code{character} value defining whether and how objects should be ##' compressed when saved on hard drive. Must be either \code{TRUE}, \code{FALSE}, \code{xz} or ##' \code{gzip} (see Details) ##' @param build.clamping.mask (\emph{optional, default} \code{TRUE}) \cr ##' A \code{logical} value defining whether a clamping mask should be built and saved on hard ##' drive or not (see Details) ##' ##' @param nb.cpu (\emph{optional, default} \code{1}) \cr ##' An \code{integer} value corresponding to the number of computing resources to be used to ##' parallelize the single models computation ##' @param seed.val (\emph{optional, default} \code{NULL}) \cr ##' An \code{integer} value corresponding to the new seed value to be set ##' ##' @param \ldots (\emph{optional, see Details)}) ##' ##' ##' @return ##' ##' A \code{BIOMOD.projection.out} object containing models projections, or links to saved ##' outputs. \cr Models projections are stored out of \R (for memory storage reasons) in ##' \code{proj.name} folder created in the current working directory : ##' \enumerate{ ##' \item the output is a \code{data.frame} if \code{new.env} is a \code{matrix} or a ##' \code{data.frame} ##' \item it is a \code{\link[terra:rast]{SpatRaster}} if \code{new.env} is a ##' \code{\link[terra:rast]{SpatRaster}} (or several \code{\link[terra:rast]{SpatRaster}} ##' objects, if \code{new.env} is too large) ##' \item raw projections, as well as binary and filtered projections (if asked), are saved in ##' the \code{proj.name} folder ##' } ##' ##' ##' @details ##' ##' If \code{models.chosen = 'all'}, projections are done for all calibration and pseudo absences ##' runs if applicable. \cr These projections may be used later by the ##' \code{\link{BIOMOD_EnsembleForecasting}} function. \cr \cr ##' ##' If \code{build.clamping.mask = TRUE}, a raster file will be saved within the projection folder. ##' This mask values will correspond to the number of variables in each pixel that are out of their ##' calibration / validation range, identifying locations where predictions are uncertain. \cr \cr ##' ##' \code{...} can take the following values : ##' \itemize{ ## \item{\code{clamping.level} : }{a \code{logical} value defining whether \code{clamping.mask} ## cells with at least one variable out of its calibration range are to be removed from the ## projections or not ##' \item{\code{omit.na} : }{a \code{logical} value defining whether all not fully referenced ##' environmental points will get \code{NA} as predictions or not} ##' \item{\code{on_0_1000} : }{a \code{logical} value defining whether \code{0 - 1} probabilities ##' are to be converted to \code{0 - 1000} scale to save memory on backup} ##' \item{\code{do.stack} : }{a \code{logical} value defining whether all projections are to be ##' saved as one \code{\link[terra:rast]{SpatRaster}} object or several ##' \code{\link[terra:rast]{SpatRaster}} files (\emph{the default if projections are too heavy to ##' be all loaded at once in memory})} ##' \item{\code{keep.in.memory} : }{a \code{logical} value defining whether all projections are ##' to be kept loaded at once in memory, or only links pointing to hard drive are to be returned} ##' \item{\code{output.format} : }{a \code{character} value corresponding to the projections ##' saving format on hard drive, must be either \code{.grd}, \code{.img}, \code{.tif} or \code{.RData} (the ##' default if \code{new.env} is given as \code{matrix} or \code{data.frame})} ##' } ##' ##' ##' @keywords models projection ##' ##' ##' @seealso \code{\link{BIOMOD_Modeling}}, \code{\link{BIOMOD_EnsembleModeling}}, ##' \code{\link{BIOMOD_RangeSize}} ##' @family Main functions ##' ##' ##' @examples ##' library(terra) ##' ##' # Load species occurrences (6 species available) ##' data(DataSpecies) ##' head(DataSpecies) ##' ##' # Select the name of the studied species ##' myRespName <- 'GuloGulo' ##' ##' # Get corresponding presence/absence data ##' myResp <- as.numeric(DataSpecies[, myRespName]) ##' ##' # Get corresponding XY coordinates ##' myRespXY <- DataSpecies[, c('X_WGS84', 'Y_WGS84')] ##' ##' # Load environmental variables extracted from BIOCLIM (bio_3, bio_4, bio_7, bio_11 & bio_12) ##' data(bioclim_current) ##' myExpl <- terra::rast(bioclim_current) ##' ##' \dontshow{ ##' myExtent <- terra::ext(0,30,45,70) ##' myExpl <- terra::crop(myExpl, myExtent) ##' } ##' ##' # ---------------------------------------------------------------# ##' file.out <- paste0(myRespName, "/", myRespName, ".AllModels.models.out") ##' if (file.exists(file.out)) { ##' myBiomodModelOut <- get(load(file.out)) ##' } else { ##' ##' # Format Data with true absences ##' myBiomodData <- BIOMOD_FormatingData(resp.var = myResp, ##' expl.var = myExpl, ##' resp.xy = myRespXY, ##' resp.name = myRespName) ##' ##' # Create default modeling options ##' myBiomodOptions <- BIOMOD_ModelingOptions() ##' ##' # Model single models ##' myBiomodModelOut <- BIOMOD_Modeling(bm.format = myBiomodData, ##' modeling.id = 'AllModels', ##' models = c('RF', 'GLM'), ##' bm.options = myBiomodOptions, ##' CV.strategy = 'random', ##' CV.nb.rep = 2, ##' CV.perc = 0.8, ##' metric.eval = c('TSS','ROC'), ##' var.import = 3, ##' seed.val = 42) ##' } ##' ##' ##' # ---------------------------------------------------------------# ##' # Project single models ##' file.proj <- paste0(myRespName, "/proj_Current/", myRespName, ".Current.projection.out") ##' if (file.exists(file.proj)) { ##' myBiomodProj <- get(load(file.proj)) ##' } else { ##' myBiomodProj <- BIOMOD_Projection(bm.mod = myBiomodModelOut, ##' proj.name = 'Current', ##' new.env = myExpl, ##' models.chosen = 'all') ##' } ##' myBiomodProj ##' plot(myBiomodProj) ##' ##' ##' @importFrom foreach foreach %dopar% ## @importFrom doParallel registerDoParallel ##' @importFrom terra rast subset nlyr writeRaster terraOptions wrap unwrap ##' mem_info app is.factor mask ##' @importFrom utils capture.output ##' @importFrom abind asub ##' ##' @export ##' ##' ################################################################################################### BIOMOD_Projection <- function(bm.mod, proj.name, new.env, new.env.xy = NULL, models.chosen = 'all', metric.binary = NULL, metric.filter = NULL, compress = TRUE, build.clamping.mask = TRUE, nb.cpu = 1, seed.val = NULL, ...) { .bm_cat("Do Single Models Projection") ## 0. Check arguments --------------------------------------------------------------------------- args <- .BIOMOD_Projection.check.args(bm.mod, proj.name, new.env, new.env.xy , models.chosen, metric.binary, metric.filter, compress, seed.val, ...) for (argi in names(args)) { assign(x = argi, value = args[[argi]]) } rm(args) ## 1. Create output object ---------------------------------------------------------------------- proj_out <- new('BIOMOD.projection.out', proj.name = proj.name, dir.name = bm.mod@dir.name, sp.name = bm.mod@sp.name, expl.var.names = bm.mod@expl.var.names, models.projected = models.chosen, scale.models = bm.mod@scale.models, coord = new.env.xy, modeling.id = bm.mod@modeling.id) proj_out@models.out@link = bm.mod@link proj_is_raster <- FALSE if (inherits(new.env, 'SpatRaster')) { proj_is_raster <- TRUE } if (proj_is_raster) { proj_out@proj.out <- new('BIOMOD.stored.SpatRaster') } else { proj_out@proj.out <- new('BIOMOD.stored.data.frame') } ## 2. Create simulation directories ------------------------------------------------------------- nameProj <- paste0("proj_", proj.name) nameProjSp <- paste0(nameProj, "_", bm.mod@sp.name) namePath <- file.path(bm.mod@dir.name, bm.mod@sp.name, nameProj) dir.create(namePath, showWarnings = FALSE, recursive = TRUE, mode = "777") if (!do.stack) { dir.create(file.path(namePath, "individual_projections"), showWarnings = FALSE, recursive = TRUE, mode = "777") } ## 3. Define the clamping mask ------------------------------------------------------------------ if (build.clamping.mask) { cat("\n\t> Building clamping mask\n") nameMask <- paste0(nameProjSp, "_ClampingMask") MinMax <- get_formal_data(bm.mod, 'MinMax') assign(x = nameMask, value = .build_clamping_mask(new.env, MinMax)) if (output.format == '.RData') { if (proj_is_raster) { save(list = wrap(nameMask), file = file.path(namePath, paste0(nameProj, "_ClampingMask", output.format)), compress = compress) } else { save(list = nameMask, file = file.path(namePath, paste0(nameProj, "_ClampingMask", output.format)), compress = compress) } } else { writeRaster(x = get(nameMask), filename = file.path(namePath, paste0(nameProj, "_ClampingMask", output.format)), datatype = "INT2S", NAflag = -9999, overwrite = TRUE) } } ## 4. MAKING PROJECTIONS ------------------------------------------------------------------------ if (nb.cpu > 1) { if (.getOS() != "windows") { if (!isNamespaceLoaded("doParallel")) { if(!requireNamespace('doParallel', quietly = TRUE)) stop("Package 'doParallel' not found") } doParallel::registerDoParallel(cores = nb.cpu) } else { warning("Parallelisation with `foreach` is not available for Windows. Sorry.") } } if (proj_is_raster) { new.env.wrap <- wrap(new.env) # ensure parallel run compatibility } proj <- foreach(mod.name = models.chosen) %dopar% { cat("\n\t> Projecting", mod.name, "...") if (proj_is_raster) { new.env <- unwrap(new.env.wrap) # ensure parallel run compatibility } if (do.stack) { filename <- NULL } else { filename <- file.path(namePath, "individual_projections", paste0(nameProj, "_", mod.name, ifelse(output.format == ".RData" , ".tif", output.format))) } mod <- get(BIOMOD_LoadModels(bm.out = bm.mod, full.name = mod.name)) temp_workdir = NULL if (length(grep("MAXENT$", mod.name)) == 1) { temp_workdir = mod@model_output_dir } pred.tmp <- predict(mod, new.env, on_0_1000 = on_0_1000, filename = filename, omit.na = omit.na, temp_workdir = temp_workdir, seedval = seed.val, overwrite = TRUE, mod.name = mod.name) if (do.stack) { if (proj_is_raster) { return(wrap(pred.tmp)) } else { return(pred.tmp) } } else { cat(filename) return(filename) } } ## Putting predictions into the right format if (do.stack) { if (proj_is_raster) { proj <- rast(lapply(proj, unwrap)) # SpatRaster needs to be wrapped before saving names(proj) <- models.chosen proj <- wrap(proj) proj.trans <- proj } else { proj <- as.data.frame(proj) names(proj) <- models.chosen proj.trans <- proj proj <- .format_proj.df(proj, obj.type = "mod") } if (keep.in.memory) { proj_out@proj.out@val <- proj proj_out@proj.out@inMemory <- TRUE } } ## save projections proj_out@type <- .get_env_class(new.env) if (!do.stack){ saved.files = unlist(proj) } else { assign(x = nameProjSp, value = proj) saved.files <- file.path(namePath, paste0(nameProjSp, output.format)) if (output.format == '.RData') { save(list = nameProjSp, file = saved.files, compress = compress) } else { writeRaster(x = rast(get(nameProjSp)), filename = saved.files, overwrite = TRUE, datatype = ifelse(on_0_1000, "INT2S", "FLT4S"), NAflag = -9999) } } proj_out@proj.out@link <- saved.files # now that proj have been saved, it can be unwrapped if it is a SpatRaster if (proj_is_raster && do.stack) { proj.trans <- rast(proj.trans) } ## 5. Compute binary and/or filtered transformation --------------------------------------------- if (!is.null(metric.binary) | !is.null(metric.filter)) { cat("\n") saved.files.binary <- NULL saved.files.filtered <- NULL thresholds <- get_evaluations(bm.mod, full.name = models.chosen) if (!on_0_1000) { thresholds[, "cutoff"] <- thresholds[, "cutoff"] / 1000 } ## Do binary/filtering transformation for (eval.meth in unique(c(metric.binary, metric.filter))) { thres.tmp <- thresholds[which(thresholds$metric.eval == eval.meth), ] rownames(thres.tmp) <- thres.tmp$full.name thres.tmp <- thres.tmp[models.chosen, "cutoff"] cat("\n\t> Building", eval.meth, "binaries / filtered") if (!do.stack) { for (i in 1:length(proj_out@proj.out@link)) { file.tmp <- proj_out@proj.out@link[i] if (eval.meth %in% metric.binary) { file.tmp.binary <- sub(output.format, paste0("_", eval.meth, "bin", output.format), file.tmp) saved.files.binary <- c(saved.files.binary, file.tmp.binary) writeRaster(x = bm_BinaryTransformation(rast(file.tmp), thres.tmp[i]), filename = file.tmp.binary, overwrite = TRUE, datatype = "INT2S", NAflag = -9999) } if (eval.meth %in% metric.filter) { file.tmp.filtered <- sub(output.format, paste0("_", eval.meth, "filt", output.format), file.tmp) saved.files.filtered <- c(saved.files.filtered, file.tmp.filtered) writeRaster(x = bm_BinaryTransformation(rast(file.tmp), thres.tmp[i], do.filtering = TRUE), filename = file.tmp.filtered, overwrite = TRUE, datatype = ifelse(on_0_1000, "INT2S", "FLT4S"), NAflag = -9999) } } } else { if (eval.meth %in% metric.binary) { nameBin <- paste0(nameProjSp, "_", eval.meth, "bin") assign(x = nameBin, value = bm_BinaryTransformation(proj.trans, thres.tmp)) file.tmp.binary <- file.path(namePath, paste0(nameBin, output.format)) saved.files.binary <- c(saved.files.binary, file.tmp.binary) if (output.format == '.RData') { if (proj_is_raster) { assign(x = nameBin, value = wrap(get(nameBin))) } else { assign(x = nameBin, value = .format_proj.df((get(nameBin)), obj.type = "mod")) } save(list = nameBin, file = file.tmp.binary, compress = compress) } else { writeRaster(x = get(nameBin), filename = file.tmp.binary, overwrite = TRUE, datatype = "INT2S", NAflag = -9999) } } if (eval.meth %in% metric.filter) { nameFilt <- paste0(nameProjSp, "_", eval.meth, "filt") assign(x = nameFilt, value = bm_BinaryTransformation(proj.trans, thres.tmp, do.filtering = TRUE)) file.tmp.filtered <- file.path(namePath, paste0(nameFilt, output.format)) saved.files.filtered <- c(saved.files.filtered, file.tmp.filtered) if (output.format == '.RData') { if (proj_is_raster) { assign(x = nameFilt, value = wrap(get(nameFilt))) } else { assign(x = nameFilt, value = .format_proj.df((get(nameFilt)), obj.type = "mod")) } save(list = nameFilt, file = file.path(namePath, paste0(nameFilt, output.format)), compress = compress) } else { writeRaster(x = get(nameFilt), filename = file.tmp.filtered, overwrite = TRUE , datatype = ifelse(on_0_1000, "INT2S", "FLT4S"), NAflag = -9999) } } } } ### save binary/filtered file link into proj_out ---------------------------- if (!is.null(metric.binary)) { proj_out@proj.out@link <- c(proj_out@proj.out@link, saved.files.binary) } if (!is.null(metric.filter)) { proj_out@proj.out@link <- c(proj_out@proj.out@link, saved.files.filtered) } cat("\n") } ## 6. SAVE MODEL OBJECT ON HARD DRIVE ----------------------------------------------------------- ## save a copy of output object without value to be lighter nameOut <- paste0(bm.mod@sp.name, ".", proj.name, ".projection.out") if (!keep.in.memory) { proj_out <- free(proj_out) } assign(nameOut, proj_out) save(list = nameOut, file = file.path(namePath, nameOut)) .bm_cat("Done") return(proj_out) } # .BIOMOD_Projection.check.args--------------------------------------------- .BIOMOD_Projection.check.args <- function(bm.mod, proj.name, new.env, new.env.xy, models.chosen, metric.binary, metric.filter, compress, seed.val, ...) { args <- list(...) ## 1. Check bm.mod ---------------------------------------------------------- .fun_testIfInherits(TRUE, "bm.mod", bm.mod, "BIOMOD.models.out") ## 2. Check proj.name ------------------------------------------------------- if (is.null(proj.name)) { stop("\nYou must define a name for Projection Outputs") } else { dir.create(paste0(bm.mod@sp.name, '/proj_', proj.name, '/'), showWarnings = FALSE) } ## 3. Check new.env --------------------------------------------------------- .fun_testIfInherits(TRUE, "new.env", new.env, c('matrix', 'data.frame', 'SpatRaster','Raster')) if (inherits(new.env, 'matrix')) { if (any(sapply(get_formal_data(bm.mod, "expl.var"), is.factor))) { stop("new.env cannot be given as matrix when model involves categorical variables") } new.env <- data.frame(new.env) } else if (inherits(new.env, 'data.frame')) { # ensure that data.table are coerced into classic data.frame new.env <- as.data.frame(new.env) } if (inherits(new.env, 'Raster')) { # conversion into SpatRaster if (any(raster::is.factor(new.env))) { new.env <- .categorical_stack_to_terra(raster::stack(new.env), expected_levels = head(get_formal_data(bm.mod, subinfo = "expl.var")) ) } else { new.env <- rast(new.env) } } if (inherits(new.env, 'SpatRaster')) { .fun_testIfIn(TRUE, "names(new.env)", names(new.env), bm.mod@expl.var.names) new.env.mask <- .get_data_mask(new.env, value.out = 1) new.env <- mask(new.env, new.env.mask) } else { .fun_testIfIn(TRUE, "colnames(new.env)", colnames(new.env), bm.mod@expl.var.names) new.env <- new.env[ , bm.mod@expl.var.names, drop = FALSE] } which.factor <- which(sapply(new.env, is.factor)) if (length(which.factor) > 0) { new.env <- .check_env_levels(new.env, expected_levels = head(get_formal_data(bm.mod, subinfo = "expl.var"))) } ## 4. Check new.env.xy ------------------------------------------------------ if (!is.null(new.env.xy) & !inherits(new.env, 'SpatRaster')) { new.env.xy = as.data.frame(new.env.xy) if (ncol(new.env.xy) != 2 || nrow(new.env.xy) != nrow(new.env)) { stop("invalid xy coordinates argument given -- dimensions mismatch !") } } else { new.env.xy = data.frame() } ## 5. Check models.chosen --------------------------------------------------- if (models.chosen[1] == 'all') { models.chosen <- bm.mod@models.computed } else { models.chosen <- intersect(models.chosen, bm.mod@models.computed) } if (length(models.chosen) < 1) { stop('No models selected') } ## check that given models exist files.check <- paste0(bm.mod@dir.name, "/", bm.mod@sp.name, "/models/", bm.mod@modeling.id, "/", models.chosen) not.checked.files <- grep('MAXENT|SRE', files.check) if (length(not.checked.files) > 0) { files.check <- files.check[-not.checked.files] } missing.files <- files.check[!file.exists(files.check)] if (length(missing.files) > 0) { stop(paste0("Projection files missing : ", toString(missing.files))) if (length(missing.files) == length(files.check)) { stop("Impossible to find any models, might be a problem of working directory") } } ## 6. Check metric.binary & metric.filter ----------------------------------- if (!is.null(metric.binary) | !is.null(metric.filter)) { models.evaluation <- get_evaluations(bm.mod) if (is.null(models.evaluation)) { warning("Binary and/or Filtered transformations of projection not ran because of models evaluation information missing") } else { available.evaluation <- unique(models.evaluation$metric.eval) if (!is.null(metric.binary) && metric.binary[1] == 'all') { metric.binary <- available.evaluation } else if (!is.null(metric.binary) && sum(!(metric.binary %in% available.evaluation)) > 0) { warning(paste0(toString(metric.binary[!(metric.binary %in% available.evaluation)]), " Binary Transformation were switched off because no corresponding evaluation method found")) metric.binary <- metric.binary[metric.binary %in% available.evaluation] } if (!is.null(metric.filter) && metric.filter[1] == 'all') { metric.filter <- available.evaluation } else if (!is.null(metric.filter) && sum(!(metric.filter %in% available.evaluation)) > 0) { warning(paste0(toString(metric.filter[!(metric.filter %in% available.evaluation)]), " Filtered Transformation were switched off because no corresponding evaluation method found")) metric.filter <- metric.filter[metric.filter %in% available.evaluation] } } } ## 7. Check compress -------------------------------------------------------- if (compress == 'xz') { compress <- ifelse(.Platform$OS.type == 'windows', 'gzip', 'xz') } ## 9. Check output.format --------------------------------------------------- output.format <- args$output.format # raster output format if (!is.null(output.format)) { if (!output.format %in% c(".img", ".grd", ".tif", ".RData")) { stop(paste0("output.format argument should be one of '.img','.grd', '.tif' or '.RData'\n" , "Note : '.img','.grd', '.tif' are only available if you give environmental condition as a SpatRaster object")) } if (output.format %in% c(".img", ".grd", ".tif") && !inherits(new.env, "SpatRaster")) { warning("output.format was automatically set to '.RData' because environmental conditions are not given as a raster object") } } else { output.format <- ifelse(!inherits(new.env, "SpatRaster"), ".RData", ".tif") } ## 9. Check do.stack -------------------------------------------------------- do.stack <- ifelse(is.null(args$do.stack), TRUE, args$do.stack) if (!inherits(new.env, 'SpatRaster')) { if (!do.stack) { cat("\n\t\t! 'do.stack' arg is always set as TRUE for data.frame/matrix dataset") } do.stack <- TRUE } else if (do.stack) { # test if there is enough memory to work with multilayer SpatRaster capture.output({ test <- mem_info( subset(new.env, 1), n = 2 * length(models.chosen) + nlyr(new.env) ) }) if (test["needed"] >= test["available"]) { terraOptions(todisk = TRUE) } # option without capture.output but with ::: # ncopies = 2 * length(models.chosen) + nlyr(new.env) # test <- new.env@ptr$mem_needs(terra:::spatOptions(ncopies = ncopies)) # if (test[1] > test[2]) { # terraOptions(todisk = TRUE) # } } else if (output.format == "RData"){ cat("\n\t\t! 'do.stack' arg is always set as TRUE for .RData output format") do.stack <- TRUE } return(list(proj.name = proj.name, new.env = new.env, new.env.xy = new.env.xy, models.chosen = models.chosen, metric.binary = metric.binary, metric.filter = metric.filter, compress = compress, do.stack = do.stack, output.format = output.format, omit.na = ifelse(is.null(args$omit.na), TRUE, args$omit.na), do.stack = do.stack, keep.in.memory = ifelse(is.null(args$keep.in.memory), TRUE, args$keep.in.memory), on_0_1000 = ifelse(is.null(args$on_0_1000), TRUE, args$on_0_1000), seed.val = seed.val)) } ### .build_clamping_mask ------------------------------------------------------- .build_clamping_mask <- function(env, MinMax) { if (inherits(env, 'SpatRaster')) { ## raster case ------------------------------------------------------------ env <- subset(env, names(MinMax)) ## create an empty mask clamp.mask <- app(subset(env, 1), function(x) ifelse(is.na(x), NA, 0)) ref.mask <- app(subset(env, 1), function(x) ifelse(is.na(x), NA, 1)) for (e.v in names(env)) { if (!is.null(MinMax[[e.v]]$min)) { # numeric variable clamp.mask <- clamp.mask + bm_BinaryTransformation(subset(env, e.v), MinMax[[e.v]]$max) + ## pix with values outside of calib range (ref.mask - bm_BinaryTransformation(subset(env, e.v), MinMax[[e.v]]$min)) ## pix with no values (within env[[1]] area) } else if (!is.null(MinMax[[e.v]]$levels)) { # factorial variable clamp.mask <- clamp.mask + app(subset(env, e.v), function(x) { ifelse(as.character(x) %in% MinMax[[e.v]]$levels, 1, 0) }) ## pix with values outside of calib range } } } else if (is.data.frame(env) | is.matrix(env) | is.numeric(env)) { ## matrix and data.frame case --------------------------------------------- env <- as.data.frame(env) # create an empty mask clamp.mask <- rep(0, nrow(env)) for (e.v in names(MinMax)) { if (!is.null(MinMax[[e.v]]$min)) { # numeric variable clamp.mask <- clamp.mask + bm_BinaryTransformation(env[, e.v], MinMax[[e.v]]$max) + ## pix with values outside of calib range (1 - bm_BinaryTransformation(env[, e.v], MinMax[[e.v]]$min)) ## pix with no values (within env[[1]] area) } else if (!is.null(MinMax[[e.v]]$levels)) { # factorial variable clamp.mask <- clamp.mask + (env[, e.v] %in% MinMax[[e.v]]$levels) } } } else { stop("Unsupported env arg") } return(clamp.mask) }
d658b2de576625cfac341efbe61d6eda711bd867
8c47fdfcb462799c38da6124cea82a7c578a7a06
/EV/EV1215.R
632b34705829fbac81bfd590de8801309c9d0903
[]
no_license
QI0222/MA_615
c90df130a277194d08e3cbdd9f110229fcf9ea8c
adc114ed3b4bc889c21995cc527ed630ab40882d
refs/heads/master
2020-07-27T06:00:12.124158
2020-03-07T00:41:09
2020-03-07T00:41:09
208,893,881
0
1
null
null
null
null
UTF-8
R
false
false
10,157
r
EV1215.R
#research question: is there any supply for the electric vehicle charging stations? #1. EDA on existing electric vehicles #2. Are the charging stations in areas with restaurants and stores? (MAP) #3. Distance between charging stations? #4. Growth rate of the electric vehicles #5. Growth rate of the charging stations #reference:https://developer.nrel.gov/docs/transportation/alt-fuel-stations-v1/nearby-route/#csv-output-format #plots, maps, text analysis, PCA or EFA, appropriate plots, sturectured text with tables, images, links #pacman::p_load("RSocrata","httr",ggplot2,leaflet,maps,stringr,jsonlite,dplyr,tidyverse,magrittr,rjson,geosphere, #NLP,tm,RColorBrewer,wordcloud,wordcloud2,pdftools,tidytext, #SentimentAnalysis,syuzhet) library(RSocrata) library(httr) library(ggplot2) library(leaflet) library(maps) library(stringr) library(jsonlite) library(dplyr) library(tidyverse) library(magrittr) library(rjson) library(geosphere) library(NLP) library(tm) library(RColorBrewer) library(wordcloud) library(wordcloud2) library(pdftools) library(tidytext) library(SentimentAnalysis) library(syuzhet) library(usmap) library(yelpr) #Data acquisation #NY charging station df <- read.socrata( "https://data.ny.gov/resource/bpkx-gmh7.json", app_token = "LK05q1lMNPWAqZ7My1YlIGCkr", email = "hayleyformer@gmail.com", password = "Hailey07#" ) #California charging station url <-"https://developer.nrel.gov/api/alt-fuel-stations/v1.json?fuel_type=ELEC&state=CA&api_key=UI8ftsbXoXhViwIMWdzStMcwdpyZPqyhHBOpv5sP" df1 <- jsonlite::fromJSON(url,simplifyDataFrame = TRUE,flatten = TRUE) df1 <- df1$fuel_stations #All states charging station url2 <-"https://developer.nrel.gov/api/alt-fuel-stations/v1.json?fuel_type=ELEC&state=all&api_key=UI8ftsbXoXhViwIMWdzStMcwdpyZPqyhHBOpv5sP" df2 <- jsonlite::fromJSON(url2,simplifyDataFrame = TRUE,flatten = TRUE) df2 <- df2$fuel_stations #percent share of US EV sales by State g <- readxl::read_xlsx("Percent share of US EV Sales by State.xlsx") #Yelp data yelp_long <- head(df$longitude,10) yelp_lat <- head(df$latitude,10) location <- as.data.frame(cbind(yelp_long,yelp_lat)) key <- "QOk02yFuAi8h5EBi-4eq1VO88CYP_pCw-kyej_XDucODNmTPOsqubieFDm0hmLqM16sjksD8aVEHuw4F00GWoIl9tavU7T4LmRRm2wob9rJVQZ1RYcNQCAKhVRX3XXYx" yelpdata1 <- business_search(api_key = key, longitude = yelp_long[1], latitude = yelp_lat[1]) yelpdata1 <- as.data.frame(yelpdata1) #yelpdata2 <- business_search(api_key = key, longitude = yelp_long[2], latitude = yelp_lat[2]) #as.data.frame(yelpdata2) #yelpdata3 <- business_search(api_key = key, longitude = yelp_long[3], latitude = yelp_lat[3]) #as.data.frame(yelpdata3) #yelpdata4 <- business_search(api_key = key, longitude = yelp_long[4], latitude = yelp_lat[4]) #as.data.frame(yelpdata4) #yelpdata5 <- business_search(api_key = key, longitude = yelp_long[5], latitude = yelp_lat[5]) #as.data.frame(yelpdata5) #Data cleaning #choose variables to use df <- df %>% select(1,2,3,5,6,7,8,11,12,16,17,21,28,42,44,45,46) #clean the access_days_time df%<>%mutate(access_time_1 = if_else(str_detect(access_days_time,"24 hours daily"), "24 hours daily", if_else(str_detect(access_days_time,"Dealership business hours"), "Dealership business hours", if_else(str_detect(access_days_time,"24 hours"), "Office business hours", if_else(str_detect(access_days_time," MON"), "24 hours daily", "others"))))) #clean the facility type df%<>%dplyr::mutate(facility_type_1 = if_else(str_detect(facility_type,"PAY_GARAGE"), "PAY_GARAGE", if_else(str_detect(facility_type,"HOTEL"), "HOTEL", if_else(str_detect(facility_type,"CAR DEALER"), "CAR DEALER", if_else(str_detect(facility_type,"MUNI_GOV"), "GOVERNMENT", if_else(str_detect(facility_type,"COVENIENCE_STORE"), "CONVENIENCE_STORE", "others")))))) #1. EDA on existing electric vehicles #1.1 fuel type plot1 <- df %>% ggplot(aes(x=fuel_type_code))+ geom_bar(fill = "steelblue")+ geom_text(stat = 'count',aes(label = ..count..),vjust=-.5)+ theme_bw() plot1 #1.2 access time plot2 <- df %>% ggplot(aes(x=access_time_1))+ geom_bar(fill = "steelblue")+ geom_text(stat = 'count',aes(label = ..count..),vjust=-.5)+ theme_bw() plot2 #1.3 facility type fac <- as.data.frame(df$facility_type_1) fac <- na.omit(fac) names(fac) <- "facility" slices <- fac %>% group_by(facility) %>% summarise(n()) names(slices) <- c("facility","count") lbls <- c("GOVERNMENT","HOTEL","OTHERS","PAY_GARAGE") pct <- round(slices$count/sum(slices$count)*100) lbls <- paste(lbls,pct) lbls <- paste(lbls,"%",sep="") plot3 <- pie(pct,labels = lbls,main = "Pie Chart of Facility Type") #1.5 mapping #mapStates = map("state",fill = TRUE,plot = FALSE) #U.S. state map with numbers of charging stations #map1 <- leaflet(data = mapStates) %>% addTiles() %>% #addPolygons(fillColor = topo.colors(10,alpha = NULL),stroke = FALSE) number <- df2 %>% group_by(state) %>% summarise(n()) colnames(number) <- c("state","number") map1 <- plot_usmap(data = number,values = "number",color = "red")+ scale_fill_continuous( low = "white", high = "red", name = "charging station", label = scales::comma)+ theme(legend.position = "right") map1 #New York charging station map2 <- leaflet(df) %>% addTiles() %>% addMarkers(~as.numeric(longitude),~as.numeric(latitude)) map2 #CA charging station map3 <- leaflet(df1) %>% addTiles() %>% addMarkers(~as.numeric(longitude),~as.numeric(latitude)) map3 #All states charging station with clustering map4 <- leaflet(df2) %>% addTiles() %>% addMarkers( clusterOptions = markerClusterOptions() ) # charging station only for Tesla tesla <- df %>% filter(str_detect(access_days_time,"Tesla")) non_tesla <- df %>% filter(!str_detect(access_days_time,"Tesla")) icons_tesla <- awesomeIcons( icon = 'ios-close', iconColor = 'black', library = 'ion', markerColor = "green" ) icons_all <- awesomeIcons( icon = 'ios-close', iconColor = 'black', library = 'ion', markerColor = "red" ) map5 <- leaflet() %>% addTiles() %>% addAwesomeMarkers(data = tesla,lng = ~as.numeric(longitude),lat = ~as.numeric(latitude),group = "Tesla - Only",icon = icons_tesla)%>% addAwesomeMarkers(data = non_tesla,lng = ~as.numeric(longitude),lat = ~as.numeric(latitude),group = "For - All",icon = icons_all) map5%>%addLayersControl(overlayGroups = c("Tesla - Only","For - All"),options = layersControlOptions(collapsed = FALSE))%>%hideGroup("For - All") #test<- yelpdata$businesses #test_coor <- test$coordinates #test%<>%dplyr::select(name,rating,price,display_phone) #test <- dplyr::bind_cols(test_coor,test) #Growth rate of the electric vehicles g[,6] <- g[,4]/g[,2] - 1 colnames(g)[6] <- "growth" table1 <- as.data.frame(g) #Grwoth rate of the charging station #As noted previously, charging infrastructure increased by 36%–46% across these charging types for the same 100 markets from 2016 to 2017. #https://theicct.org/sites/default/files/publications/US_charging_Gap_20190124.pdf #Connected with YELP data yelpdata1$businesses.coordinates map6 <- leaflet(yelpdata1$businesses.coordinates) %>% addTiles() %>% addMarkers(~as.numeric(longitude),~as.numeric(latitude)) %>% addMarkers(lng = -73.932309, lat = 40.718037, icon = list( iconUrl = "https://img.icons8.com/pastel-glyph/64/000000/cat--v3.png", iconSize = c(75, 75) )) map6 #the place with the cat icon is the charging station. #distances between the charging station and the resutaurants around p1 <- yelpdata1$businesses.coordinates p2 <- as.data.frame(cbind(rep(40.718037,20),rep(-73.932309,20))) distance <- as.data.frame(geosphere::distHaversine(p1,p2)) colnames(distance) <- "distance for charging station CAT" #Opinion about charging station #text mining pdf_path <- "./energies-11-02174.pdf" text <- pdftools::pdf_text(pdf_path) cat(text[1]) text <- read_lines(text) #cleaning the text clean_text <- tolower(text) #make text to lower case using tolower() function clean_text <- gsub(pattern = "\\W",replace=" ", clean_text) #remove puncations clean_text <- gsub(pattern = "\\d",replace=" ", clean_text) #remove digits clean_text <- removeWords(clean_text,words = c(stopwords(),"ai")) #remove stop words clean_text <- gsub(pattern = "\\b[A-z]\\b{1}",replace=" ", clean_text) #remove single letters clean_text <- stripWhitespace(clean_text) #remove white spaces clean_text <- strsplit(clean_text," ") #split individual words and add space between them as split #word_cloud word_cloud <- unlist(clean_text) tm1 <- wordcloud(word_cloud,min.freq = 5,random.order = FALSE,rot.per = 0.2, colors = brewer.pal(5,"Dark2"),scale = c(4,0.2)) tm1 #sentiment analysis sent <- analyzeSentiment(text,language = "english") sent <- as.data.frame(sent[,1:4]) head(sent) summary(sent$SentimentGI) sent2 <- get_nrc_sentiment(text) sent3 <- as.data.frame(colSums(sent2)) sent3 <- rownames_to_column(sent3) colnames(sent3) <- c("emotion","count") tm2 <- ggplot(sent3, aes(x = emotion, y = count, fill = emotion)) + geom_bar(stat = "identity") + theme_minimal() + theme(legend.position="none", panel.grid.major = element_blank()) + labs( x = "Emotion", y = "Total Count") + ggtitle("Sentiment of Electric Vehicle") + theme(plot.title = element_text(hjust=0.5)) tm2
dabc5f96c4133eaf423434aeb5cb24058b51a732
0500ba15e741ce1c84bfd397f0f3b43af8cb5ffb
/cran/paws.management/man/ssm_delete_parameters.Rd
07a3bda2c33cb7f8160cd7f011574913c5aceac3
[ "Apache-2.0" ]
permissive
paws-r/paws
196d42a2b9aca0e551a51ea5e6f34daca739591b
a689da2aee079391e100060524f6b973130f4e40
refs/heads/main
2023-08-18T00:33:48.538539
2023-08-09T09:31:24
2023-08-09T09:31:24
154,419,943
293
45
NOASSERTION
2023-09-14T15:31:32
2018-10-24T01:28:47
R
UTF-8
R
false
true
659
rd
ssm_delete_parameters.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/ssm_operations.R \name{ssm_delete_parameters} \alias{ssm_delete_parameters} \title{Delete a list of parameters} \usage{ ssm_delete_parameters(Names) } \arguments{ \item{Names}{[required] The names of the parameters to delete. After deleting a parameter, wait for at least 30 seconds to create a parameter with the same name.} } \description{ Delete a list of parameters. After deleting a parameter, wait for at least 30 seconds to create a parameter with the same name. See \url{https://www.paws-r-sdk.com/docs/ssm_delete_parameters/} for full documentation. } \keyword{internal}
8c5b2cf84a0d4896f2d76646eca163d76ea67498
355aedf0b2b57e92c1e379727ba8c0e7a7296fa3
/process/Amniote_Database_References_Aug_2015_pre.R
02b11428082aa239f66b01188a66ba8f8fc9f03e
[]
no_license
annakrystalli/bird_trait_networks
a2be0342bd84b1bb242d50a73727379518dadac5
81c56555147a56deb14af876e93996ef56330098
refs/heads/master
2021-01-17T00:59:06.585208
2018-02-01T18:50:00
2018-02-01T18:50:00
47,277,564
1
2
null
null
null
null
UTF-8
R
false
false
377
r
Amniote_Database_References_Aug_2015_pre.R
## ---- prR1-subset ---- data <- data[data$class == "Aves",] ## ---- prR1-derive_repro.age.diff ---- add_keep.dat <- data.frame(repro.age.diff = paste(data$female_maturity_d, data$male_maturity_d, sep = "; ")) add_keep.dat[is.na(data$female_maturity_d) | is.na(data$male_maturity_d),] <- NA add_keep.vars <- "repro.age.diff"
ea99c5e50c357997fc0635587aa49561ab355c69
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
/data/genthat_extracted_code/umx/examples/umxConfint.Rd.R
51a25bdf369d9ec26d086fcf7dc1caaba851dd69
[]
no_license
surayaaramli/typeRrh
d257ac8905c49123f4ccd4e377ee3dfc84d1636c
66e6996f31961bc8b9aafe1a6a6098327b66bf71
refs/heads/master
2023-05-05T04:05:31.617869
2019-04-25T22:10:06
2019-04-25T22:10:06
null
0
0
null
null
null
null
UTF-8
R
false
false
1,307
r
umxConfint.Rd.R
library(umx) ### Name: umxConfint ### Title: Get confidence intervals from a umx model ### Aliases: umxConfint ### ** Examples require(umx) data(demoOneFactor) latents = c("G") manifests = names(demoOneFactor) m1 <- umxRAM("One Factor", data = mxData(cov(demoOneFactor), type = "cov", numObs = 500), umxPath(from = latents, to = manifests), umxPath(var = manifests), umxPath(var = latents, fixedAt = 1) ) m1 = umxConfint(m1, run = TRUE) # There are no existing CI requests... # Add a CI request for "G_to_x1", run, and report. Save with this CI computed m2 = umxConfint(m1, parm = "G_to_x1", run = TRUE) # Just print out any existing CIs umxConfint(m2) # CI requests added for free matrix parameters. User prompted to set run = TRUE m3 = umxConfint(m1, "all") # Run the requested CIs m3 = umxConfint(m3, run = TRUE) # Run CIs for free one-headed (asymmetric) paths in RAM model. # note: Deletes other existing requests, tmp = umxConfint(m1, parm = "A", run = TRUE) # Wipe existing CIs, add G_to_x1 tmp = umxConfint(m1, parm = "G_to_x1", run = TRUE, wipeExistingRequests = TRUE) ## Not run: ##D # For complex twin models, where algebras have parameters in some cells, smart might help ##D # note: only implemented for umxCP so far ##D m2 = umxConfint(m1, "smart") ## End(Not run)
cf05020c5202267f2a1a37e9b382b0f4db92904b
45f602f6af1ba44934ef8c2d928ecc90bf849b2d
/Oakland/Oakland Code.R
db0aba5771778f2f1a86ebee703ce3f5651b251b
[ "Apache-2.0" ]
permissive
Howard-Center-Investigations/homelessness-in-the-us
e1e3690178d9d5241cf393bee2b371bc39fb5f3a
989b40c105fe4c5b8a1a93b0857758c805594178
refs/heads/master
2022-11-24T14:23:15.394426
2020-07-21T19:30:55
2020-07-21T19:30:55
212,883,711
3
0
null
null
null
null
UTF-8
R
false
false
16,259
r
Oakland Code.R
## Install packages library(tidyverse) #helps with cleaning data library(janitor) library(lubridate) # Read in oakland data, read_csv is "a bit smarter" than read.csv oakdata <- read_csv("oaklanddata.csv") # Look at columns to see how each variable is interpreted (factors, characters, dates, #etc.) problem is that date was read in as a character, not a date glimpse(oakdata) # Cleaning #this makes the names lowercase, seperates the date variable base don where there is a space #changes the date character strong into a month-day-year date, and then pulls out the year #in a seperate column #didn't work :round_date(date, "month") #gives error "subcript out of bounds" oakdata <- oakdata %>% clean_names() %>% separate(datetimeinit, c("date", "time", "am_pm"), sep=" ") %>% mutate(date = mdy(date)) %>% mutate(year = year(date)) %>% mutate(month= month(date)) %>% separate(reqaddress, c("latitude", "longitude"), sep=" ") oakdata$month_yr <- format(as.Date(oakdata$date), "%Y-%m") #remove commas and parentheses oakdata$latitude <- substring(oakdata$latitude, 2,11) oakdata$longitude<- substring(oakdata$longitude, 1, 12) options(digits=11) oakdata$latitude <- as.numeric(as.character(oakdata$latitude)) options(digits=12) oakdata$longitude <- as.numeric(as.character(oakdata$longitude)) glimpse(oakdata) #Identify pertinent variables issue<- oakdata$description reqcategory<- oakdata$reqcategory #this is too messy- need to find a way to group some addresses together based on proximity #Counts/Descriptions library (plyr) library(dplyr) #count based on one variable issuecount = count(oakdata, "oakdata$description") categorycount = count(oakdata, "oakdata$reqcategory") yearcount= count(oakdata, "oakdata$year") #not including 2020 because only january and february right now completeyears <- oakdata %>% filter(year != "2020" ) monthcount = count(completeyears, "completeyears$month") #new dataframe with only homeless encampment data he_data <- oakdata %>% filter(oakdata$description == "Homeless Encampment") he_completeyears<- he_data %>% filter(year != "2020") he_year= count(he_data, "he_data$year") he_month = count(he_data, "he_data$month") he_month_yr = count(he_data, "he_data$month_yr") #many more homeless reports in july, august, sept, than jan, feb, march, april #graph data on homeless encampments over the years month_year<- he_month_yr$`he_data$month_yr` library(ggplot2) heyear<- he_year$he_data.year heyearcount<- he_year$freq plot(x=heyear, y= heyearcount, type = "b", xlab="Year", ylab="# of Homeless Encampment Reports", main="Homeless Encampment Reports: Oakland 2009-2020", xlim = c(2009, 2020), ylim = c(0, 3500), col="steelblue") library(chron) #graph data on homeless encampments by month-year date install.packages("zoo") library(zoo) he_over_month_yr <- read.zoo(he_month_yr, FUN= as.yearmon) plot (he_over_month_yr, xlab= "Month-Year", ylab= "# of Homeless Encampment Reports", main="Homeless Encampment Reports: Oakland 2009-2020", col = "steelblue") # had a hard time converting "month_yr" to date format, so I took the shortcut above # to get the graph, below are my failed attempts #as.Date(as.yearmon(he_month_yr$he_data.month_yr)) #parse_date_time(he_month_yr$he_data.month_yr, "ym") #glimpse(he_month_yr) #month_yr still in character format #mapping the data #testing out some leaflet functions #library (leaflet) #testmap <- leaflet() %>% #addTiles() %>% # Add default OpenStreetMap map tiles #setView(lng=37.813, lat=-122.288, zoom =12) #testmap #split the lat/long coordinates into seperate columns in the initial function at the #top of the script library(leaflet) #map of all homeless encampment reports he_data_map<- leaflet(data = he_data) %>% addTiles() %>% addMarkers(~longitude, ~latitude) # 2363 missing or invalud lat/lon values- may want to skim data to make sure this #sounds right he_data_map addTiles(he_data_map, urlTemplate = "//{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", attribution = NULL, layerId = NULL, group = NULL, options = tileOptions(), data = he_data) #are the (30, 140) coordinates mistakes? #removing them and the NA coordinates #only filtering out the <37 latitudes also filtered out the outlier longitudes he_data_cleaned <- he_data %>% filter(latitude > 37) #cleaned map of all homeless encampment reports he_data_map_cleaned<- leaflet(data = he_data_cleaned) %>% addTiles() %>% addMarkers(~longitude, ~latitude) he_data_map_cleaned #trying to get all the data onto one map in different colors getColor <- function(he_data_cleaned) { sapply(he_data_cleaned$year, function(year) { if(year = 2009) { "green" } else if(year = 2010) { "orange" } else { "red" } }) } getColor <- function(he_data_cleaned) { sapply(he_data_cleaned$year, function(year) { if(year = 2009) { "green" } else if(year = 2010) { "blue" } else if(year = 2011) { "orange" } else if(year = 2012) { "yellow" } else if(year = 2013) { "red" } else if(year = 2014) { "black" } else if(year = 2015) { "pink" } else if(year = 2016) { "green" } else if(year = 2017) { "white" } else if(year = 2018) { "purple" } else if(year = 2019) { "gray" } else if(year = 2020) { "brown" } }) } icons <- awesomeIcons( icon = 'ios-close', iconColor = 'black', library = 'ion', markerColor = getColor(he_data_cleaned) ) he_by_year_map<- leaflet(he_data_cleaned) %>% addTiles() %>% addAwesomeMarkers(~long, ~lat, icon=icons, label=~as.character(year)) #divide the homeless encampment data by year he_2009<- he_data_cleaned %>% filter(year == "2009") he_2010<- he_data_cleaned %>% filter(year == "2010") he_2011<- he_data_cleaned %>% filter(year == "2011") he_2012<- he_data_cleaned %>% filter(year == "2012") he_2013<- he_data_cleaned %>% filter(year == "2013") he_2014<- he_data_cleaned %>% filter(year == "2014") he_2015<- he_data_cleaned %>% filter(year == "2015") he_2016<- he_data_cleaned %>% filter(year == "2016") he_2017<- he_data_cleaned %>% filter(year == "2017") he_2018<- he_data_cleaned %>% filter(year == "2018") he_2019<- he_data_cleaned %>% filter(year == "2019") he_2020<- he_data_cleaned %>% filter(year == "2020") #Map of 2019 homeless encampments he_2019_map<-leaflet(data = he_2019) %>% addTiles() %>% addMarkers(~longitude, ~latitude) he_2019_map #heat map of 2019 homeless encampments ? #map of 2009 homeless encampments he_2009_map<- leaflet(data = he_2009) %>% addTiles() %>% addMarkers(~longitude, ~latitude) he_2009_map #Goal: create a map that shows each year of data as a layer that a user can easily control experiment_map<- leaflet() %>% addTiles() %>% addMarkers(data = he_2019, group = "2019") %>% addMarkers(data = he_2014, group = "2014") %>% addMarkers(data = he_2009, group = "2009") experiment_map experiment_map_2 <- leaflet() %>% # Base groups addTiles() %>% addProviderTiles(providers$Stamen.Toner, group = "Toner") %>% addProviderTiles(providers$Stamen.TonerLite, group = "Toner Lite") %>% # Overlay groups addCircles(~long, ~lat, ~10^mag/5, stroke = F, group = "Quakes") %>% addPolygons(data = outline, lng = ~long, lat = ~lat, fill = F, weight = 2, color = "#FFFFCC", group = "Outline") %>% # Layers control addLayersControl( baseGroups = c("OSM (default)", "Toner", "Toner Lite"), overlayGroups = c("Quakes", "Outline"), options = layersControlOptions(collapsed = FALSE) ) map #Goal: have data show up when you click and/or hover over a point #what data do i want to show up though? #Goal: match each call to a census tract by matching the lat/long values # assign each call to a census tract library(sf) library(tidycensus) library(tigris) # select only homeless encampments, longitude, latitude #he_location_data <- he_data %>% #select( latitude, longitude) #ca <- tidycensus::get_acs(state = "CA", geography = "tract", # variables = "B19013_001", geometry = TRUE) #code from stack overflow https://stackoverflow.com/questions/52248394/get-census-tract-from-lat-lon-using-tigris #ca_tracts <- tracts("CA", class = "sf") %>% #select(GEOID, TRACTCE) #bbox <- st_bbox(ca_tracts) #?st_bbox #my_points <- data.frame( #x = runif(200000, bbox[1], bbox[3]), #y = runif(200000, bbox[2], bbox[4]) #) %>% # convert the points to same CRS #st_as_sf(coords = c("x", "y"), #crs = st_crs(ca_tracts)) #my_points_tract <- st_join(my_points, ca_tracts) #another tactic #?tracts #CA FIPS code = 06 #CA<- tracts(state = "06") %>% #st_as_sf() #CA_join <- st_join(he_data, CA) #?st_join #class(he_data) #he_data_expmt <- he_location_data %>% # st_as_sf(he_location_data, coords= c("latitude", "longitude")) #another tactic #library(devtools) #he_data$census_code <- apply(he_location_data, 2, function(column) call_geolocator_latlon(c('lat'), c('long'))) #?apply #call_geolocator_latlon(he_data$latitude, he_data$longitude) #call_geolocator_latlon(lat,long) #he_data_expmt <- he_data %>% #filter(is.na(latitude) == F & is.na(longitude) == F) %>% #st_as_sf(coords= c("latitude", "longitude")) #?data.frame #lat<- he_data #he_data$census_code <- apply(he_data, 1, function(row) call_geolocator_latlon(row['latitude'], row['longitude'])) #?apply #?row #another tactic #this data frame gives the GEOID, Tract ID, etc #CA <- tracts(state = 06) #CA <- st_as_sf(CA) #plot(CA) #CA<- CA%>% # clean_names() #clean the lat lon columns #names(CA)[11] <- "latitude" #names(CA)[12] <- "longitude" #CA$latitude <- substring(CA$latitude, 2,11) #glimpse(CA) #options(digits=5) #CA$latitude <- substring(CA$latitude, 1,11) #CA$latitude <- as.numeric(as.character(CA$latitude)) #options(digits=8) #CA$longitude <- substring(CA$longitude, 1,8) #CA$longitude <- as.numeric(as.character(CA$longitude)) #now we need to match up this data with the oakland homeless data # the struggle will be getting the digits in each latitude column to match. the CA data #has 7 digits #it appears there are no matches.... #only use three digits of long/lat #he_tract_data<- merge(he_datamerge_test, CA, by = c("latitude" = "latitude", "longitude" = "longitude")) #there are matches! roughly 11,000 in the initial homeless encampment data and roughly 117 matches #trying to map the CA census tracts #back to square 1 library(tigris) library(acs) library(stringr) # to pad fips codes ?tracts tracts(state= "CA") tracts <- tracts(state = 'CA', county= '001') api.key.install(key="YOUR API KEY") #using geo locator function but with the data by year so that it will work glimpse(coord_2009) ?group_by coord_2009 <- he_2009 %>% mutate(GEOID = apply(he_2009, 1, function(row) call_geolocator_latlon(row['latitude'], row['longitude']))) #coord_2009_test<- coord_2009%>% # count("GEOID") #?lapply #coord_2009[, .(count = .N, var = sum(VAR)), by = GEOID] #coord_2009[, .N, by=.(GEOID)] coord_2010 <- he_2010 %>% mutate(GEOID = apply(he_2010, 1, function(row) call_geolocator_latlon(row['latitude'], row['longitude']))) coord_2011 <- he_2011 %>% mutate(GEOID = apply(he_2011, 1, function(row) call_geolocator_latlon(row['latitude'], row['longitude']))) coord_2012 <- he_2012 %>% mutate(GEOID = apply(he_2012, 1, function(row) call_geolocator_latlon(row['latitude'], row['longitude']))) coord_2013 <- he_2013 %>% mutate(GEOID = apply(he_2013, 1, function(row) call_geolocator_latlon(row['latitude'], row['longitude']))) coord_2014 <- he_2014 %>% mutate(GEOID = apply(he_2014, 1, function(row) call_geolocator_latlon(row['latitude'], row['longitude']))) coord_2015 <- he_2015 %>% mutate(GEOID = apply(he_2015, 1, function(row) call_geolocator_latlon(row['latitude'], row['longitude']))) coord_2016 <- he_2016 %>% mutate(GEOID = apply(he_2016, 1, function(row) call_geolocator_latlon(row['latitude'], row['longitude']))) coord_2017 <- he_2017 %>% mutate(GEOID = apply(he_2017, 1, function(row) call_geolocator_latlon(row['latitude'], row['longitude']))) coord_2018 <- he_2018 %>% mutate(GEOID = apply(he_2018, 1, function(row) call_geolocator_latlon(row['latitude'], row['longitude']))) coord_2019 <- he_2019 %>% mutate(GEOID = apply(he_2019, 1, function(row) call_geolocator_latlon(row['latitude'], row['longitude']))) coord_2020 <- he_2020 %>% mutate(GEOID = apply(he_2020, 1, function(row) call_geolocator_latlon(row['latitude'], row['longitude']))) #saving the global environment save.image(file='oakenvironment.RData') #combinging all geolocated homeless ancampments data again #checked- 10870 rows which is what the original he_data_cleaned dataset had he_with_geoid<- rbind(coord_2009, coord_2010, coord_2011, coord_2012, coord_2013, coord_2014, coord_2015, coord_2016, coord_2017, coord_2018, coord_2019, coord_2020) #get rid of the last four digits so it matches the gentrification data he_with_geoid$GEOID<- substring(he_with_geoid$GEOID, 1,11) glimpse(he_with_geoid) #Importing Gentrification data: gentdata<- read_csv("US_tr_GentDecline.csv") #filter out for oakland gentdata<- gentdata%>% filter(CountyName== "Alameda County") #add column showing percent change in number of low income people gentdata$'% expansion'<- gentdata$StrongExpansionDecline/gentdata$TotPop16 gentdata$percent_expansion<-NULL gentdatasimple<- gentdata%>% select(GEOID, StrongExpansionDecline, TotPop16, '% expansion') #all homeless encampment data matched with gentrification data- the rows without lat/long #values are tracts that didn't have any homeless encampments called in them #may want to make sure this makes sense he_gent<-full_join(gentdata, he_with_geoid, by = "GEOID") #counts of how many homeless reports happened in each GEOID geoid_counts<- count(he_gent, "GEOID") #all homeless encampment data matched with gentrification data- only GEOIDs with reports he_gent2<-left_join(he_with_geoid, gentdata, by ="GEOID") he_gent3<- inner_join(he_with_geoid, gentdata, by = "GEOID") #have to eliminate the last four numbers of the GEOID in order to macth to gentdata- #11 numbers specifies census tract, the extra four are for block(unnecessary i think) coord_2009_tract<- coord_2009 coord_2009_tract$GEOID<- substring(coord_2009_tract$GEOID, 1,11) coord_2009_count<- count(coord_2009_tract, "GEOID") names(coord_2009_count)[2] <- "freq 2009" coord_2019_tract<- coord_2019 coord_2019_tract$GEOID<- substring(coord_2019_tract$GEOID, 1,11) coord_2019_count<- count(coord_2019_tract, "GEOID") names(coord_2019_count)[2] <- "freq 2019" count_09_19<- full_join(coord_2009_count, coord_2019_count, by = "GEOID") #make NA values 0 count_09_19[is.na(count_09_19)] <- 0 #one way we could get around the baseline 0 issue: #count_09_19[is.na(count_09_19)] <- 0.00000000000000000000001 count_09_19$'change in calls'<- count_09_19$`freq 2019`-count_09_19$`freq 2009` count_09_19$'%change in calls'<- (count_09_19$'change in calls'/count_09_19$`freq 2009`) #table with only certain variables #so only 113/361 census tracts have reported calls #there is one census tract that shows up in our data but not in the gent data #seems like a mistake: 06013353001 should probably be "060013353001" to follow th pattern #manually fix it ? he_gent_combined<- full_join(count_09_19, gentdatasimple, by ="GEOID") names(he_gent_combined)[6] <- "StrongExpDec" #some findings- homeless calls in only 25 tracts in 2009 -> 113 tracts in 2019 #(including the same 25) plot(he_gent_combined$`%change in calls`, he_gent_combined$`% expansion`, xlab = "% Change in Homeless Encampment Calls 2009-2019", ylab = "% Change in Low Income Pop 2000-2016") ggplot(he_gent_combined, aes(x = '% change in calls', y = '% expansion')) +geom_point() #hard to read a lot form this map because so much has changed over the 2009-2019 period- #encampment calls have increased in every single tract, and it's hard to distill that #data in this scatterplot and with only 2 years
4a1a8d4a0bda9aba700c52cf02cf8e845b910572
c23216384c211a86d6fa2d04211d54da21693978
/Submissions/me2685@columbia.edu/SIS_Challenge.R
5b8633423856ef46a13166d4ab4aec885654f1d8
[]
no_license
SportsInfoSolutions/AnalyticsChallenge2020
e49a239fbb00ba38d4e192726d2b64c62eded5c5
cd12a9caaec5d49f8f12c805d381d9619bd298d4
refs/heads/master
2023-06-05T03:18:33.617477
2021-06-24T20:54:41
2021-06-24T20:54:41
274,144,333
17
62
null
2020-07-22T14:03:21
2020-06-22T13:27:05
HTML
UTF-8
R
false
false
15,746
r
SIS_Challenge.R
library(tidyverse) library(readr) library(RCurl) library(glue) pbp <- read_csv("Data/AnalyticsChallenge2020Data.csv", na = c("NULL", "NA")) # Clean Data pbp_clean <- pbp %>% # Remove kneels and spikes filter(!str_detect(PlayDesc, "kneel") & !str_detect(PlayDesc, "spike")) %>% # Classify Scrambles using SIS data (more reliable than GSIS-provided play descriptions) left_join(pbp %>% group_by(GameID, EventID) %>% summarize(run = max(if_else(str_detect(EventType, "designed run"), 1, 0)), pass = max(if_else(str_detect(EventType, "pass"), 1, 0)), pass_rush = max(if_else(IsRushing == 1, 1, 0)), PlayDesc = paste(unique(PlayDesc), collapse = '-')) %>% filter((run == 1 & pass_rush == 1)|str_detect(PlayDesc, "scramble")) %>% select(GameID, EventID) %>% mutate(scramble = 1)) %>% mutate(scramble = replace_na(scramble, 0), event_type = if_else(str_detect(EventType, "pass") | scramble == 1, "dropback", "designed run"), yardline_100 = if_else(SideOfField == "Oppo", StartYard, 100 - StartYard), tech_side = case_when(TechniqueName %in% c("0", "Off Ball") ~ TechniqueName, TechniqueName == "Outside" ~ as.character(glue("{SideOfBall}OLB")), TRUE ~ as.character(glue("{SideOfBall}{TechniqueName}"))), in_designed_gap = case_when(event_type == "dropback" ~ NA_real_, RunDirection == "Middle" ~ if_else(tech_side %in% c("0", "L1", "R1", "L2i", "R2i"), 1, 0), RunDirection == "Right A Gap" ~ if_else(tech_side %in% c("0", "L1", "L2", "L2i"), 1, 0), RunDirection == "Left A Gap" ~ if_else(tech_side %in% c("0", "R1", "R2", "R2i"), 1, 0), RunDirection == "Right Off-Tackle B Gap" ~ if_else(tech_side %in% c("L2", "L3", "L4", "L4i"), 1, 0), RunDirection == "Left Off-Tackle B Gap" ~ if_else(tech_side %in% c("R2", "R3", "R4", "R4i"), 1, 0), RunDirection == "Right Off-Tackle C Gap" ~ if_else(tech_side %in% c("L4", "L5", "L7", "L6"), 1, 0), RunDirection == "Left Off-Tackle C Gap" ~ if_else(tech_side %in% c("R4", "R5", "R7", "R6"), 1, 0), RunDirection == "Right D Gap" ~ if_else(tech_side %in% c("L6", "L9", "LOLB"), 1, 0), RunDirection == "Left D Gap" ~ if_else(tech_side %in% c("R6", "R9", "ROLB"), 1, 0)), gap_force = if_else(UsedDesignedGap == 0 & in_designed_gap == 1, 1, 0), success = if_else(EPA > 0, 1, 0), position_group = case_when(TechniqueName %in% c("7", "Outside", "9", "6", "5") ~ "Edge", TechniqueName == "Off Ball" ~ TechniqueName, TRUE ~ "iDL"), dl_tackle = if_else((SoloTackle == 1 | AssistedTackle == 1) & position_group %in% c("Edge", "iDL") & (SackOnPlay == 0 | is.na(SackOnPlay)), 1, 0)) # pbp_clean %>% # filter(event_type == "designed run" & UsedDesignedGap == 0) %>% # mutate(TimeLeft = glue("{floor(TimeLeft/60)}:{TimeLeft - floor(TimeLeft/60)*60}")) %>% # select(Week, OffensiveTeam, Quarter, TimeLeft, Down, ToGo, RunDirection) %>% # distinct() # # Look at pressure rates from edge players vs interior players DEDT <- pbp_clean %>% filter (event_type == "dropback" & IsRushing == 1) %>% group_by(PlayerId) %>% summarise(Player = paste(unique(Name), collapse = '-'), Position = paste(unique(RosterPosition), collapse = '-'), RushSnaps = n(), Pressure = sum(Pressure), PressureRate = Pressure/RushSnaps, meanEPA = mean(EPA), EdgeRate = sum(if_else(position_group == "Edge", 1, 0))/RushSnaps, EPA = sum(EPA)) %>% ungroup() %>% filter(RushSnaps >= 100) %>% mutate(dl_pos = as.factor(if_else(EdgeRate >= 0.5, "Edge", "iDL"))) DEDT %>% ggplot(aes(x = PressureRate, fill = dl_pos)) + geom_density(alpha = 0.5) + scale_fill_manual(values = c("red", "blue")) + scale_y_continuous(limits = c(0, 15), expand = c(0, 0)) + scale_x_continuous(labels = scales::percent_format(accuracy = 1), limits = c(0, 0.23), expand = c(0, 0)) + labs(x = "Pressure Rate", y = "Density", title = "Distribution of Player Pressure Rates by Position Group", fill = "Position Group") + theme_bw() + theme(legend.position = c(0.915, 0.885), axis.title.x = element_text(size = 14), axis.title.y = element_blank(), axis.text.x = element_text(size = 12, margin = margin(5, 0, 10, 0)), axis.text.y = element_blank(), axis.ticks.y = element_blank(), plot.title = element_text(size = 18, hjust = 0.5, face = "bold", margin = margin(b = 8, unit = "pt")), plot.subtitle = element_text(size = 14, hjust = 0.5, face = "italic", margin = margin(b = 16, unit = "pt")), plot.margin = unit(c(0.5, 0.5, 0.5, 0.5), "cm")) #Look at pressure rates by technique - league wide techs <- pbp_clean %>% filter(event_type == "dropback" & IsRushing == 1) %>% group_by(tech_side) %>% summarise(RushSnaps = n(), Pressure = sum(Pressure), PressureRate = Pressure/RushSnaps, meanEPA = mean(EPA), EPA = sum(EPA)) %>% ungroup() tech_names <- c("LOLB", "L9","L6", "L7", "L5", "L4", "L4i", "L3", "L2", "L2i", "L1", "0", "R1", "R2i", "R2", "R3", "R4i", "R4", "R5", "R7", "R6", "R9", "ROLB") techs %>% filter(tech_side != "Off Ball") %>% ggplot(aes(x = tech_side, y = PressureRate)) + geom_bar(stat = "identity", fill = "steelblue") + scale_x_discrete(limits = tech_names, expand = c(0.025, 0)) + scale_y_continuous(limits = c(0, 0.13), expand = c(0, 0)) + #scale_x_continuous(limits = c(-5, 5)) + labs(x = "Technique", y = "Pressure Rate", title = "Pressure Rate by DL Technique") + theme_bw() + theme(axis.title = element_text(size = 14), axis.text.x = element_text(size = 11, margin = margin(5, 0, 10, 0)), axis.text.y = element_text(size = 12, margin = margin(0, 5, 0, 10)), plot.title = element_text(size = 18, hjust = 0.5, face = "bold", margin = margin(b = 8, unit = "pt")), plot.subtitle = element_text(size = 14, hjust = 0.5, face = "italic", margin = margin(b = 16, unit = "pt")), plot.margin = unit(c(0.5, 0.5, 0.5, 0.5), "cm")) # Create Dataframe of Pass plays - Scrambles dfpass <- pbp_clean %>% filter(event_type == "dropback" & scramble == 0) %>% mutate(edge_pressure = if_else(position_group == "Edge" & Pressure == 1, 1, 0), idl_pressure = if_else(position_group == "iDL" & Pressure == 1, 1, 0)) %>% group_by(GameID, EventID) %>% summarise(Quarter = mean(Quarter), TimeLeft = mean(TimeLeft), Down = mean(Down), ToGo = mean(ToGo), StartYard = mean(yardline_100), Completion = mean(Completion), OffensiveYardage = mean(OffensiveYardage), EPA = mean(EPA), success = mean(success), Touchdown = mean(Touchdown), PressureOnPlay = mean(PressureOnPlay), PassBreakupOnPlay = mean(PassBreakupOnPlay), SackOnPlay = mean(SackOnPlay), dl_tackle = max(dl_tackle), edge_p = max(edge_pressure), idl_p = max(idl_pressure)) %>% mutate(pressure_type = case_when(edge_p == 1 & idl_p == 1 ~ "Both", edge_p == 1 ~ "Edge", idl_p == 1 ~ "iDL", edge_p == 0 & idl_p == 0 & PressureOnPlay == 1 ~ "Other", TRUE ~ "No Pressure")) %>% select(-edge_p, -idl_p) %>% na.omit() #Look at EPA distributions by Pressure Type dfpass %>% filter(pressure_type != "Other") %>% ggplot(aes(x = EPA, fill = pressure_type)) + geom_density(alpha = 0.5) + scale_fill_manual(values = c("red", "blue", "green", "yellow")) + scale_y_continuous(expand = c(0, 0)) + scale_x_continuous(limits = c(-5, 5), expand = c(0, 0)) + labs(x = "EPA", y = "Density", title = "Distribution of EPA by Pressure Type", fill = "Pressure Type") + theme_bw() + theme(legend.position = c(0.915, 0.885), axis.title.x = element_text(size = 14), axis.title.y = element_blank(), axis.text.x = element_text(size = 12, margin = margin(5, 0, 10, 0)), axis.text.y = element_blank(), axis.ticks.y = element_blank(), plot.title = element_text(size = 18, hjust = 0.5, face = "bold", margin = margin(b = 8, unit = "pt")), plot.subtitle = element_text(size = 14, hjust = 0.5, face = "italic", margin = margin(b = 16, unit = "pt")), plot.margin = unit(c(0.5, 0.5, 0.5, 0.5), "cm")) + facet_wrap(~pressure_type) #Kolmogorov-Smirnov Test, cannot reject null hyptohesis that two samples come from the same distribution ks.test(Pressures$EPA[Pressures$pressure_type == "Edge"], Pressures$EPA[Pressures$pressure_type == "iDL"]) #Independent Sammples T-Test, cannot reject null hypothesis that the two sample means are equal t.test(Pressures$EPA[Pressures$pressure_type == "Edge"], Pressures$EPA[Pressures$pressure_type == "iDL"]) #Create dataframe of run plays dfrun <- pbp_clean %>% filter(event_type == "designed run") %>% group_by(GameID, EventID) %>% mutate(in_designed_gap = max(in_designed_gap)) %>% summarise(Quarter = mean(Quarter), TimeLeft = mean(TimeLeft), Down = mean(Down), ToGo = mean(ToGo), StartYard = mean(yardline_100), OffensiveYardage = mean(OffensiveYardage), EPA = mean(EPA), success = mean(success), Touchdown = mean(Touchdown), RunDirection= paste(unique(RunDirection), collapse = '-'), UsedDesignedGap = paste(unique(UsedDesignedGap), collapse = '-'), in_designed_gap = paste(unique(in_designed_gap), collapse = '-'), gap_force = max(gap_force), dl_tackle = max(dl_tackle), PlayDesc = paste(unique(PlayDesc), collapse = '-')) #Look at whether gap forces have a significant effect on run plays dfrun %>% na.omit() %>% ggplot(aes(x = as.factor(gap_force), y = EPA)) + geom_boxplot() ks.test(dfrun$EPA[dfrun$gap_force ==1], dfrun$EPA[dfrun$gap_force == 0]) t.test(dfrun$EPA[dfrun$gap_force ==1], dfrun$EPA[dfrun$gap_force == 0]) #We can conclude gap forces have no significant effect on the outcome of run plays #Look at whether DL tackles have a significant effect on run plays with tackles by other position groups # or runner out of bounds dfrun %>% filter(Touchdown == 0) %>% na.omit() %>% ggplot(aes(x = as.factor(dl_tackle), y = EPA)) + geom_boxplot() ks.test(dfrun$EPA[dfrun$dl_tackle ==1], dfrun$EPA[dfrun$dl_tackle == 0 & dfrun$Touchdown == 0]) t.test(dfrun$EPA[dfrun$dl_tackle ==1], dfrun$EPA[dfrun$dl_tackle == 0 & dfrun$Touchdown == 0]) #We can conclude that a DL tackle has a significant effect on the outcome of run plays #Compare distribution of EPA and Offensive Yards Gained and success rate #of plays with a defender in the run gap and plays without dfrun %>% ggplot(aes(x = EPA, fill = as.factor(gap_force))) + geom_density(alpha = 0.5) + scale_fill_manual(values = c("red","blue")) dfrun %>% ggplot(aes(x = OffensiveYardage, fill = in_designed_gap)) + geom_density(alpha = 0.5) + scale_fill_manual(values = c("red","blue")) dfrun %>% ggplot(aes(x = EPA, fill = as.factor(dl_tackle))) + geom_density(alpha = 0.5) + scale_fill_manual(values = c("red","blue")) # The most successful run type is when the offense targets an unoccupied gap and is able to run # through that gap dfrun %>% group_by(in_designed_gap, UsedDesignedGap) %>% summarize(runs = n(), epa = mean(EPA, na.rm = T), sr = mean(success)) #Fit a linear model to determine the effects of pressures, pass breakups on pass plays #Control for TDs + Downs + Yardline passmodel <- lm(EPA ~ PassBreakupOnPlay + PressureOnPlay + Touchdown + as.factor(Down) + StartYard + ToGo, data = dfpass) PressureValue <- as.numeric(passmodel$coefficients["PressureOnPlay"]) PbuValue <- as.numeric(passmodel$coefficients["PassBreakupOnPlay"]) #Fit a linear model to determine the effects of DL tackles on run plays #Control for TDs + Downs + Yardline runmodel <- lm(EPA ~ dl_tackle + Touchdown + as.facor(Down) + StartYard + ToGo, data = dfrun) TackleValue <- as.numeric(runmodel$coefficients["dl_tackle"]) pbp_clean$dEPA <- 0 for (i in 1:nrow(pbp_clean)){ if(pbp_clean$event_type[i] == "dropback" & pbp_clean$scramble[i] == 0) { pbp_clean$dEPA[i] <- pbp_clean$Pressure[i] * PressureValue + pbp_clean$PassBreakup[i] * PbuValue } else if (pbp_clean$event_type[i] == "designed run") { pbp_clean$dEPA[i] <- pbp_clean$SoloTackle[i] * TackleValue + (pbp_clean$AssistedTackle[i] * TackleValue)/2 } else { pbp_clean$dEPA[i] <- 0 } } pbp_clean$dEPA <- pbp_clean$dEPA * -1 TechValues <- pbp_clean %>% group_by(TechniqueName) %>% summarise(Snaps = n(), dEPA = sum(dEPA), dEPA100 = (dEPA/Snaps)*100) %>% ungroup() TalentDistributions <- pbp_clean %>% group_by(TechniqueName, Name, PlayerId) %>% summarise(Snaps = n(), dEPA = sum(dEPA), dEPA100 = (dEPA/Snaps)*100) %>% ungroup() %>% filter(Snaps >= 20) TalentDistributions %>% ggplot(aes(x = dEPA100, fill = TechniqueName)) + geom_density(alpha = 0.5) + facet_wrap(~TechniqueName) TalentDistributions %>% ggplot(aes(x = dEPA, fill = TechniqueName)) + geom_density(alpha = 0.5) + facet_wrap(~TechniqueName) TechValues %>% filter(TechniqueName != "Off Ball") %>% ggplot(aes(x = TechniqueName, y = dEPA100)) + geom_bar(stat = "identity", fill = "steelblue") + scale_x_discrete(limits = c("0","1","2","2i","3","4i","4","5","6","7","9","Outside")) + #scale_x_continuous(limits = c(-5, 5)) + labs(x = "Technique", y = "dEPA/100", title = "dEPA per 100 Snaps by DL Technique") + theme_bw() + theme(axis.title = element_text(size = 14), axis.text.x = element_text(size = 11, margin = margin(5, 0, 10, 0)), axis.text.y = element_text(size = 12, margin = margin(0, 5, 0, 10)), plot.title = element_text(size = 18, hjust = 0.5, face = "bold", margin = margin(b = 8, unit = "pt")), plot.subtitle = element_text(size = 14, hjust = 0.5, face = "italic", margin = margin(b = 16, unit = "pt")), plot.margin = unit(c(0.5, 0.5, 0.5, 0.5), "cm"))
cdcbcaea478db72bec1acd36b47ca1abbf5c3dd3
3a268ed108e371a7e5039a60b29a26e0c5c2a78e
/R/crossplot.R
e83d96b6a6310a6207c23a0702404c4c4fc3e966
[]
no_license
ChandlerLutz/crossplotr
1b0608b0cb09f5d86a1f4928a049f8e7e103a148
80e4407aed1e447a3672063f9332650234b94cf6
refs/heads/master
2021-01-12T06:37:10.985067
2018-12-16T22:09:31
2018-12-16T22:09:31
77,396,652
1
0
null
null
null
null
UTF-8
R
false
false
7,249
r
crossplot.R
## c:/Dropbox/Rpackages/crossplotr/R/plot_basic.R ## Chandler Lutz ## Questions/comments: cl.eco@cbs.dk ## $Revisions: 1.0.0 $Date: 2016-12-26 #' Create a basic cross-sectional plot using standard evaluation #' of the variable names #' #' @param data the data to be plotted #' @param x.var string with the x axis variable #' @param y.var string with the y axis variable #' @param size.var string with the size (weighting) variable. Defaults #' to \code{NULL} #' @param shapes.var string with the shapes (different shapes for #' different) points variable. Defaults to \code{NULL} #' @param label.var string with the names of the points that can be #' used with \code{geom_text} or \code{geom_text_repel} #' @param control.vars a character vector with the names of variables #' that will be used as controls via the Frisch–Waugh–Lovell #' theorem. The result will be a plot (an AV Plot) and statistics #' where the variables in \code{control.vars} are partialed #' out. These variables must be present in the original #' dataset. Note: if \code{control.vars} is set, an attribute will #' be added to the returned plot and will be named #' \code{control.vars} #' @param title string with the the title for plot #' @param xlabel string with the xlabel. Defualts to \code{NULL} #' @param ylabel string with the ylabel #' @param shapes numeric vector with the shapes of the points. For #' shape options, see #' \url{http://www.cookbook-r.com/Graphs/Shapes_and_line_types/} #' @param colors character vector with the colors for different #' points. Defaults to \code{c("blue", "red", "green")} #' @param points.alpha \code{numeric(1)} indicating the alpha to be #' applied to the points. Default value is \code{1}. Setting #' \code{points.alpha = 0.7} is helpful when plotting labels with #' the points #' @return a \code{ggplot2} plot with the cross-sectional output #' @examples #' data(mtcars) #' crossplot(mtcars, x.var = "mpg", y.var = "hp", size.var = "wt", #' shapes.var = "cyl") #' ##Control for (partial out) qsec #' p <- crossplot(mtcars, x.var = "hp", y.var = "mpg", size.var = "wt", #' shapes.var = "cyl", control.vars = "qsec") #' print(p) #' p$control.vars #' @export crossplot <- function(data, x.var, y.var, size.var = NULL, shapes.var = NULL, label.var = NULL, control.vars = NULL, title = NULL, xlabel = NULL, ylabel = NULL, shapes = c(1, 2, 0, 5, 6), colors = c("blue", "red", "darkgreen"), points.alpha = 1) { ##Make sure data is a dataframe if (!is.data.frame(data)) stop("Error: data is not a data frame") data <- as.data.frame(data) ##Make sure x.var, y.var, size.var, shapes.var, label.var, and control.vars ##are character strings if (!is.character(x.var) || !is.character(y.var)) stop("Error: x.var and y.var need to be character strings") if (!is.null(size.var) && !is.character(size.var)) stop("Error: size.var needs to be a character string") if (!is.null(shapes.var) && !is.character(shapes.var)) stop("Error: shapes.var needs to be a character string") if (!is.null(label.var) && !is.character(label.var)) stop("Error: shapes.var needs to be a character string") if (!is.null(control.vars) && !is.character(control.vars)) stop("Error: control.vars needs to be a character vector") ##if xlabel or ylabel are null, use the x and y variable names if (is.null(xlabel)) xlabel <- x.var if (is.null(ylabel)) ylabel <- y.var ##Only complete cases for the variables of interest -- see utils.R data <- data_no_na_values(data) ##If necessary, update x and y using control.vars and the ##Frisch–Waugh–Lovell thm if (!is.null(control.vars)) { if (!(control.vars %in% names(data))) stop("Error: each member of control.vars needs to be in data") if (is.null(size.var)) { ##Not weighted data[[x.var]] <- residuals(lm(data[, x.var] ~ data[, control.vars])) data[[y.var]] <- residuals(lm(data[, y.var] ~ data[, control.vars])) } else { ##Weighted data[[x.var]] <- residuals(lm(data[, x.var] ~ data[, control.vars], weights = data[, size.var])) data[[y.var]] <- residuals(lm(data[, y.var] ~ data[, control.vars], weights = data[, size.var])) } } ##Update shapes.var and factor ordering to make sure the bottom-positioned ##legend has space if (!is.null(shapes.var)) { if (is.factor(data[[shapes.var]])) { ##factor -- retain the levels fact.levels <- levels(data[[shapes.var]]) %>% as.character } else { fact.levels <- data[[shapes.var]] %>% unique %>% as.character } fact.levels <- stringr::str_trim(fact.levels) data[[shapes.var]] <- factor(paste0(stringr::str_trim(data[[shapes.var]]), " "), levels = paste0(fact.levels, " ")) } ##Do the basic plot if (is.null(label.var)) { p <- ggplot(data, aes_string(x.var, y.var)) } else { p <- ggplot(data, aes_string(x.var, y.var, label = label.var)) } ##Depending on shapes.var is set if (!is.null(shapes.var)) { p <- p + geom_point(aes_string(size = size.var, color = shapes.var, shape = shapes.var), alpha = points.alpha) } else if (is.null(shapes.var)) { p <- p + geom_point(aes_string(size = size.var), shape = 1, alpha = points.alpha) } ##The aestetics of the plot p <- p + background_grid(minor='none') + ##theme_bw() + ##The colors -- black and red scale_colour_manual(values = colors) + ##The size of the shapes -- range from 2 to 20 and remove legend scale_size_continuous(range = c(2, 20), guide = "none") + ##For shapes across the metros scale_shape_manual(values = shapes) + labs(x = xlabel, y = ylabel) ##If necessary, add the title if (!is.null(title)) { p <- p + ggtitle(title) } p <- p + ##remove legend title and add other aesthetics to the legend theme(legend.text = element_text(size = 16), legend.title = element_blank(), ##legend.background = element_rect(fill="gray90", ## size=.5,linetype="dotted"), legend.background = element_rect(color="black", size=.5,linetype="solid"), panel.grid.minor = element_blank()) + ##make symbols in legend bigger. see ##http://stackoverflow.com/a/20416049/1317443 guides(colour = guide_legend(override.aes = list(size=6))) ##Add control.vars as an attribute to p if (!is.null(control.vars)) { p$control.vars <- control.vars } else { p$control.vars <- NA } return(p) }
5864f9a28afd673765a5118d193c832ab9dfbef0
fa2ed649ad6cda9eaa3a2fc3a89b30a6e31ef8a8
/single_cell_RNA_sequencing/QC.R
91ad580b47169d4de199bddb86149deca64ce846
[]
no_license
boxiangliu/onek1k_phase1
984095b5d4f419adecc8093080773493b363cb1f
d91eecb08ff1f7693712274de39d87a5215a7131
refs/heads/main
2023-09-01T17:12:16.981311
2021-10-13T08:11:08
2021-10-13T08:11:08
null
0
0
null
null
null
null
UTF-8
R
false
false
10,672
r
QC.R
# Script information ------------------------------------------------------ #' title: Quality control for Onek1k data #' author: Jose Alquicira Hernandez #' date: 2019/05/20 #' description: Removes outlier cells based on the expression of mitochondrial #' gene expression, number of UMIs, and genes detected per cell. Data is read #' from multiple directories and integrated to create a single gene expression #' matrix. A Seurat object is created and quality control is applied to remove #' outlier cells based on number of genes, counts, and mitochondrial expression. #' For the percentage of mitochondrial gene expression, Cells that deviate 2 negative #' and 3 positive SDs are considered as outliers and removed. For the total #' number of UMIs and features (genes) per cell, only the low threshold is applied. #' Doublets are filtered out based on demuxlet results prior QC. # Import libraries -------------------------------------------------------- # Primary library("tidyverse") library("here") library("dsLib") library("data.table") # Secondary library("Seurat") library("bestNormalize") # Set output -------------------------------------------------------------- output <- set_output("2019-06-16", "QC") # Read data --------------------------------------------------------------- # Input directory input <- file.path("", "share", "ScratchGeneral", "annsen", "data", "experimental_data", "CLEAN", "OneK1K_scRNA") # Get file names for all pools samples <- list.dirs(input, full.names = FALSE, recursive = FALSE) %>% str_subset("OneK1K_scRNA_Sample") # rename pools pools <- samples %>% str_split("_") %>% map(~ .[3]) %>% unlist() %>% str_remove("Sample") # Create helper function to read data readData <- function(dirSample, pool){ # Input dirSample <- file.path(input, dirSample, "outs", "filtered_gene_bc_matrices", "hg19") # Read file x <- Read10X(data.dir = dirSample, gene.column = 2) # Assign pool id to barcode colnames(x) <- paste0(colnames(x),"-", pool) x } # Read gene expression matrices inicio("Reading gene expression data") data <- map2(samples, pools, readData) fin() # Get gene and cell counts data %>% map(dim) %>% reduce(rbind) %>% as.data.frame() %>% set_names(c("genes", "cells")) %>% mutate(pool = paste0("pool_",pools)) -> geneCellInfo # Save data summary per pool write_delim(geneCellInfo, path = here(output, "pool_genes_cells.txt"), delim = "\t") # Get gene intersection from all pools data %>% map(row.names) %>% reduce(intersect) -> geneIntersection # Validate that all genes are shared among all pools and in the same order cat("\nAre all genes shared among all pools?\n") data %>% map(row.names) %>% map_lgl(~all(geneIntersection == .)) %>% all() %>% cat("\n") # The intersection of all gene names is equal to the number of genes # in each pool. Therefore, all genes are shared among all btches. # All gene names are in the same order in all matrices. # Create pool info inicio("Creating metadata") pmap(list(geneCellInfo$pool, geneCellInfo$cells), rep) %>% unlist() -> poolInfo data %>% map(colnames) %>% unlist() %>% data.frame(row.names = ., pool = poolInfo) -> poolInfo fin() # Merge cells into a single gene expression matrix inicio("Integrating pools") data <- do.call(cbind, data) fin() # Create Seurat object inicio("Creating Seurat object") data <- CreateSeuratObject(data, project = "onek1k", meta.data = poolInfo) fin() inicio("Saving pre-QC metadata") saveRDS(data@meta.data, file = here(output, "preQC_metadata.RDS")) fin() # Keep singlets ----------------------------------------------------------- # Keep singlets only as determined by demuxlet inicio("Extracting singlets") path <- file.path("data", "singlets", "barcodes_assigned_to_ppl.txt") singlets <- fread(file = here(path), data.table = FALSE) singlets$id <- paste(str_remove(singlets$BARCODE, "-.*$"), str_remove(singlets$batch, "sample"), sep = "-") i <- colnames(data) %in% singlets$id table(i) data <- data[,i] fin() # Add individul information to metadata inicio("Adding individual metadata") i <- singlets$id %in% colnames(data) singlets <- singlets[i,] singlets %>% `rownames<-`(NULL) %>% column_to_rownames("id") %>% select(-BARCODE, -batch) -> singlets data <- AddMetaData(data, metadata = singlets, col.name = "individual") levs <- fct_drop(data@meta.data$pool) i <- levs %>% levels() %>% str_split("_") %>% map(2) %>% flatten_chr() %>% as.integer() %>% order() data$pool <- factor(levs, levels = levels(levs)[i]) fin() inicio("Saving pre-QC metadata after doublet removal") saveRDS(data@meta.data, file = here(output, "preQC_singlets_metadata.RDS")) fin() # QC ---------------------------------------------------------------------- # Get percentage expression of mitochondrial and ribosomal genes data <- PercentageFeatureSet(data, pattern = "^MT-", col.name = "percent.mt") # Extract metadata meta.data <- data@meta.data # Define QC metrics to evaluate to remove outliers metricsLabels <- list("% Mitochondrial gene expression", "Number of UMIs", "Number of features") metrics <- list("percent.mt", "nCount_RNA", "nFeature_RNA") names(metrics) <- metrics # Create function to get the cutoffs based on normalized data getCutoffs <- function(object, group, metric, lowSD = 3, highSD = 2){ # Normalize QC metric across pools res <- object %>% split(.[[group]]) %>% # Split data by pool map(~pull(., !!sym(metric))) %>% # Extract pool information only map(quietly(orderNorm)) %>% # Transform to a normal distribution map("result") # Extract results from `orderNorm` # Extract higher threshold based on `lowSD` standard deviations from the mean res %>% map(~mean(.$x.t) + sd(.$x.t) * highSD) -> higher # Extract lower threshold based on `highSD` standard deviations from the mean res %>% map(~mean(.$x.t) - sd(.$x.t) * lowSD) -> lower # Transform Z-scores to original distributions higherTransform <- map2(res, higher, predict, inverse = TRUE) lowerTransform <- map2(res, lower, predict, inverse = TRUE) # Bind results and merge into a tibble higherTransform <- bind_cols(higherTransform) %>% gather(key = !!sym(group), value = higher) lowerTransform <- bind_cols(lowerTransform) %>% gather(key = !!sym(group), value = lower) # Combine lower and higher thresholds into a single tibble cutoffs <- bind_cols(higherTransform, lowerTransform) %>% gather(key = "type", value = metric, c(2,4)) %>% select(-2) # Combine lower and higher Z-score thresholds into a single tibble higher <- bind_cols(higher) %>% gather(key = group, value = higher) lower <- bind_cols(lower) %>% gather(key = group, value = lower) cutoffsTrans <- bind_cols(higher, lower) %>% gather(key = "type", value = metric, c(2,4)) %>% select(-2) # Extract original and Z-score distributions res %>% map(~.[c("x", "x.t")]) %>% # Extract original and transformed distributions map(as.data.frame) %>% # Bind into a data.frame map(`names<-`, c(metric, paste0(metric, "_norm"))) %>% # Rename columns bind_rows(.id = group) -> res # Combine distributions across pools # Returns: # - cutoffs: A data.frame containing the group (pool), type of threhold (higher or lower), and the value # - normCutoffs: Normalized cutoffs # - trans: A data.frame including the original and the normalized distribution by group (pool) list(cutoffs = as.data.frame(cutoffs), normCutoffs = as.data.frame(cutoffsTrans), trans = res) } # Get cutoffs inicio("Obtaining cutoffs across all pools") cutoffs <- map(metrics, ~getCutoffs(meta.data, "pool", .)) names(cutoffs) <- names(metrics) fin() # Filter data ------------------------------------------------------------- # Get a list of cutoffs by pool and metric # Sets Inf higher cutoffs for "nCount_RNA" and "nFeature_RNA" setHighCutoff <- function(x, inf = TRUE){ x %>% map("cutoffs") %>% map(spread, key = "type", value = "metric", 3) -> x if(inf){ x <- x %>% map(~mutate(.x, higher = Inf)) } x %>% map(~split(., .["pool"])) } cutoffsBypool <- setHighCutoff(cutoffs[c("nCount_RNA", "nFeature_RNA")]) cutoffsBypool <- append(cutoffsBypool, setHighCutoff(cutoffs[c("percent.mt")], inf = FALSE)) findOutliers <- function(cutoff, metric, group){ # Iterate for each value in `group` variable and filter data based on # corresponding filters. Data for each value in group is stored in `res` list res <- map(names(cutoff), function(val){ meta.data %>% rownames_to_column("barcode") %>% filter(UQ(as.name(group)) == !!quo(val)) -> subMeta lower <- subMeta %>% filter(!!sym(metric) < cutoff[[val]]$lower) higher <- subMeta %>% filter(!!sym(metric) > cutoff[[val]]$higher) list(lower = lower, higher = higher) %>% bind_rows(.id = "type") }) # Combine res %>% map(bind_rows) } # Get outliers inicio("Extracting outliers") res <- map2(cutoffsBypool, names(cutoffsBypool), findOutliers, group = "pool") fin() outliers <- res %>% map(bind_rows) %>% bind_rows(.id = "origin") %>% distinct(barcode, .keep_all = TRUE) # Get number of outliers by QC metric and type of cutoff outliers %>% group_by(type, origin) %>% summarise(n = n()) # Get number of outliers by QC metric outliers %>% group_by(origin) %>% summarise(n = n()) # Filter data inicio("Removing outliers") data <- data[,!colnames(data) %in% outliers$barcode] fin() # Set latent variable ----------------------------------------------------- b1 <- levels(data@meta.data$pool)[1:33] latent <- as.factor(ifelse(data@meta.data$pool %in% b1, "b1", "b2")) meta.data.latent <- data.frame(latent, row.names = colnames(data)) data <- AddMetaData(data, meta.data.latent) # Save data --------------------------------------------------------------- inicio("Saving results") saveRDS(data, file = here(output, "QC.RDS")) saveRDS(outliers, file = here(output, "outliers.RDS")) saveRDS(cutoffs, file = here(output, "cutoffs.RDS")) saveRDS(data@meta.data, file = here(output, "QC_metadata.RDS")) fin() # Session info ------------------------------------------------------------ print_session(here(output))
488a8b93da1c3030816f44ce0e31d3f90ac138e6
c7a896607481d06dd0aac96dddbd9d36e822ac8d
/tests/testthat/test-import-competitions.R
8ad278da64c42c896914e83f48c8eaf3e996e52a
[]
no_license
IsaacVerm/penalty
49a046cb5939e693935fdcf45bf7bc5c4f24f3f2
3f00f72f9fbd1b3632a58f7163171d4d89e683be
refs/heads/master
2021-03-30T21:18:30.662954
2018-03-23T09:09:21
2018-03-23T12:43:41
124,901,887
0
0
null
null
null
null
UTF-8
R
false
false
982
r
test-import-competitions.R
context("get_competitions") test_that("returns response succesfully", { response <- get_competitions() expect_equal(response$status_code, 200) expect_is(response, "response") }) context("extract_competition_ids") test_that("returns list", { response <- get_competitions() ids <- extract_competition_ids(response, "Premier League") expect_is(ids, "list") }) test_that("returns ids labelled by season", { response <- get_competitions() ids <- extract_competition_ids(response, "Premier League") id_regex <- "\\d{1,2}" label_regex <- "\\d{4}\\/\\d{2}" season_ids <- ids[["season"]] season_labels <- names(season_ids) expect_match(season_ids, id_regex) expect_match(season_labels, label_regex) }) test_that("returns competition id", { response <- get_competitions() ids <- extract_competition_ids(response, "Premier League") id_regex <-"\\d{1}" competition_id <- ids[["competition"]] expect_match(competition_id, id_regex) })
9cc43e425225b0b0b15010269bd44138ed825648
ac961f7c20e60c955720e0d93483b4d92ce01726
/unsorted_pantherJson2df.R
dd2c0b9a504a44d8c2c426f49117e409c5b13253
[]
no_license
mengchen18/RFunctionCollection
01b2936ea794297a87cf277ef0f583d02a1bb4ac
222d22fc8f12a622af01b91711a66c6e9da08be8
refs/heads/master
2022-05-24T17:49:05.385208
2022-05-17T12:58:42
2022-05-17T12:58:42
127,109,330
1
0
null
null
null
null
UTF-8
R
false
false
1,633
r
unsorted_pantherJson2df.R
pantherJson2df <- function(js) { getfixwidth <- function(x) { if (is.null(x)) x <- NA x } einfo <- function(v, cat) { c(GO_group = cat, GO_level = getfixwidth(v$term$level), GO_ID = getfixwidth(v$term$id), GO_Desc = getfixwidth(v$term$label), N_reference = getfixwidth(v$number_in_reference), N_observed = getfixwidth(v$input_list$number_in_list), N_expected = getfixwidth(v$input_list$expected), Fold_enrichment = getfixwidth(v$input_list$fold_enrichment), Direction = getfixwidth(v$input_list$plus_minus), Q_value = getfixwidth(v$input_list$pValue), Genes = getfixwidth(paste(unlist(v$input_list$mapped_id_list), collapse = ";")) ) } ii <- js$overrepresentation$group lt <- lapply(seq_along(ii), function(i) { x <- ii[[i]][[1]] if (!is.null(names(x))) r <- einfo(x, cat = i) else { r <- sapply(x, einfo, cat = i) r <- t(r) } r }) sapply(lt, dim) tab <- do.call(rbind, lt) tab <- as.data.frame(tab, stringsAsFactors = FALSE) numcol <- c("GO_group", "GO_level", "N_reference", "N_observed", "N_expected", "Fold_enrichment", "Q_value") tab[numcol] <- lapply(tab[numcol], as.numeric) attr(t, "tool_release_date") <- js$overrepresentation$tool_release_date attr(t, "data_version_release_date") <- js$overrepresentation$data_version_release_date attr(t, "test_type") <- js$overrepresentation$test_type attr(t, "correction") <- js$overrepresentation$correction attr(t, "annotation_type") <- js$overrepresentation$annotation_type tab }
846f2c95c57c83d158eae5d780ae452009de01e9
3a4c4c729d37c10c6db2d4de24a7d8cb8115949b
/R/get_attrs_desc.R
46b18ad61a6db92113eb8f4c17b1562704704e6f
[ "MIT" ]
permissive
twang2218/pmap
9155e2b5591e3fc100200734b24b11b0006a8c4f
1cd62ff0b2c02faff3b2e20cc0e5c98dff871582
refs/heads/master
2021-11-25T16:24:07.288289
2021-10-31T16:02:08
2021-11-02T08:46:04
116,099,299
19
3
NOASSERTION
2021-11-02T08:46:05
2018-01-03T06:16:51
R
UTF-8
R
false
false
1,802
r
get_attrs_desc.R
#' @title Get an attribute key-pair string from an object #' @usage get_attrs_desc(object) #' @param object Given object, can be `list`, `matrix`, or `data.frame` #' @description Get an attribute list string from an object #' @examples #' print(df) #' # id name is_manager #' # 1 1 Jane FALSE #' # 2 2 John FALSE #' # 3 3 Eric FALSE #' # 4 4 Selena TRUE #' get_attrs_desc(df) #' # [1] "id: 1\nname: Jane\nis_manager: FALSE" #' # [2] "id: 2\nname: John\nis_manager: FALSE" #' # [3] "id: 3\nname: Eric\nis_manager: FALSE" #' # [4] "id: 4\nname: Selena\nis_manager: TRUE" #' @export get_attrs_desc <- function(object) { cls <- class(object) # Get attribute names # `names()` can only support `list` and `data.frame`; # and `colnames()` cannot support `list`. attrs.name <- NULL if (inherits(object, "list")) { attrs.name <- names(object) } else { attrs.name <- colnames(object) } if (any(is.null(attrs.name)) || any(is.na(attrs.name)) || length(attrs.name) == 0) { return("") } # Get attributes key-pair # `matrix` do not support `object[[name]]`, so it has to be treated specially. attrs <- NULL if (inherits(object, "matrix")) { attrs <- sapply( attrs.name, function(name) { paste0(name, ": ", object[, name]) } ) } else { attrs <- sapply( attrs.name, function(name) { paste0(name, ": ", object[[name]]) } ) } # Combine attributes key-pairs to a single string contains the list # `paste()` is only works for columns oriented direction, so `apply()` # is used for `matrix` and `data.frame` if (inherits(attrs, c("matrix", "data.frame"))) { apply(attrs, 1, paste, collapse = "\n") } else { paste(attrs, collapse = "\n") } }
bec599c49867ebca72deffeee00b680956e006d5
096fe210156cd34fec1743fc8be582d3903721cb
/man/print.striprawdata.Rd
a8009db3c7f113b9830e5d7f44cd802c08931874
[]
no_license
Lifebrain/metagam
43d383fcaa331562a0899651fd9468708c188af0
37d9f75a3cc97322d0ae2957e0fdeaa49ef54dfc
refs/heads/master
2023-09-01T07:34:58.376500
2023-05-05T18:06:03
2023-05-05T18:06:03
235,595,959
8
2
null
2022-01-24T10:18:37
2020-01-22T14:54:25
R
UTF-8
R
false
true
432
rd
print.striprawdata.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/summary_strip_rawdata.R \name{print.striprawdata} \alias{print.striprawdata} \title{Print method for striprawdata} \usage{ \method{print}{striprawdata}(x, ...) } \arguments{ \item{x}{Object of class \code{striprawdata}.} \item{...}{Other arguments.} } \value{ The function invisibly returns its argument. } \description{ Print method for striprawdata }
15d22b232fffec1a93d83dd5d8635c5f7c3e3d2a
9e758a1fd686a06c99eccf25e02bf736640531c7
/R/quotas_errors.R
bbc15bccea731ba1675ff08ad6081676c61d6787
[]
no_license
addixvietnam/googleAnalyticsR_v0.4.2
2873c59bd23c76a06deaa036d676e6675c275869
d60ff8f8c6f6748b1fc985b9b079ac6b4738f8b3
refs/heads/master
2020-08-26T12:54:05.693373
2019-10-23T09:28:49
2019-10-23T09:28:49
217,016,500
0
0
null
null
null
null
UTF-8
R
false
false
1,319
r
quotas_errors.R
default_project_message <- function(){ is_default_project <- getOption("googleAuthR.client_id") %in% c("289759286325-da3fr5kq4nl4nkhmhs2uft776kdsggbo.apps.googleusercontent.com", "289759286325-42j8nmkeq5n9v9eb1kiuj2i97v9oea1f.apps.googleusercontent.com", "201908948134-rm1ij8ursrfcbkv9koc0aqver84b04r7.apps.googleusercontent.com", "201908948134-cjjs89cffh3k429vi7943ftpk3jg36ed.apps.googleusercontent.com") if(is_default_project){ myMessage("Default Google Project for googleAnalyticsR is now set. This is shared with all googleAnalyticsR users. \n If making a lot of API calls, please: \n 1) create your own Google Project at https://console.developers.google.com \n 2) Activate the Google Analytics Reporting API \n 3) set options(googleAuthR.client_id) and options(googleAuthR.client_secret) \n 4) Reload the package.", level = 3) } } error_check <- function(x){ if(is.error(x)){ if(grepl("insufficient tokens for quota",error.message(x))){ default_project_message() warning("The Google Project ", getOption("googleAuthR.client_id") ," has run out of quota (typically 50,000 API calls per day)") } stop(error.message(x)) } x }
68d68df1aaac0d776f1c9740fd39f032f7074a98
319c8effd49600b5796cd1759063b0b8f10aeac1
/workspace/crispr/data_P101SC17051084-01-B1-7/cdf.r.2018052114
c902896223d896a607453359ffdd755792934900
[]
no_license
ijayden-lung/hpc
94ff6b8e30049b1246b1381638a39f4f46df655c
6e8efdebc6a070f761547b0af888780bdd7a761d
refs/heads/master
2021-06-16T14:58:51.056045
2021-01-27T02:51:12
2021-01-27T02:51:12
132,264,399
1
1
null
null
null
null
UTF-8
R
false
false
1,697
2018052114
cdf.r.2018052114
#!/usr/bin/env Rscript library(grid) library(ggplot2) args<-commandArgs(T) data = read.table(args[1],header=TRUE,row.names=1) pdf(args[2],width=12,height=21) grid.newpage() pushViewport(viewport(layout = grid.layout(3, 1))) vplayout <- function(x, y) viewport(layout.pos.row = x, layout.pos.col = y) df <- data.frame(x = c(data$mKO293RGFPPos.1,data$mKO293RGFPNeg.1,data$mKO293Rtotal.1),g = gl(3,labels =c('mKO293RGFPPos.1','mKO293RGFPNeg.1','mKO293Rtotal.1'), length(data$mKO293RGFPPos.1))) a<-ggplot(df, aes(log10(x),colour = g))+stat_ecdf(geom = "step",pad=FALSE)+scale_x_continuous("log10 Number of reads per sgRNA",limits=c(0,4))+scale_y_continuous("Cumulative percentage of mKO library",breaks=0.1*(0:10),labels=scales::percent) df <- data.frame(x = c(data$mKO293RGFPPos.2,data$mKO293RGFPNeg.2,data$mKO293Rtotal.2),g = gl(3,labels =c('mKO293RGFPPos.2','mKO293RGFPNeg.2','mKO293Rtotal.2'), length(data$mKO293RGFPPos.1))) b<-ggplot(df, aes(log10(x),colour = g))+stat_ecdf(geom = "step",pad=FALSE)+scale_x_continuous("log10 Number of reads per sgRNA",limits=c(0,4))+scale_y_continuous("Cumulative percentage of mKO library",breaks=0.1*(0:10),labels=scales::percent) df <- data.frame(x = c(data$mKO293RGFPPos.3,data$mKO293RGFPNeg.3,data$mKO293Rtotal.3),g = gl(3,labels =c('mKO293RGFPPos.3','mKO293RGFPNeg.3','mKO293Rtotal.3'), length(data$mKO293RGFPPos.1))) c<-ggplot(df, aes(log10(x),colour = g))+stat_ecdf(geom = "step",pad=FALSE)+scale_x_continuous("log10 Number of reads per sgRNA",limits=c(0,4))+scale_y_continuous("Cumulative percentage of mKO library",breaks=0.1*(0:10),labels=scales::percent) print(a, vp = vplayout(1,1)) print(b, vp = vplayout(2,1)) print(c, vp = vplayout(3,1))
618abbb80952d420fad609d3dee369be0db53927
4dfb7d79f898a0bb8819129b1c34ad7e2c75d352
/Untitled.r
0b406b598d3b806ce687e65c124d85a61e700e1e
[]
no_license
AmandaJunqueira/gittutorial
080147e0472722941dae305beff2631b9273ed26
b242f87980e7f3f160f610d92d6b5a70d6d190eb
refs/heads/master
2021-01-02T04:48:05.774199
2020-02-10T11:50:25
2020-02-10T11:50:25
239,494,927
0
0
null
null
null
null
UTF-8
R
false
false
13
r
Untitled.r
bla bla <- 1;
da257424fbb07c060066307f7b6a423b0602e342
200d05f1571ea8ddbbc37ced7eb926d43d571f5a
/man/build_model_objects.Rd
d0f2be47e0c2e2fbd4d4e4e36c8fd6053708122e
[]
no_license
STAT545-UBC-hw-2018-19/hw07-shreeramsenthi
0982b633c94d8c4ebfd40acada3ae6ad11fd268e
a71f1a1e3bd20fc120a8eaa0c995c322ff52035f
refs/heads/master
2020-04-05T06:01:21.970231
2018-11-15T08:22:27
2018-11-15T08:22:27
null
0
0
null
null
null
null
UTF-8
R
false
true
587
rd
build_model_objects.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/build_model_objects.R \name{build_model_objects} \alias{build_model_objects} \title{Build list of model objects} \usage{ build_model_objects(formulas, data, model = stats::lm, ...) } \arguments{ \item{formulas}{List of model formulas} \item{data}{Dataframe with variables corresponding to the components of `formulas`} \item{model}{Function that generates model objects from formulas} \item{...}{args to be passed to `model`} } \value{ A list of model objects } \description{ Build list of model objects }
170f671cfb5209469a974d45329e973230534857
ab84adde7680f319f025396f156adb7d1df66b65
/data-raw/ucdp_acd.R
e9d82a15516badadd070a9cb0d04595fd790b405
[]
no_license
Louis8102/peacesciencer
9492d44c0749ef484611003e1c7518293a4d73c4
cc6f9b6130779b451a1300a7b199bc87904fb5b2
refs/heads/master
2023-04-15T11:30:23.807519
2021-04-28T14:56:46
2021-04-28T14:56:46
null
0
0
null
null
null
null
UTF-8
R
false
false
1,998
r
ucdp_acd.R
library(tidyverse) ucdp_acd <- readxl::read_excel("~/Dropbox/data/ucdpprio/acd/ucdp-prio-acd-201.xlsx") # I'mma select just what I want ucdp_acd %>% select(conflict_id, year, gwno_a, gwno_a_2nd, gwno_b, gwno_b_2nd, incompatibility, intensity_level, type_of_conflict:ep_end_date) -> ucdp_acd # Oof, I hate how UCDP does this. Alas, let's do it. I'd think this work. # conflict_id == 420, 252, and 412 should be a nice trial balloon to how well this works. # conflict_id == 218 = Kashmir. Also a good trial balloon for how well I'm capturing recurring conflicts and conflicts that span years. # conflict_id == 11345 = South Sudan, which has no end date. Also a good trial balloon. ucdp_acd %>% mutate(gwno_a = strsplit(as.character(gwno_a), ",")) %>% unnest(gwno_a) %>% mutate(gwno_a_2nd = strsplit(as.character(gwno_a_2nd), ",")) %>% unnest(gwno_a_2nd) %>% mutate(gwno_b = strsplit(as.character(gwno_b), ",")) %>% unnest(gwno_b) %>% mutate(gwno_b_2nd = strsplit(as.character(gwno_b_2nd), ",")) %>% unnest(gwno_b_2nd) -> ucdp_acd ucdp_acd %>% mutate_at(vars("start_date", "start_date2", "ep_end_date"), ~lubridate::ymd(.)) %>% mutate_at(vars("gwno_a", "gwno_a_2nd", "gwno_b", "gwno_b_2nd"), ~as.numeric(.)) -> ucdp_acd save(ucdp_acd, file="data/ucdp_acd.rda") # Here is where I fiddle with things... ucdp_acd %>% mutate(gwcode = gwno_a) %>% bind_rows(., ucdp_acd %>% mutate(gwcode = gwno_a_2nd)) %>% bind_rows(., ucdp_acd %>% mutate(gwcode = gwno_b)) %>% bind_rows(., ucdp_acd %>% mutate(gwcode = gwno_b_2nd)) %>% filter(!is.na(gwcode)) %>% mutate(sidea = case_when(gwcode == gwno_a ~ 1, gwcode == gwno_a_2nd ~ 1, TRUE ~ 0)) %>% select(conflict_id, year, gwcode, sidea, everything()) %>% arrange(year, conflict_id) filter(type_of_conflict == 2) %>% summary ucdp_acd %>% filter(type_of_conflict %in% c(1, 3)) %>% summary ucdp_acd %>% filter(conflict_id == 11345) %>% data.frame
f2f5fc93757815f4209a102649c8f0c8fd75b86a
fc087468a9a228a59f819285eb0fc4c2b726934c
/week 9 notes.R
61f7ee3753ca5df4b783f6253225872719ce15e7
[]
no_license
jmsahakian/R_DAVIS_in_class_project
16475f15c78bb20ffb27d61bcd01feb04fc9f468
312481656b104706c692c59c501e658ff020eca3
refs/heads/master
2020-11-25T05:17:13.101369
2020-05-01T02:33:35
2020-05-01T02:33:35
228,517,141
0
0
null
2019-12-17T02:36:09
2019-12-17T02:36:09
null
UTF-8
R
false
false
1,667
r
week 9 notes.R
#Week 9 Notes #Date Times using 'lubridate' package #load packages library(tidyverse) library(lubridate) nyf1 <- read_csv("data/raw_data/2015_NFY_solinst.csv", skip = 12) sample_dates <- c("07-15-2019", "12-24-2018", "03-07-2013", "04-04-2019") sample_dates <- as.Date(sample_dates, format = "%m-%d-%Y") dt <- c("07-15-2019 14:32:09", "12-24-2018 12:40:01") dt <- as.POSIXct(dt, format = "%m-%d-%Y %H:%M:%OS") ?as.POSIXct dt #have to originally rerun dt dt <- as.POSIXct(dt, format = "%m-%d-%Y %H:%M:%OS", tz = "GMT") dt #sometimes you need to explicit tell R Studio which package to use lubridate:: dates_lub <- mdy(sample_dates) sample_dates2 <- c("5A06A17 14:22", "8A17A13 06:33") sample_dates2_lub <- mdy_hm(sample_dates2, tz = "GMT") sample_dates2_lub head(nfy1) #automically converted the date and time varibles #typically do not want tidyversie to do these conversions #want to force tidyverse to see these fields as characters nyf1 <- read_csv("data/raw_data/2015_NFY_solinst.csv", skip = 12, col_types = "ccidd") head(nyf1) #quick way to make a new column nyf1$Datetime <- paste(nyf1$Date, nyf1$Time, sep = " ") head(nyf1) nyf1$Datetime2 <- ymd_hms(nyf1$Datetime, tz = "GMT") tz(nyf1$Datetime2) load("data/raw_data/mauna_loa_met_2001_minute.rda") #RDS has only one object and RDA has multiple objects summary(mloa_2001) #will need to use the paste function to create the dates variables we want mloa_2001$Datetime <- paste0(mloa_2001$year, "-", mloa_2001$month, "-", mloa_2001$day, " ", mloa_2001$hour24, ":", mloa_2001$min) head(mloa_2001) mloa_2001$Datetime <- ymd_hm(mloa_2001$Datetime, tz = "HST") tz(mloa_2001$Datetime)
ef9a13e39da1e578edc10c5ee772bf28b27581fd
98f35573ae5ccec324f57f5752e5798c82445ca2
/inst/predictive/predictive.R
3958d5777368992fb23e3988a0c17e9e7f92b36b
[]
no_license
cran/AOV1R
fd23065a2b8649d10695ebefe289cba930c751ca
230941f1c4d8b55a83e4aadf2946d97b65f86d93
refs/heads/master
2023-01-07T07:59:10.998185
2020-11-10T09:00:08
2020-11-10T09:00:08
312,225,640
0
0
null
null
null
null
UTF-8
R
false
false
3,590
r
predictive.R
library(AOV1R) nsims <- 1000 test <- logical(nsims) for(i in 1:nsims){ dat <- simAV1R(I=2, J=3, mu=10, sigmab=1, sigmaw=1) fit <- aov1r(y ~ group, dat) pred <- predict(fit) newy <- simAV1R(I=1, J=1, mu=10, sigmab=1, sigmaw=1)$y test[i] <- newy > pred[1] && newy < pred[2] } mean(test) # unbalanced nsims <- 1000 test <- logical(nsims) for(i in 1:nsims){ dat <- simAV1R(I=3, J=4, mu=10, sigmab=1, sigmaw=1)[-c(1,2),] fit <- aov1r(y ~ group, dat) pred <- predict(fit) newy <- simAV1R(I=1, J=1, mu=10, sigmab=1, sigmaw=1)$y test[i] <- newy > pred[1] && newy < pred[2] } mean(test) n <- 20000 Z <- rnorm(n) I <- 6; J <- 4 U2b <- rchisq(n, I-1) U2w <- rchisq(n, I*(J-1)) nsims <- 1000 test <- logical(nsims) for(i in 1:nsims){ dat <- simAV1R(I=I, J=J, mu=10, sigmab=1, sigmaw=1) fit <- aov1r(y ~ group, dat) pivots <- AOV1R:::pivotal0(fit, Z, U2b, U2w) # sims <- numeric(n) # for(j in 1:n){ # sims[j] <- simAV1R(I=1, J=1, # mu=pivots$G_mu[j], # sigmab=sqrt(max(0,pivots$G_sigma2b[j])), # sigmaw=sqrt(pivots$G_sigma2w[j]))$y # } sims <- rnorm(n, pivots$G_mu, sqrt(pivots$G_sigma2b+pivots$G_sigma2w)) pred <- quantile(sims, c(0.025, 0.975)) newy <- simAV1R(I=1, J=1, mu=10, sigmab=1, sigmaw=1)$y test[i] <- newy > pred[1] && newy < pred[2] } mean(test) # 0.99 avec la 1ère méthode, pour nsims=100 # 0.985 avec la deuxième pour large nsims (I=2 J=3) #### set.seed(666) dat <- simAV1R(I=6, J=2, mu=10, sigmab=2, sigmaw=2) fit <- aov1r(y~group, dat) predict(fit) library(rstanarm) options(mc.cores = parallel::detectCores()) sfit <- stan_lmer(y ~ (1|group), data=dat, prior_covariance = decov(1, 1, 0.01, 100), iter = 3500, warmup=1000, adapt_delta = 0.98, prior_PD=FALSE) predictive_interval(sfit, newdata=data.frame(group="xxx"), prob=0.95) predictive_interval(sfit, newdata=data.frame(group="xxx"), re.form=NA, prob=0.95) samples <- rstan::extract(sfit$stanfit) # aux is sigma and theta_L is sigma²_b psims <- rnorm(10000, samples$alpha, sqrt(samples$theta_L[,1]+samples$aux^2)) quantile(psims, c(0.025, 0.975)) pivotals <- AOV1R:::pivotal(fit) plot(density(pivotals$G_mu)) lines(density(samples$alpha), col="red") plot(density(pivotals$G_sigma2b)) lines(density(samples$theta_L[,1]), col="red") plot(density(pivotals$G_sigma2w)) lines(density(samples$aux^2), col="red") library(brms) options(mc.cores = parallel::detectCores()) bfit <- brm(y ~ (1|group), data = dat, control = list(adapt_delta = 0.95), prior = c(prior(cauchy(0,5),class="sd")), iter = 3500, warmup = 1000) pred <- posterior_predict(bfit, newdata=data.frame(group="xxx"), allow_new_levels=TRUE) quantile(pred, c(0.025, 0.975)) samples <- posterior_samples(bfit) names(samples) psims <- rnorm(10000, samples$b_Intercept, sqrt(samples$sd_group__Intercept^2 + samples$sigma^2)) quantile(psims, c(0.025, 0.975)) pivotals <- AOV1R:::pivotal(fit) plot(density(pivotals$G_mu)) lines(density(samples$b_Intercept), col="red") plot(density(pivotals$G_sigma2b)) lines(density(samples$sd_group__Intercept^2), col="red") plot(density(pivotals$G_sigma2w)) lines(density(samples$sigma^2), col="red") plot(density(pivotals$G_sigma2b+pivotals$G_sigma2w, from=0, to=200)) lines(density(samples$sd_group__Intercept^2+samples$sigma^2), col="red") # assez nickel ! plot(pivotals$G_mu[1:2000], pivotals$G_sigma2w[1:2000]) points(samples$b_Intercept, samples$sigma^2, col="red") library(lme4) lfit <- lmer(y ~ (1|group), dat)
18bfee5f4f45bd6cc6888326d6e7c5a075a9998f
e434738314e1ac1c97247e5395e044357a7c0eb6
/tests/testthat/test_shiny_reactive.R
aad37bfb7e4198e399e5e4cc3019b5f6fcf7f137
[]
no_license
edanen/cytomapper
39e1063ded2e339bbc31fe584c28727ef75f19b8
60c4685887a33072ffae2637eb69a9c0dfcdbb29
refs/heads/master
2022-12-16T16:52:42.941716
2020-09-13T16:41:11
2020-09-13T16:41:11
null
0
0
null
null
null
null
UTF-8
R
false
false
280
r
test_shiny_reactive.R
data("pancreasImages") data("pancreasMasks") data("pancreasSCE") shiny::testServer(app = cytomapperShiny(object = pancreasSCE, img_id = "ImageNb", cell_id = "CellNb"), { session$setInputs(sample = 1, plotCount = 1) expect_equal(input$sample, 1) })
3c564e548d5105772e119eafea45733869e111b0
1cd07d10573cbf1f63ee64d9634d29498437bc2d
/Intro File.R
a176e9f8d61271e9d4e5a6bf7ba5759f737d84b0
[]
no_license
anshikadhingra/R-programming
405bc159d6bc069bcf540cbe6c6cd70d4d8c304d
6c88fc2c01e388dfb67379eb366956990d1c6ee4
refs/heads/main
2023-08-24T10:37:03.965081
2021-10-30T10:08:40
2021-10-30T10:08:40
303,133,108
3
2
null
null
null
null
UTF-8
R
false
false
131
r
Intro File.R
#Introduction print("Welcome to Analytics Edge class") a<-(print("Welcome to Analytics Edge class")) a X=1:5 Y=6:10 plot(X,Y)
d7d9d50aae8d05349c95fe22b389046d2b985339
6efad62861b49cb755623da49bd5725bcfe28e27
/LAB1/Part3/Shiny/ui.R
0dde9e90af6542399f07309b6ccdbef0821da84d
[]
no_license
Keerthu-Baskar/Data-Intensive-Computing-UB-CSE587
a37a740bffa8a463e3d2a75e6588d608c8c2969b
e477d37df5376a28b35da5a09c5b066fd5a1f353
refs/heads/master
2020-07-07T17:03:58.668115
2020-01-01T21:13:59
2020-01-01T21:13:59
203,415,040
0
0
null
null
null
null
UTF-8
R
false
false
651
r
ui.R
library(shiny) ui <- pageWithSidebar( # App title ---- headerPanel("Twitter Vs CDC Flu"), # Sidebar panel for inputs ---- wellPanel( fluidRow( column(3, selectInput("populatie", label = h4("Maps"), choices = list("Twitter" = "tw", "CDC" = "cd", "CDC vs Twitter" = "cdt"), selected = "tw"), uiOutput("img1")), # here is the image column(9, plotOutput("plot2")) ) ), # Main panel for displaying outputs ---- mainPanel() ) #ui <- fluidPage( # titlePanel("My Shiny App"), #tags$div(img(src = "rstudio.png")) #)
04cf676a9d99412e0d81deb8b571abe12cd66f33
b5822b9c2a756f4e540c426e7e84af35dae8caec
/rockchalk/R/vech2mat.R
e8d273f19a1e596843944afa2b644dc7d5c828aa
[]
no_license
pauljohn32/rockchalk
0c75b7a7bc142669efcfabbc70d511f60c3f47e0
fc2d3d04396bf89ef020e824f50db3c348e3e226
refs/heads/master
2022-08-20T02:49:56.898990
2022-07-26T01:20:12
2022-07-26T01:20:12
8,965,635
8
5
null
2022-07-18T00:36:58
2013-03-23T04:07:35
R
UTF-8
R
false
false
2,326
r
vech2mat.R
##' Convert a half-vector (vech) into a matrix. ##' ##' Fills a matrix from a vector that represents the lower triangle. ##' If user does not supply a value for diag, then the vech will fill ##' in the diagonal as well as the strictly lower triangle. If diag ##' is provided (either a number or a vector), then vech is for the ##' strictly lower triangular part. The default value for lowerOnly ##' is FALSE, which means that a symmetric matrix will be created. See ##' examples for a demonstration of how to fill in the lower triangle ##' and leave the diagonal and the upper triangle empty. ##' ##' @param vech A vector ##' @param diag Optional. A single value or a vector for the ##' diagonal. A vech is a strictly lower triangluar vech, it ##' does not include diagonal values. diag can be either a single ##' value (to replace all elements along the diagonal) or a vector of ##' the correct length to replace the diagonal. ##' @param lowerOnly Default = FALSE. ##' @seealso Similar functions exist in many packages, see ##' \code{vec2sm} in corpcor, \code{xpnd} in MCMCpack ##' @export ##' @examples ##' x <- 1:6 ##' vech2mat(x) ##' vech2mat(x, diag = 7) ##' vech2mat(x, diag = c(99, 98, 97, 96)) ##' vech2mat(x, diag = 0, lowerOnly = TRUE) vech2mat <- function(vech, diag = NULL, lowerOnly = FALSE) { ## Must calculate correct number of rows from vech, if ## vech implies a non-square, stop. ## If no diag, then vech provides the diagonal values if (!is.null(diag)){ d <- (sqrt(1 + 8 * length(vech)) + 1)/2 if (!as.integer(d) == d) stop(deparse(substitute(vech)), " must have the correct number of elements to fill a stricly lower triangle.") X <- matrix(0, nrow = d, ncol = d) X[lower.tri(X, diag = FALSE)] <- vech diag(X) <- makeVec(diag, d) if (!lowerOnly) X[upper.tri(X)] <- t(X)[upper.tri(X)] } else { d <- (sqrt(1 + 8 * length(vech)) - 1)/2 if (!as.integer(d) == d) stop(paste("You supplied diag. So ", deparse(substitute(vech)), " must have the correct number of elements to fill in a lower triangle, including the diagonal..")) X <- matrix(0, nrow = d, ncol = d) X[lower.tri(X, diag = TRUE)] <- vech if (!lowerOnly) X[upper.tri(X)] <- t(X)[upper.tri(X)] } X } NULL
4dc463467a7548a15ee1d47024fe115402d1cad8
aae4c7348a09c650369468b0cc20d3e10cfaeb60
/GenericClustering.R
89e33d8f03232ef8111ddfc6fceb30aeef4a394a
[]
no_license
Prashant0701/PracticeAnalytics
112f4100015ee5dbb6b405ffdfae76f1e4b23309
4a3c8b67cc1573785b82dea90a81aa2b4dc56329
refs/heads/master
2021-08-23T19:40:01.461759
2017-12-06T08:02:22
2017-12-06T08:02:22
113,286,117
0
0
null
null
null
null
UTF-8
R
false
false
3,591
r
GenericClustering.R
rm(list=ls()) library(caret) library(RWeka) set.seed(1234) # separate data into test and train sets, 70/30 split in this case splitIndex <- createDataPartition(iris$Species, p = 0.7, list = FALSE) train <- iris[splitIndex, ] test <- iris[-splitIndex, ] testInd <- test[ ,!colnames(test) %in% "Species"] testDep <- as.factor(test[, names(test) == "Species"]) TrainData <- iris[,1:4] TrainClasses <- iris[,5] #First Model jripFit1 <- train(TrainData, TrainClasses,method = "JRip") jripFit1 plot(jripFit1) #Second Model jripFit2 <- train(TrainData, TrainClasses,method = "JRip",preProcess = c("center", "scale"),tuneLength = 10,trControl = trainControl(method = "cv")) jripFit2 plot(jripFit2) # K means neighborCount=2 modelKNN <- knn3(Species ~ ., data = train, k = neighborCount, prob = TRUE) predKNN <- predict(modelKNN, testInd, type = "prob") confKNN <- confusionMatrix(testDep, predKNN) #Another Round km <- kmeans(iris[,1:4], 3) plot(iris[,1], iris[,2], col=km$cluster) points(km$centers[,c(1,2)], col=1:3, pch=19, cex=2) table(km$cluster, iris$Species) #Another Way km2 <- kmeans(iris[,1:4], 3) plot(iris[,1], iris[,2], col=km2$cluster) points(km2$centers[,c(1,2)], col=1:3, pch=19, cex=2) table(km2$cluster, iris$Species) #heir m <- matrix(1:15,5,3) dist(m) # computes the distance between rows of m (since there are 3 columns, it is the euclidian distance between tri-dimensional points) dist(m,method="manhattan") # using the manhattan metric sampleiris <- iris[sample(1:150, 40),] # get samples from iris dataset # each observation has 4 variables, ie, they are interpreted as 4-D points distance <- dist(sampleiris[,-5], method="euclidean") cluster <- hclust(distance, method="average") plot(cluster, hang=-1, label=sampleiris$Species) plot(as.dendrogram(cluster), edgePar=list(col="darkgreen", lwd=2), horiz=T) str(as.dendrogram(cluster)) # Prints dendrogram structure as text. cluster$labels[cluster$order] # Prints the row labels in the order they appear in the tree. #Prune by cluster par(mfrow=c(1,2)) group.3 <- cutree(cluster, k = 3) # prune the tree by 3 clusters table(group.3, sampleiris$Species) # compare with known classes plot(sampleiris[,c(1,2)], col=group.3, pch=19, cex=2.5, main="3 clusters") points(sampleiris[,c(1,2)], col=sampleiris$Species, pch=19, cex=1) group.6 <- cutree(cluster, k = 6) # we can prune by more clusters table(group.6, sampleiris$Species) plot(sampleiris[,c(1,2)], col=group.6, pch=19, cex=2.5, main="6 clusters") points(sampleiris[,c(1,2)], col=sampleiris$Species, pch=19, cex=1) # the little points are the true classes par(mfrow=c(1,1)) plot(cluster, hang=-1, label=sampleiris$Species) abline(h=0.9,lty=3,col="red") height.0.9 <- cutree(cluster, h = 0.9) table(height.0.9, sampleiris$Species) # compare with known classes plot(sampleiris[,c(1,2)], col=height.0.9, pch=19, cex=2.5, main="3 clusters") points(sampleiris[,c(1,2)], col=sampleiris$Species, pch=19, cex=1) # Calculate the dissimilarity between observations using the Euclidean distance dist.iris <- dist(iris, method="euclidean") # Compute a hierarchical cluster analysis on the distance matrix using the complete linkage method h.iris <- hclust(dist.iris, method="complete") h.iris head(h.iris$merge, n=10) plot(h.iris) h.iris.heights <- h.iris$height # height values h.iris.heights[1:10] subs <- round(h.iris.heights - c(0,h.iris.heights[-length(h.iris.heights)]), 3) # subtract next height which.max(subs) # Cuts dendrogram at specified level and draws rectangles around the resulting clusters plot(cluster); rect.hclust(cluster, k=6, border="red")
77acddf84a17de77233e433287d95029045b0990
29d34e3302b71d41d77af715727e963aea119392
/R/rtPalette.R
56f047c2616aeb710c80b9e0ee830dd9aa37fab2
[]
no_license
bakaibaiazbekov/rtemis
1f5721990d31ec5000b38354cb7768bd625e185f
a0c47e5f7fed297af5ad20ae821274b328696e5e
refs/heads/master
2020-05-14T20:21:40.137680
2019-04-17T15:42:33
2019-04-17T15:42:33
181,943,092
1
0
null
2019-04-17T18:00:09
2019-04-17T18:00:09
null
UTF-8
R
false
false
12,824
r
rtPalette.R
# rtPalette.R # ::rtemis:: # 2016 Efstathios D. Gennatas egenn.github.io # Penn ==== #' rtemis Color Palettes #' #' \code{pennCol}: Penn color palette (http://www.upenn.edu/about/styleguide-color-type) #' @name rtPalettes #' @export pennCol <- list(darkestBlue = "#000f3a", darkerBlue = "#00144d", blue = "#01256e", lighterBlue = "#045ea7", lightestBlue = "#82afd3", darkestRed = "#57000a", darkerRed = "#74000e", red = "#95001a", lighterRed = "#c2004d", lightestRed = "#e180a6", darkestYellow = "#af7f00", darkerYellow = "#eaa900", yellow = "#f2c100", lighterYellow = "#f8de00", lightestYellow = "#fcef80", darkestGreen = "#005200", darkerGreen = "#006e00", green = "#008e00", lighterGreen = "#00be00", lightestGreen = "#80df80", darkestOrange = "#812d00", darkerOrange = "#ac3c00", orange = "#c35a00", lighterOrange = "#df9700", lightestOrange = "#efcb80", darkestPurple = "#23001f", darkerPurple = "#2f0029", purple = "#4a0042", lighterPurple = "#890082", lightestPurple = "#c480c1") #' \code{pennPalette}: Subset of \code{pennCol}. This is the default palette of the \link{mplot3} family #' #' @name rtPalettes #' @export pennPalette <- pennCol[c("lighterBlue", "red", "green", "yellow", "lighterPurple", "orange", "lightestBlue", "lighterRed", "lighterGreen", "lightestPurple", "lighterOrange")] #' \code{pennLightPalette}: Subset of \code{pennCol}. This is the lighter Penn palette for use with the dark themes #' @name rtPalettes #' @export pennLightPalette <- pennCol[c("lightestBlue", "lightestRed", "lightestGreen", "lightestYellow", "lightestPurple")] # Imperial ==== #' Imperial Colors #' #' \code{imperialCol}: Imperial College London color palette (https://www.imperial.ac.uk/brand-style-guide/visual-identity/brand-colours/) #' #' @name rtPalettes #' @export imperialCol <- list(navy = "#002147", imperialBlue = "#003E74", lightGrey = "#EBEEEE", coolGrey = "#9D9D9D", lightBlue = "#D4EFFC", blue = "#006EAF", processBlue = "#0091D4", poolBlue = "#00ACD7", darkTeal = "#0F8291", teal = "#009CBC", seaglass = "#379f9f", darkGreen = "#02893B", kermitGreen = "#66A40A", lime = "#BBCE00", orange = "#D24000", tangerine = "#EC7300", lemonYellow = "#FFDD00", brick = "#A51900", red = "#DD2501", cherry = "#E40043", raspberry = "#9F004E", magentaPink = "#C81E78", iris = "#751E66", violet = "#960078", plum = "#321E6D", purple = "#653098") # UCSF ==== #' UCSF Colors #' #' \code{ucsfCol}: UCSF color palette (http://identity.ucsf.edu/color) #' #' @name rtPalettes #' @export ucsfCol <- list(navy = "#052049", teal = "#18A3AC", green = "#90BD31", blue = "#178CCB", orange = "#F48024", purple = "#716FB2", red = "#EC1848", yellow = "#FFDD00", iTeal = "#058488", iGreen = "#6EA400", iBlue = "#007CBE", iOrange = "#F26D04", iRed = "#EB093C") #' UCSF Color Palette #' #' \code{ucsfPalette}: Subset of \code{ucsfCol} for use with \link{mplot3}, etc #' #' @name rtPalettes #' @export # ucsfPalette <- ucsfCol[c("iTeal", "iRed", "iBlue", "yellow", "purple", "iOrange", "iGreen")] ucsfPalette <- ucsfCol[c("teal", "orange", "blue", "yellow", "purple", "red", "navy", "green")] # Berkeley ==== #' Berkeley Colors #' #' \code{berkeleyCol}: Berkeley color palette (https://brand.berkeley.edu/colors/) #' #' @name rtPalettes #' @export berkeleyCol <- list(berkeleyBlue = "#003262", foundersRock = "#3B7EA1", californiaGold = "#FDB515", medalist = "#C4820E", wellmanTile = "#D9661F", roseGarden = "#EE1F60", goldenGate = "#ED4E33", southHall = "#6C3302", bayFog = "#DDD5C7", lawrence = "#00B0DA", lapLane = "#00A598", pacific = "#46535E", satherGate = "#B9D3B6", ion = "#CFDD45", soyBean = "#859438", stonePine = "#584F29", grey = "#EEEEEE", webGrey = "#888888") # Stanford ==== #' Stanford Colors #' #' \code{stanfordCol}: Stanford color palette (https://identity.stanford.edu/color.html#digital-color) #' #' @name rtPalettes #' @export stanfordCol <- list(cardinal = "#8c1515", coolGrey = "#4d4f53", birghtRed = "#B1040E", chocolate = "#2F2424", stone = "#544948", fog = "#F4F4F4", lightSandstone = "#F9F6EF", sandstone = "#d2c295", warmGrey = "#3f3c30", beige = "#9d9573", lightSage = "#c7d1c5", clay = "#5f574f", cloud = "#dad7cb", driftwood = "#b6b1a9", sandhill = "#b3995d", paloAlto = "#175e54", teal = "#00505c", purple = "#53284f", redwood = "#8d3c1e", brown = "#5e3032", sky = "#0098db", lagunita = "#007c92", mint = "#009b76", gold = "#b26f16", sun = "#eaab00", poppy = "#e98300") # USF ==== #' USF Colors #' #' \code{usfCol}: USF color palette (https://myusf.usfca.edu/marketing-communications/resources/graphics-resources/brand-standards/color-palette) #' Color conversions performed using https://www.pantone.com/color-finder/ #' @name rtPalettes #' @export usfCol <- list(green = "#205C40", yellow = "#ffb81c", gray = "#75787B") # UC San Diego ==== #' UC San Diego Colors #' #' \code{ucsdCol}: UC San Diego color palette (https://ucpa.ucsd.edu/brand/elements/color-palette/) #' @name rtPalettes #' @export ucsdCol <- list(blue = "#182B49", mediumBlue = "#006A96", gold = "#C69214", yellow = "#FFCD00", cyan = "#00C6D7", green = "#6E963B", lightYellow = "#F3E500", orange = "#FC8900", coolGray = "#747678", lightGray = "#B6B1A9", darkGold = "#84754E") # UCLA ==== #' UCLA Colors #' #' \code{uclaCol}: UCLA color palette (http://brand.ucla.edu/identity/colors) #' @name rtPalettes #' @export uclaCol <- list(blue = "#2774AE", gold = "#FFD100", darkestBlue = "#003B5C", darkerBlue = "#005587", lighterBlue = "#8BB8E8", lightestBlue = "#C3D7EE", darkestGold = "#FFB81C", darkerGold = "#FFC72C", yellow = "#FFFF00", green = "#00FF87", magenta = "#FF00A5", cyan = "#00FFFF", purple = "#8237FF") # University of California ==== #' University of California Colors #' #' \code{ucCol}: University of California color palette #' (http://brand.universityofcalifornia.edu/guidelines/color.html#!primary-colors) #' @name rtPalettes #' @export ucCol <- list(ucBlue = "#1295D8", ucGold = "#FFB511", blue = "#005581", lightBlue = "#72CDF4", gold = "#FFD200", lightgold = "#FFE552", orange = "#FF6E1B", lightOrange = "#FF8F28", pink = "#E44C9A", lightPink = "#FEB2E0", teal = "#00778B", lightTeal = "#00A3AD", ucGray = "#7C7E7F", warmGray8 = "#8F8884", warmGray3 = "#BEB6AF", warmGray1 = "#DBD5CD", metallicGold = "#B4975A") # Washington ==== #' University of Washington Colors #' #' \code{uwCol}: University of Washington color palette #' (http://www.washington.edu/brand/graphic-elements/primary-color-palette/) #' @name rtPalettes #' @export uwCol <- list(purple = "#4b2e83", gold = "#b7a57a", metallicGold = "#85754d") # NIH ==== #' NIH Colors #' #' \code{nihCol}: NIH color palette (https://www.nlm.nih.gov/about/nlm_logo_guidelines_030414_508.pdf) #' @name rtPalettes #' @export nihCol <- list(blue = "#20558a", gray = "#616265") # Apple ==== #' Apple Colors #' #' \code{appleCol}: Apple Human Interface Guidelines color palette #' (https://developer.apple.com/design/human-interface-guidelines/ios/visual-design/color/) #' @name rtPalettes #' @export appleCol <- list(red = "#FF3B30", orange = "#FF9500", yellow = "#FFCC00", green = "#4CD964", tealBlue = "#5AC8FA", blue = "#007AFF", purple = "#5856D6", pink = "#FF2D55") # Google ==== #' Google Colors #' #' \code{googleCol}: Google brand palette (https://brandpalettes.com/google-colors/) #' @name rtPalettes #' @export googleCol <- list(blue = "#4285F4", red = "#DB4437", yellow = "#F4B400", green = "#0F9D58") # Amazon ==== #' Amazon Colors #' #' \code{amazonCol}: Amazon brand palette #' (https://images-na.ssl-images-amazon.com/images/G/01/AdvertisingSite/pdfs/AmazonBrandUsageGuidelines.pdf) #' @name rtPalettes #' @export amazonCol <- list(orange = "#FF9900", blue = "#146EB4") # Microsoft ==== #' Microsoft Colors #' #' \code{microsoftCol}: Microsoft brand palette #' (https://brandcolors.net/b/microsoft) #' @name rtPalettes #' @export microsoftCol <- list(orange = "#f65314", green = "#7cbb00", blue = "#00a1f1", yellow = "#ffbb00") rtPalettes <- list(pennCol = pennCol, imperialCol = imperialCol, ucsfCol = ucsfCol, ucsfPalette = ucsfPalette, berkeleyCol = berkeleyCol, stanfordCol = stanfordCol, usfCol = usfCol, ucsdCol = ucsdCol, uclaCol = uclaCol, uwCol = uwCol, nihCol = nihCol, appleCol = appleCol, googleCol = googleCol, amazonCol = amazonCol, microsoftCol = microsoftCol) #' \pkg{rtemis} Color Palettes #' #' \code{rtPalettes} prints names of available color palettes #' Each palette is a named list of hexadecimal color definitions which can be used with any #' graphics function. #' @param palette String: Name of palette to return. Default = NULL: available palette names #' are printed and no palette is returned #' @return #' A list of available palettes, invisibly #' @examples #' rtPalette() #' @export rtPalette <- function(palette = NULL) { if (is.null(palette)) { msg(crayon::cyan("The following palettes are available:")) print(paste(c("pennCol", "imperialCol", "ucsfCol", "berkeleyCol", "stanfordCol", "ucsdCol", "uclaCol", "usfCol", "nihCol"))) } else { palette <- match.arg(palette, c("pennCol", "imperialCol", "ucsfCol", "ucsfPalette", "berkeleyCol", "stanfordCol", "usfCol", "ucsdCol", "uclaCol", "nihCol")) rtPalettes[[palette]] } } # rtemis::rtPalettes # Custom crayon styles ==== teal <- make_style(teal = "#18A3AC") rtBlue <- make_style(rtBlue = "#005581") rtOrange <- make_style(rtOrange = "#F48024") rtHighlight.color <- getOption("rt.highlight.color", "#18A3AC") rtHighlight <- make_style(rtHighlight = rtHighlight.color)
fa1c455d6a4528c64bf0307ed2ca3e1ab7565075
11615afb4c52f1acbf0b5c07501bdc0fdff76e4d
/run_analysis.R
1e580cda32060eb3de3e11cf5c24ae0ffa3e0aea
[]
no_license
michaelpboyle/Proj03GetClean
e37290c9f3a4ddcae432f6bd6bdf8701b6c2961d
db158694b19c289d2ab02aea0d0e2705fef77d4c
refs/heads/master
2021-01-18T15:14:47.450345
2015-04-25T21:49:55
2015-04-25T21:49:55
34,489,533
0
0
null
null
null
null
UTF-8
R
false
false
5,451
r
run_analysis.R
#################################################################################################### ## Get Data #################################################################################################### ## Download files (Using wget method for Linux OS) projUrl <- "https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip" download.file(projUrl,destfile = "./03Data/projData.zip",method="wget") dateDownloaded <- date() print(dateDownloaded) ## Record download date ## Unzip (extract) files unzip("./03Data/projData.zip",list=FALSE) #################################################################################################### #################################################################################################### ## Read features.txt and modify values to remove punctuation marks. Keeping names mixed-case ## for better readability. ## Resulting vector "features" will be used as column names for ## test and train dataframes. #################################################################################################### ## Requirement #4 ## Appropriately labels the data set with descriptive variable names. featureData <- read.table("./UCI HAR Dataset/features.txt") features <- gsub("[[:punct:]]", "", featureData$V2) #################################################################### ## Create df_test (Test dataset "dataframe") #################################################################### ## Read in 3 tables making up test data. testData <- read.table("./UCI HAR Dataset/test/X_test.txt" ,col.names=features) testSubjData <- read.table("./UCI HAR Dataset/test/subject_test.txt" ,col.names='Subject') testActvtyData <- read.table("./UCI HAR Dataset/test/y_test.txt" ,col.names='Activity') ## Combine 3 dataframes so that we have columns: ## Subject, Activity, followed by 561 features testDescription <- cbind(testSubjData,testActvtyData) str(testDescription) table(testDescription) df_test <- cbind(testDescription,testData) #################################################################### #################################################################### ## Create df_train (Train dataset "dataframe") #################################################################### ## Read in 3 tables making up train data. trainData <- read.table("./UCI HAR Dataset/train/X_train.txt" ,col.names=features) trainSubjData <- read.table("./UCI HAR Dataset/train/subject_train.txt" ,col.names='Subject') trainActvtyData <- read.table("./UCI HAR Dataset/train/y_train.txt" ,col.names='Activity') ## Combine 3 dataframes so that we have columns: ## Subject, Activity, followed by 561 features trainDescription <- cbind(trainSubjData,trainActvtyData) str(trainDescription) table(trainDescription) df_train <- cbind(trainDescription,trainData) #################################################################### ################################################################################ ## Create df_HAR (Human Activity Recognition dataframe). ################################################################################ ## Requirement #1 ## Merge (append) the training and the test sets to create one data set. df_HAR <- rbind(df_train,df_test) ## Requirement #2 ## Extract only the measurements on the mean and standard deviation for each measurement. ## Merge (append) the training and the test sets to create one data set. f_keep <- features[grep("mean|std",features)] df_HAR1 <- df_HAR[,c("Subject","Activity",f_keep)] ################################################################################ ################################################################################ ## Add ActivityDescription field to dataset ################################################################################ ## Requirement #3 ## Use descriptive activity names to name the activities in the data set activityDescription <- read.table("./UCI HAR Dataset/activity_labels.txt" ,col.names=c('Activity','ActivityDescription')) df_HAR2 <- merge(df_HAR1,activityDescription,by.x="Activity",by.y="Activity",all=FALSE) ################################################################################ ## Remove large temporary dataframes rm(testData) rm(trainData) rm(df_train) rm(df_test) rm(df_HAR) ################################################################################ ## Summarize dataset on Activity and Subject, Provide means for remaining variables. ################################################################################ ## Requirement #5 ## From the data set in step 4, creates a second, independent tidy data set with the average ## of each variable for each activity and each subject. averages_HCI <- aggregate(by=list(Activity=df_HAR2$ActivityDescription ,Subject=df_HAR2$Subject) ,df_HAR2[,f_keep],FUN="mean") str(averages_HCI) ## Show structure of final dataset ########################################################################################### ## Upload the tidy data set created in step 5 of the instructions as a txt file ## with write.table() using row.name=FALSE write.table(averages_HCI,file="./averages_HCI.txt",row.name=FALSE) q()
99de9dc45d6cc75a7a8b890bbe4e96602951386b
04c91c0754a70d50c8e82dcd1378ecc77ee5b1f7
/positive_test.R
4feaf66faac9913d1478bdd3eba569358d77498a
[]
no_license
jbsalomond/BaDEst-Test
d28878b1b9f506286f20475457a02a75f10a6f73
abe6760c5ddb82c3b4637fe66fc162f52fac7ea8
refs/heads/master
2021-03-24T13:32:53.946583
2017-07-06T11:38:07
2017-07-06T11:38:07
78,019,719
0
0
null
null
null
null
UTF-8
R
false
false
4,147
r
positive_test.R
library(dplyr) library(MASS) library(invgamma) library(pbapply) library(parallel) cl = cl <- makeCluster(10) clusterExport(cl, ls()) clusterEvalQ(cl, library(MASS)) clusterEvalQ(cl, library(dplyr)) clusterEvalQ(cl, library(invgamma)) clusterEvalQ(cl, library(pbapply)) # Function H H = function(omega){ (- min(omega)) } # sampling k ## Computing the log prob Cxk = function(k,x,y,prior,alpha,beta,mu,lambda){ n = length(x) TDC = mutate(data.frame(x), I = cut(x,breaks = seq(0,k)/k,right = F),Z = 1,Y = y) Yi2 = aggregate(Y ~ I, function(z){sum((z - mean(z))^2)},data = TDC)$Y #Yim = aggregate(Y ~ I, mean,data = TDC)$Y ni = aggregate(Z ~ I, sum,data = TDC)$Z #Y3 = ni*mu*(Yim - m)^2/(ni + mu) #beta = 2*mean(Yi) btilde = beta + 0.5*sum(Yi2) #+ 0.5*sum(Y3) if(prior == "pois"){ logprior = dpois(k-2,lambda,log = T) } if(prior == "geom"){ logprior = dgeom(k-1,lambda,log = T) } lpik = -log(btilde)*(alpha + n/2) - 0.5*sum(log(ni + mu)) + 0.5*k*log(mu/(2*pi)) + logprior return(lpik) } # sample k sampleK00 = function(x,y,prior,alpha,beta,mu,lambda,Kmax,Nk){ kliste = seq(2,Kmax) logpik = sapply(X = kliste,FUN = Cxk, x = x,y = y,prior = prior,alpha = alpha,beta = beta,mu = mu,lambda = lambda) pik = exp(logpik)/sum(exp(logpik)) sample(2:Kmax,prob = pik,replace = T,size = Nk) } sampleK = function(x,y,prior,alpha,beta,mu,lambda,Kmax,Nk){ k0 = ceiling(sqrt(length(x)))+2 kliste = seq(2,k0) logpik = sapply(X = kliste,FUN = Cxk, x = x,y = y,prior = prior,alpha = alpha,beta = beta,mu = mu,lambda = lambda) test = TRUE i = k0 while(test){ logpik = c(logpik,Cxk(k = i+1,x=x,y=y,prior = prior,alpha = alpha,beta = beta,mu=mu,lambda = lambda)) #print(length(logpik)-k0) #print((logpik[i] - max(logpik))) test = (logpik[i] - max(logpik)) > -300 #print(test) test = test&(i<Kmax) i = i+1 } center = logpik - max(logpik) #print(center) pik = exp(center)/sum(exp(center)) sample(2:i,prob = pik,replace = T,size = Nk) } test = function(x,y,prior,alpha,beta,mu,lambda,Kmax,Nk,M0,verbose=F,autoM0 = F){ # Sample k first n = length(x) k = sampleK(x,y,prior,alpha,beta,mu,lambda,Kmax,Nk) df = data.frame(k = k, ni = 1) ktable = aggregate(ni~k,data = df,FUN = sum) #print(ktable) K = dim(ktable)[1] out = rep(0,K) if(verbose) print(ktable) for(i in 1:K){ j = ktable[i,1] nj = ktable[i,2] outk = rep(0,nj) TDC = mutate(data.frame(x), I = cut(x,breaks = seq(0,j)/j,right = F),Z = 1,Y = y) Yi = aggregate(Y~I, data = TDC, mean)$Y ni = aggregate(Z~I, data = TDC, sum)$Z Yi2 = aggregate(Y ~ I, function(z){sum((z - mean(z))^2)},data = TDC)$Y #Yim = aggregate(Y ~ I, mean,data = TDC)$Y #Y3 = ni*mu*(Yim - m)^2/(ni + mu) btilde = beta + 0.5*sum(Yi2) #+ 0.5*sum(Y3) sigma = rinvgamma(nj,shape = alpha + n/2, rate = btilde) #print(median(sqrt(sigma))) if(verbose) print(median(sigma)) for(l in 1:nj){ if(autoM0) tau = 2*M0*sqrt(log(n/j))*(sqrt(j*median(sigma)/(n+j*mu))) else tau = (M0*sqrt(j*median(sigma)*log(n)/(n))) postmean = Yi postvar = sigma[l]/(ni + mu) omega = rnorm(n = j, m = postmean,sd = sqrt(postvar)) #print(j) #print(omega) #print(H(omega)) #print(tau) outk[l] = H(omega)>tau } out[i] = sum(outk) } return(sum(out)/Nk>=0.5) } run = function(n,sd = 0.1,verbose = T,autoM0 = F,prior = "geom",lambda = 0.4,M0=1,mu=1,Kmax=100){ sd = 0.1 ro = 6*(log(n)/n)^(1/3) f = function(x){ ro*(abs(x-0.5)-0.1)*(abs(x-0.5)<0.1) } X = seq(0,1,length = n+1)[-(n+1)] y = f(X) + rnorm(n,sd = sd) return(test(X,y,prior,alpha = 100, beta = .5,mu = mu,lambda = lambda,Kmax= Kmax,Nk = 2500,M0 = M0,verbose = verbose,autoM0 = autoM0) ) } positive = function(spsize){ mean(replicate(run(n = spsize, verbose = F,prior = "geom",lambda = .4,M0 = 1,mu = 1,autoM0 = T),n = 250)) } positive(100) nlist = c(100,250,500,1000,2500) clusterExport(cl, ls()) start.time = proc.time() resutl <- parLapply(cl,nlist,positive) print(proc.time() - start.time) t(unlist(resutl))
765754535c42758b0d89335ea2c43bfda287c85b
80013fca745bae4e41b2d185e82ffa3e602baab2
/SGP_CONFIG/configToSGPNormGroup.R
bf160ae0c5bdf89250141301067e10219aa10f6e
[]
no_license
CenterForAssessment/Washington
cc581196abf1aa292a987e5302d7c650a7941f60
38057ecb2f9ce15626984d7e528f86c92e437e46
refs/heads/master
2023-08-16T18:28:01.700164
2023-08-10T19:22:46
2023-08-10T19:22:46
5,937,904
1
0
null
2014-08-13T10:44:18
2012-09-24T17:15:35
R
UTF-8
R
false
false
3,539
r
configToSGPNormGroup.R
################################################################################################### ### ### Script to convert SGP configurations for EOCT analyses to SGP_NORM_GROUP preference tables ### ################################################################################################### ### Load packages require("data.table") options(error=recover) ### utility function configToSGPNormGroup <- function(sgp.config) { if ("sgp.norm.group.preference" %in% names(sgp.config)) { tmp.data.all <- data.table() for (g in 1:length(sgp.config$sgp.grade.sequences)) { l <- length(sgp.config$sgp.grade.sequences[[g]]) tmp.norm.group <- paste(tail(sgp.config$sgp.panel.years, l), paste(tail(sgp.config$sgp.content.areas, l), unlist(sgp.config$sgp.grade.sequences[[g]]), sep="_"), sep="/") #tmp.norm.group.baseline <- tmp.data <- data.table( SGP_NORM_GROUP=paste(tmp.norm.group, collapse="; "), # SGP_NORM_GROUP_BASELINE=paste(tmp.norm.group.baseline, collapse="; "), PREFERENCE= sgp.config$sgp.norm.group.preference*100) if (length(tmp.norm.group) > 2) { for (n in 1:(length(tmp.norm.group)-2)) { tmp.data <- rbind(tmp.data, data.table( SGP_NORM_GROUP=paste(tail(tmp.norm.group, -n), collapse="; "), # SGP_NORM_GROUP_BASELINE=paste(tmp.norm.group.baseline, collapse="; "), PREFERENCE= (sgp.config$sgp.norm.group.preference*100)+n)) } } tmp.data.all <- rbind(tmp.data.all, tmp.data) } return(unique(tmp.data.all)) } else { return(NULL) } } ### Load and create 2012_2013 EOC Configuration source("EOCT/2010_2011/MATHEMATICS.R") source("EOCT/2011_2012/MATHEMATICS.R") # source("EOCT/2010_2011/BIOLOGY.R") # BIO starts in 2012 source("EOCT/2011_2012/BIOLOGY.R") # not calculating Science or Biology in 2013, but leave this in for WA_SGP_Norm_Group_Preference.Rdata source("EOCT/2012_2013/MATHEMATICS.R") WA_EOCT_2010_2011.config <- c( EOC_MATHEMATICS_1.2010_2011.config, EOC_MATHEMATICS_2.2010_2011.config) WA_EOCT_2011_2012.config <- c( EOC_MATHEMATICS_1.2011_2012.config, EOC_MATHEMATICS_2.2011_2012.config, BIOLOGY.2011_2012.config) WA_EOC_2012_2013.config <- c( EOC_MATHEMATICS_1.2012_2013.config, EOC_MATHEMATICS_2.2012_2013.config) ### Create configToNormGroup data.frame tmp.configToNormGroup <- lapply(WA_EOCT_2010_2011.config, configToSGPNormGroup) WA_SGP_Norm_Group_Preference_2010_2011 <- data.table( YEAR="2010_2011", rbindlist(tmp.configToNormGroup)) tmp.configToNormGroup <- lapply(WA_EOCT_2011_2012.config, configToSGPNormGroup) WA_SGP_Norm_Group_Preference_2011_2012 <- data.table( YEAR="2011_2012", rbindlist(tmp.configToNormGroup)) tmp.configToNormGroup <- lapply(WA_EOC_2012_2013.config, configToSGPNormGroup) WA_SGP_Norm_Group_Preference_2012_2013 <- data.table( YEAR="2012_2013", rbindlist(tmp.configToNormGroup)) WA_SGP_Norm_Group_Preference <- rbind( WA_SGP_Norm_Group_Preference_2010_2011, WA_SGP_Norm_Group_Preference_2011_2012, WA_SGP_Norm_Group_Preference_2012_2013 ) WA_SGP_Norm_Group_Preference$SGP_NORM_GROUP <- as.factor(WA_SGP_Norm_Group_Preference$SGP_NORM_GROUP) ### Save result setkey(WA_SGP_Norm_Group_Preference, YEAR, SGP_NORM_GROUP) save(WA_SGP_Norm_Group_Preference, file="WA_SGP_Norm_Group_Preference.Rdata")
3b3caf8386ba4fe774b8ea4f230b86b19f77e9cb
f095bf142246d6d1785e419333aa6b06453b92e8
/Get & Clean Data/week4.R
09fe40b73ea47fc8c2e604e07e1a47af60403da3
[]
no_license
mornkey/datasciencecoursera
82f0fc087b7d441240e04e649332d18b1f46674a
6951a03bafca8dad2b77aceb294936e38d84d572
refs/heads/master
2020-05-27T06:28:49.788246
2019-08-07T08:28:34
2019-08-07T08:28:34
188,522,360
0
0
null
null
null
null
UTF-8
R
false
false
2,817
r
week4.R
# fixing character variables URL <- 'https://data.baltimorecity.gov/api/views/dz54-2aru/rows.csv?accessType=DOWNLOAD' download.file(URL,destfile = './camera.csv',method = 'curl') data <- read.csv('camera.csv') names(data) tolower(names(data)) # convert characters to lowercases toupper(names(data))# convert characters to uppercases x <-strsplit(names(data),'\\.') x[6] # split 'location.1' to 'location' and '1' , output as list x[[6]][1] # call the first string which is 'location' x[[6]][2] # useful string functions library(stringr) nchar('nontapat sumalnop') # 17 nchar('nontapatsumalnop') # 16, spaces also counted as 1 cha substr('nontapat sumalnop',1,8) # "nontapat", take out only pos 1:8 paste('nontapat','sumalnop',sep = '-') # "nontapat-sumalnop" paste0('nontapat','sumalnop') # "nontapatsumalnop" , default to no space str_trim(' nontapat ') # "nontapat" , trim out extra spaces at the beginning and the end # names of variables should be ! # lower cases when possible, easy to read and understand, no duplicate, dont have characters like _ . , or white spaces # variables with characer values : should be made into factor variables ### working with DATES d <- date() # gives date and time : "Wed Jul 17 13:44:23 2019" class(d) # character d2 <- Sys.Date() # gives only date : "2019-07-17" class(d2) # class : Date # formatting dates # %d : day as number(0-31), %a : abbreviated weekday (Mon,Wed etc.), %A : unabbreviated weekday # %m : month as number (00-12), %b : abbreviated month, %B : unabbreviated month # %y : 2 digits year, %Y : four digits year format(d2,'%a%b%d') # can use with or without spaces format(d2,'%a %d %b %Y') # take vector of strings and convert as date x <- c('1jan1960','2jan1995','27oct1997');z <- as.Date(x,'%d%b%Y') # as.Date takes input as pattern of text you want to convert but the output is formatted in the form of %Y-%m-%d format(z,'%a %d %b %Y') # take output from as.Date as input of format() x <- c('1jan1960','2jan1995','27oct1997');z <- as.Date(x,'%d%b%Y');format(z,'%a %d %b %Y') y <- c('1-oct-2001','7-aug-1997');z <- as.Date(y,'%d-%b-%Y');format(z,'%a %d %b %Y') # date objects can perform these operation like ... z[1]-z[2] # Time difference of 1516 days as.numeric(z[1]-z[2]) # 1516 z[2]-z[1] # Time difference of -1516 days as.numeric(z[2]-z[1]) # -1516 # converting to Julian ... weekdays(z) months(z) julian(z) # number of days since the origin # Lubridate package library(lubridate) x <- c('2014.01.08','2010-10-22'); ymd(x) # any . / - or spaces will no longer troubles you anymore x <- c('08/04/1989');mdy(x) x <- c('27-10-1997','07 08 1997') ; dmy(x) x <- Sys.time();ymd_hms(x) ymd_hms('2011 08 03 10:15:03',tz='Asia/Bangkok') # can also set time zone Sys.timezone() # find your time zone # Free Data Resource : see in dir
b5ef122606879f8d2a82cf7f1585beb3d0f758af
4755427593f4e0f5a162640d6de1041110e63763
/cursus/data/matrix.R
5885404eb0c286c7a45517bdc03bce211be0f10b
[]
no_license
HoGentTIN/onderzoekstechnieken-cursus
5e642d984ab422f1d001984463f0e693f89e9637
bd7e61aa8d2a0a4525de82774568954c76dd33ae
refs/heads/master
2022-06-28T05:09:34.694920
2022-06-21T13:35:59
2022-06-21T13:35:59
80,239,413
21
59
null
2020-05-25T06:56:06
2017-01-27T19:35:24
HTML
UTF-8
R
false
false
485
r
matrix.R
> A = matrix( + c(2, 4, 3, 1, 5, 7), # the data elementen + nrow=2, # aantal rijen + ncol=3, # aantal kolommen + byrow = TRUE) # vul de matrix aan per rij > A # print de matrix [,1] [,2] [,3] [1,] 2 4 3 [2,] 1 5 7 > A[2, 3] # element op 2de rij, 3de kolom [1] 7 > A[2, ] # de 2de rij [1] 1 5 7 > A[ ,c(1,3)] # de eerste en de derde kolom [,1] [,2] [1,] 2 3 [2,] 1 7
7846b63dc7d37468734c5ffc4816be4b5390d56b
86772a78af6ca3567ed333c9a4cd68c5af73848d
/examples/Digits recognition 10 logistics/all_digits_new.r
861e1a4747a4f54969902f4cf8f28a0024f4a9ab
[]
no_license
aliaksah/EMJMCMC2016
077170db8ca4a21fbf158d182f551b3814c6c702
3954d55fc45296297ee561e0f97f85eb5048c39e
refs/heads/master
2023-07-19T16:52:43.772170
2023-07-15T16:05:37
2023-07-15T16:05:37
53,848,643
17
5
null
2021-11-25T14:53:35
2016-03-14T10:51:06
R
UTF-8
R
false
false
6,754
r
all_digits_new.r
source("https://raw.githubusercontent.com/aliaksah/EMJMCMC2016/master/R/the_mode_jumping_package4.r") estimate.glm.cpen.slow <- function(formula, data, family, logn,r = 0.1,relat =c("gone","gthird","sigmoid","tanh","atan","erf","gfifth","grelu")) { capture.output({out <- glm(family = family,formula = formula,data = data)}) fmla.proc<-as.character(formula)[2:3] fobserved <- fmla.proc[1] fmla.proc[2]<-stri_replace_all(str = fmla.proc[2],fixed = " ",replacement = "") fmla.proc[2]<-stri_replace_all(str = fmla.proc[2],fixed = "\n",replacement = "") sj<-2*(stri_count_fixed(str = fmla.proc[2], pattern = "*")) sj<-sj+1*(stri_count_fixed(str = fmla.proc[2], pattern = "+")) for(rel in relat) sj<-sj+2*(stri_count_fixed(str = fmla.proc[2], pattern = rel)) mlik = ((-out$deviance +2*log(r)*sum(sj)))/2 return(list(mlik = mlik,waic = -(out$deviance + 2*out$rank) , dic = -(out$deviance + logn*out$rank),summary.fixed =list(mean = coefficients(out)))) } estimate.glm.cpen <- function(formula, data, family, logn,r = 0.1,relat =c("gone","gthird","sigmoid","tanh","atan","erf","gfifth","grelu")) { #capture.output({out <- speedglm::speedglm(family = family,formula = formula,data = data)}) capture.output({out <- glm(family = family,formula = formula,data = data)}) fmla.proc<-as.character(formula)[2:3] fobserved <- fmla.proc[1] fmla.proc[2]<-stri_replace_all(str = fmla.proc[2],fixed = " ",replacement = "") fmla.proc[2]<-stri_replace_all(str = fmla.proc[2],fixed = "\n",replacement = "") sj<-2*(stri_count_fixed(str = fmla.proc[2], pattern = "*")) sj<-sj+1*(stri_count_fixed(str = fmla.proc[2], pattern = "+")) for(rel in relat) sj<-sj+2*(stri_count_fixed(str = fmla.proc[2], pattern = rel)) mlik = ((-out$deviance +2*log(r)*sum(sj)))/2 return(list(mlik = mlik,waic = -(out$deviance + 2*out$rank) , dic = -(out$deviance + logn*out$rank),summary.fixed =list(mean = coefficients(out)))) } parall.gmj <<- mclapply digits <- read.table(file = "train.csv",sep = ",",header = T,fill=TRUE) digits$Y1<-as.integer(digits$label==1) digits$Y2<-as.integer(digits$label==2) digits$Y3<-as.integer(digits$label==3) digits$Y4<-as.integer(digits$label==4) digits$Y5<-as.integer(digits$label==5) digits$Y6<-as.integer(digits$label==6) digits$Y7<-as.integer(digits$label==7) digits$Y8<-as.integer(digits$label==8) digits$Y9<-as.integer(digits$label==9) digits$Y10<-as.integer(digits$label==10) #digits<-digits[,-which(colSums(digits)==0)] g<-function(x) { return((x = 1/(1+exp(-x)))) } index <- sample.int(n = dim(digits)[1],size = dim(digits)[1]*0.025,replace = F) test <- digits[-index, ] train <- digits[index, ] data.example <- as.data.frame(train,stringsAsFactors = T) runpar<-function(vect) { set.seed(as.integer(vect[23])) do.call(runemjmcmc, vect[1:22]) ppp<-mySearch$post_proceed_results_hash(hashStat = hashStat) ppp$p.post Nvars<-mySearch$Nvars linx <-mySearch$Nvars+4 lHash<-length(hashStat) mliks <- values(hashStat)[which((1:(lHash * linx)) %% linx == 1)] betas <- values(hashStat)[which((1:(lHash * linx)) %% linx == 4)] cterm<-max(values(hashStat)[1,],na.rm = T) post.populi<-sum(exp(values(hashStat)[1,][1:1000]-cterm),na.rm = T) for(i in 1:(Nvars-1)) { betas<-cbind(betas,values(hashStat)[which((1:(lHash * linx)) %% linx == (4+i))]) } betas<-cbind(betas,values(hashStat)[which((1:(lHash * linx)) %% linx == (0))]) t<-system.time({ res<-mySearch$forecast.matrix.na(link.g = g, covariates = (vect$test),betas = betas,mliks.in = mliks)$forecast }) rm(betas) rm(mliks) clear(hashStat) rm(hashStat) return(list(p.post = ppp$p.post, fparam = mySearch$fparam, res = res, post.populi = post.populi, cterm = cterm)) } gc() gone<-function(x)as.integer(x>1) gthird<-function(x)as.integer(abs(x)^(1/3)) gfifth<-function(x)as.integer(abs(x)^(1/5)) grelu<-function(x)as.integer(x*(x>0)) total = array(0,dim = c(10,10,3)) M<-32 for(dig in 4:1) { print(dig) idss<-which(abs(cor(x = train[1:785],y=train[785+dig]))>0.01) formula1 = as.formula(paste(colnames(train)[785+dig],"~ 1 +",paste0(colnames(train)[idss][-1],collapse = "+"))) vect<-list(formula = formula1,data = data.example,estimator =estimate.glm.cpen,estimator.args = list(data = data.example,family = binomial(), logn = log(dim(train)[1]),r=exp(-0.5)),recalc_margin = 95,locstop=T,presearch=F,save.beta = T,interact = T,relations = c("gone","gthird","sigmoid","tanh","atan","erf","gfifth","grelu"),relations.prob =c(0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1),interact.param=list(allow_offsprings=3,mutation_rate = 100,last.mutation=2500, max.tree.size = 20, Nvars.max =200,p.allow.replace=0.7,p.allow.tree=0.5,p.nor=0.3,p.and = 0.7),n.models = 30000,unique =F,max.cpu = 4,max.cpu.glob = 4,create.table = F,create.hash = T,pseudo.paral = T,burn.in = 100,print.freq = 1000,advanced.param = list( max.N.glob=as.integer(10), min.N.glob=as.integer(5), max.N=as.integer(3), min.N=as.integer(1), printable = F)) length(vect) params <- list(vect)[rep(1,M)] for(jj in 1:M) { params[[jj]]$cpu<-jj params[[jj]]$test<-test } gc() length(params[[1]]) results<-parall.gmj(X = params,FUN = runpar,mc.preschedule = F, mc.cores = M,mc.cleanup = T) cbind(results[[1]]$fparam,results[[1]]$p.post) post.popul <- array(0,M) max.popul <- array(0,M) nulls = NULL for(k in 1:M) { if(length(results[[k]])==1||length(results[[k]]$cterm)==0) { nulls<-c(nulls,k) next } else { not.null <- k } } for(k in 1:M) { if(k %in% nulls) { results[[k]]<-results[[not.null]] } max.popul[k]<-results[[k]]$cterm post.popul[k]<-results[[k]]$post.populi } ml.max<-max(max.popul) post.popul<-post.popul*exp(-ml.max+max.popul) p.gen.post<-post.popul/sum(post.popul) res1 = array(0,dim = length(results[[1]]$res)) for(i in 1:M) { if(length(which(is.na(results[[i]]$res)))>0) next res1<-res1+results[[i]]$res*p.gen.post[i] } for(jjjj in 1:10) { res = as.integer(res1>=0.1*jjjj) prec<-(1-sum(abs(res-test[,785+dig]),na.rm = T)/length(res)) #FNR ps<-which(test[,785+dig]==1) fnr<-sum(abs(res[ps]-test[,785+dig][ps]))/(sum(abs(res[ps]-test[,785+dig][ps]))+length(ps)) #FPR ns<-which(test[,785+dig]==0) fpr<-sum(abs(res[ns]-test[,785+dig][ns]))/(sum(abs(res[ns]-test[,785+dig][ns]))+length(ns)) total[dig,jjjj,1]=prec total[dig,jjjj,2]=fnr total[dig,jjjj,3]=fpr print(prec) } write.csv(file ="results.csv",x=total) write.csv(file =paste0("res",dig,".csv"),x=res1) rm(results) gc() }
d56b528e942421dfcc2c52783a1a374a9f03702e
1b840fb7602d2bb94adb38f0500a85fd9027bc89
/Excluded_from_manuscript/Scripts/RR_cv_by_tree.R
37cb44bd9cd4252aff47d6e3662ca9851223deb3
[ "MIT" ]
permissive
sgraham9319/TreeGrowth
d23be1521050082015c44db227060e953ee1adec
703fb7fc70536ba9b0549100bb14d713dcedea2b
refs/heads/main
2023-04-12T13:31:24.377864
2022-02-12T16:32:05
2022-02-12T16:32:05
353,162,167
0
0
null
null
null
null
UTF-8
R
false
false
3,907
r
RR_cv_by_tree.R
library(dplyr) # Define required functions z_trans <- function(x){(x - mean(x)) / sd(x)} coef_det <- function(x){ 1 - (sum((x$observations - x$predictions)^2) / sum((x$observations - mean(x$observations))^2)) } # Define focal species focal_sps <- "ABAM" # Load training data train <- read.csv(paste("Data/Output_data/training1.csv", sep = ""), stringsAsFactors = F) # Subset to focal species train <- train %>% filter(species == focal_sps) # Create vector of common competitors comm_comps <- names(which(table(train$sps_comp) > 100)) # Reduce to one row per tree id train <- train %>% group_by(tree_id) %>% filter(row_number() == 1) %>% ungroup() # Extract observations obs <- train %>% select(tree_id, size_corr_growth) # Create column for density of rare species train <- train %>% mutate(rare_density = abs( all_density - apply(train %>% select(paste(comm_comps, "density", sep = "_")), 1, sum))) # Select columns required by model train <- train %>% select(size_corr_growth, all_density, paste(comm_comps, "density", sep = "_"), rare_density, precip_mm, temp_C, elev_m, aet_mm, pet_mm) # Remove any columns containing only zeros train <- train %>% select(-which(apply(train, 2, sum) == 0)) # Define outcome variable outcome_var <- "size_corr_growth" # Create model formula object mod_form <- as.formula(paste(outcome_var, "~", paste(setdiff(names(train), outcome_var), collapse = "+"))) # Create design matrix dm <- model.matrix(mod_form, train) # Standardize variables except for first column (intercept) dm[, 2:ncol(dm)] <- apply(dm[, 2:ncol(dm)], 2, z_trans) # Change any columns of NaNs (no variation) to zeros dm[, which(is.nan(dm[1, ]))] <- 0 # Fit glmnet model mod <- glmnet::cv.glmnet(x = dm, y = train$size_corr_growth, family = "gaussian") # Plot lambda vs. MSE plot(mod) # Make predictions for training data preds <- predict(mod, newx = dm, s = "lambda.1se") # Combine predictions with observations obs_pred <- cbind(obs, preds) names(obs_pred) <- c("tree_id", "observations", "predictions") # Calculate coefficient of determination R_squared <- coef_det(obs_pred) # Load test data test <- read.csv(paste("Data/Output_data/test1.csv", sep = ""), stringsAsFactors = F) # Reduce to one row per tree id and subset to focal species test <- test %>% group_by(tree_id) %>% filter(row_number() == 1 & species == focal_sps) %>% ungroup() # Extract observations obs_test <- test %>% select(tree_id, size_corr_growth) # Create column for density of rare species test <- test %>% mutate(rare_density = abs( all_density - apply(test %>% select(paste(comm_comps, "density", sep = "_")), 1, sum))) # Select columns required by model test <- test %>% select(size_corr_growth, all_density, paste(comm_comps, "density", sep = "_"), rare_density, precip_mm, temp_C, elev_m, aet_mm, pet_mm) # Remove any columns containing only zeros test <- test %>% select(-which(apply(test, 2, sum) == 0)) # Create test design matrix dm_test <- model.matrix(mod_form, test) # Standardize variables except for first column (intercept) dm_test[, 2:ncol(dm_test)] <- apply(dm_test[, 2:ncol(dm_test)], 2, z_trans) # Change any columns of NaNs (no variation) to zeros dm_test[, which(is.nan(dm_test[1, ]))] <- 0 # Make predictions for test data preds_test <- predict(mod, newx = dm_test, s = "lambda.1se") # Combine predictions with observations obs_pred_test <- cbind(obs_test, preds_test) names(obs_pred_test) <- c("tree_id", "observations", "predictions") # Calculate coefficient of determination R_squared_test <- coef_det(obs_pred_test) # Check coefficients of 1se model coef(mod)
c3c01896378fefc936357905e40702dcfb803dee
71a1c5fc44d44efde09b576b0a8709694619b609
/man/state_opinion.Rd
ba0f6c6c27be84196c01becc82c47300af3f4f46
[]
no_license
cwarshaw/dgirt
d3cb7650636cc077125c1897f27c8b07b7776002
0c2b334490b998ba3cf6bf06219e96124a39b34c
refs/heads/master
2021-01-18T18:44:38.609943
2016-03-18T16:42:36
2016-03-18T16:42:36
54,498,307
0
0
null
2016-03-22T18:14:15
2016-03-22T18:14:14
null
UTF-8
R
false
true
529
rd
state_opinion.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/data-state_opinion.r \docType{data} \name{state_opinion} \alias{state_opinion} \title{State-level policy item responses} \format{A `dplyr` `tbl_df` with 295,248 rows and 33 columns.} \usage{ state_opinion } \description{ A dataset of survey item responses and characteristics of respondents. Data are from the Cooperative Congressional Election Study (CCES) 2006-2014. `Q_` prepends the names of item response variables. } \examples{ state_opinion }
6e22697f510e6b14950d551896942e1f7d1ed87c
5021ebeb63a466032093215e7f7f098c5f49344a
/plot1.R
21bbe57ca5fc0fcdce555a73897f87e2ffee3a19
[]
no_license
abolick/ExData_Plotting1
ec41592ccfc04a44432d4ff21d4e6a1dd62a9538
8b817cd017158a6796b195c176b6b6b9ccd6d2a9
refs/heads/master
2021-01-24T23:51:44.484929
2015-01-12T00:04:20
2015-01-12T00:04:20
29,080,835
0
0
null
2015-01-11T04:05:10
2015-01-11T04:05:09
null
UTF-8
R
false
false
578
r
plot1.R
data <- read.table(file = "household_power_consumption.txt", sep = ";", skip = 66637, nrows = 2880, na.strings= "?") a <- colnames(read.table("household_power_consumption.txt", sep = ";",nrow = 1, header = TRUE)) # assign column names to data names(data) <- a str(data) #creates png file png("plot1.png",width =480,height=480) hist(data$Global_active_power,col="red", main ="Global Active Power", xlab="Global Active Power (kilowatts)") dev.off()
7ed5dee5bb09f1fb45f6b9ec05e5f14d8485a13b
2bec5a52ce1fb3266e72f8fbeb5226b025584a16
/ProFound/man/profoundSegimGroup.Rd
ef3702e0adbf54f0fd0510adb5c13f4b4175429f
[]
no_license
akhikolla/InformationHouse
4e45b11df18dee47519e917fcf0a869a77661fce
c0daab1e3f2827fd08aa5c31127fadae3f001948
refs/heads/master
2023-02-12T19:00:20.752555
2020-12-31T20:59:23
2020-12-31T20:59:23
325,589,503
9
2
null
null
null
null
UTF-8
R
false
false
3,094
rd
profoundSegimGroup.Rd
\name{profoundSegimGroup} \alias{profoundSegimGroup} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Create Segmentation Groups } \description{ Given an input segmentation map, returns a map of groups of touching segments as well as the IDs of segments within each group. } \usage{ profoundSegimGroup(segim = NULL) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{segim}{ Integer matrix; required, the segmentation map. } } \details{ To use this function you will need to have EBImage installed. Since this can be a bit cumbersome on some platforms (given its dependencies) this is only listed as a suggested package. You can have a go at installing it by running: > source("http://bioconductor.org/biocLite.R") > biocLite("EBImage") Linux users might also need to install some non-standard graphics libraries (depending on your install). If you do not have them already, you should look to install **jpeg** and **tiff** libraries (these are apparently technically not entirely free, hence not coming by default on some strictly open source Linux variants). \code{profoundSegimGroup} uses the \code{bwlabel} function from EBImage. } \value{ A list containting the following structures: \item{groupim}{An map of the unique groups identified in the input \option{segim}, where the groupID is the same as the lowest valued segID in the group.} \item{groupsegID}{A data.frame of lists giving the segIDs of segments in each group.} The data.frame returned by \option{groupsegID} is a slightly unusal structure to see in R, but it allows for a compact manner of storing uneven vectors of grouped segments. E.g. you might have a massive group containing 30 other segments and many groups containing a single segment. Padding a normal matrix out to accommodate the larger figure would be quite inefficient. It contains the following: \item{groupID}{Group ID, which can be matched against values in \option{groupim}} \item{segID}{An embedded list of segmentation IDs for segments in the group. I.e. each list element of \option{segID} is a vector (see Examples for clarity).} \item{Ngroup}{The total number of segments that are in the group.} \item{Npix}{The total number of pixels that are in the group.} } \author{ Aaron Robotham } \seealso{ \code{\link{profoundSegimNear}}, ~~~ } \examples{ \dontrun{ image=readFITS(system.file("extdata", 'VIKING/mystery_VIKING_Z.fits', package="ProFound")) profound=profoundProFound(image, skycut=1.5, magzero=30, verbose=TRUE) #Look for nearby (in this case touching) neighbours group=profoundSegimGroup(profound$segim) #Look at the first few rows (groups 1:5): group$groupsegID[1:5,] #To access the embedded vectors you have to use unlist: unlist(group$groupsegID[1,2]) #We can check to see which segments are in group number 1: profoundSegimPlot(image$imDat, profound$segim) magimage(group$groupim==1, col=c(NA,'red'), add=TRUE) } } % Add one or more standard keywords, see file 'KEYWORDS' in the % R documentation directory. \concept{ segments }% use one of RShowDoc("KEYWORDS")
3206bcb3d8f46c110a763816be879ae81197e80a
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
/data/genthat_extracted_code/RPPanalyzer/examples/select.sample.group.Rd.R
3b9b4844eed7142abe9096cab2b3e4a57f470454
[]
no_license
surayaaramli/typeRrh
d257ac8905c49123f4ccd4e377ee3dfc84d1636c
66e6996f31961bc8b9aafe1a6a6098327b66bf71
refs/heads/master
2023-05-05T04:05:31.617869
2019-04-25T22:10:06
2019-04-25T22:10:06
null
0
0
null
null
null
null
UTF-8
R
false
false
289
r
select.sample.group.Rd.R
library(RPPanalyzer) ### Name: select.sample.group ### Title: Selects samples from RPPA data ### Aliases: select.sample.group ### Keywords: manip ### ** Examples library(RPPanalyzer) data(dataII) selectedData <- select.sample.group(dataII,params=list("stimulation"=c("A","B")))
5fd06a106dc59ecea4804092bbcad1b74283d77c
0273c7facf88bc6c4320f368063d9545b1523f8a
/src/lemma_ngrams.R
1e1224bba47fbcfc2a8d94ca789611daab4a0003
[]
no_license
mnbram/boardgameanalysis
a5f7d169e813c2481165909497dbf24ba3025186
292a0b4da4bd8246636239ebc44022b736b57df5
refs/heads/master
2021-01-16T18:10:48.364226
2017-08-11T16:10:40
2017-08-11T16:10:40
100,047,861
0
0
null
null
null
null
UTF-8
R
false
false
3,205
r
lemma_ngrams.R
library(tidyverse) library(tidytext) library(stringr) library(glmnet) library(doParallel) setwd("~/bgg/kickstarter") lemma_files <- list.files("data/lemmas", full.names = TRUE) texts <- lapply(lemma_files, readLines) text_lengths <- map_int(texts, length) kids <- map_int(lemma_files, function(x) as.integer(str_match(x, "[0-9]+"))) lemmas <- tibble( k_id = rep(kids, text_lengths), text = unlist(texts) ) rm(texts) # Remove lemmatized pronouns and parsing mistakes as stop words stop_plus <- c(stop_words$word, "pron", "â") unigrams_bow <- lemmas %>% unnest_tokens(type, text) %>% count(k_id, type, sort = TRUE) %>% ungroup() %>% filter(!type %in% stop_plus) %>% mutate(type = str_replace_all(type, fixed("_"), "-")) bigrams_bow <- lemmas %>% unnest_tokens(type, text, token = "ngrams", n = 2) %>% count(k_id, type, sort = TRUE) %>% ungroup() %>% separate(type, c("word1", "word2"), sep = " ") %>% filter( !word1 %in% stop_plus, !word2 %in% stop_plus ) %>% unite(type, word1, word2, sep = "__") common <- rbind(unigrams_bow, bigrams_bow) %>% group_by(type) %>% summarize(freq_in_campaigns = length(unique(k_id))/length(lemma_files)) %>% filter(freq_in_campaigns >= 0.001) sparse_unibi_bow <- rbind(unigrams_bow, bigrams_bow) %>% filter(type %in% common$type) %>% cast_sparse(k_id, type) br_data <- read_delim("data/benrugg.csv", delim = ",", escape_backslash = TRUE, escape_double = FALSE) %>% filter( sub_category == "Tabletop Games", kickstarter_id %in% kids ) %>% select(kickstarter_id, state) %>% slice(match(as.integer(rownames(sparse_unibi_bow)), kickstarter_id)) states <- setNames(ifelse(br_data$state == "successful", 1, 0), br_data$kickstarter_id) %>% as.matrix() colnames(states) <- "success_" sparse_results_bow <- cbind(states, sparse_unibi_bow) registerDoParallel(cores = 6) penalties <- rep(1, ncol(sparse_results_bow)-1) penalties[grep("__", colnames(sparse_results_bow[,-1]))] <- 0.5 glm_coefs <- function() { glm_bow <- cv.glmnet( sparse_results_bow[,-1], as.factor(sparse_results_bow[,1]), alpha = 1, family = "binomial", penalty.factor = penalties, standardize = FALSE, type.measure = "auc", parallel = TRUE) coef(glm_bow, s = "lambda.min") %>% tidy() %>% filter(value != 0) } set.seed(984) glm_coefs_cv <- lapply(1:100, function(x) glm_coefs()) glm100_coef <- lapply(glm_coefs_cv, function(x) { x %>% filter(row != "(Intercept)") %>% select(row, value) %>% as_tibble() }) %>% bind_rows() %>% group_by(row) %>% summarize(n = n(), mean = mean(value)) %>% arrange(desc(n), desc(abs(mean))) term_counts <- apply(sparse_unibi_bow, 2, sum) term_freqs <- tidy(term_counts) %>% filter(names %in% glm100_coef$row) %>% mutate(freq = x/nrow(sparse_unibi_bow)) glm100_coef_full <- glm100_coef %>% left_join(term_freqs, by = c("row" = "names")) %>% rename(term = row, nmodels = n, coef = mean) %>% select(term, nmodels, coef, freq) write_csv(glm100_coef_full, "glm100_coef_all.csv")
7868deaf2b701ffd634651d6e0fdea21e6c3fe0a
6dbd098f38a9dc01a837a65a4ce633282c59c108
/scripts/mtbls520_18_phylogeny.r
cd3e669ef0b1ad9b2850ad5e0438e9d7b17b0fc2
[ "Apache-2.0" ]
permissive
korseby/container-mtbls520
82b656267c2fdfc6beffe8c312395bc304945e25
04b55283e3698a82111fa4531198915e556ba2a4
refs/heads/master
2021-06-17T06:00:45.219498
2019-08-09T06:06:58
2019-08-09T06:06:58
107,677,250
1
2
null
null
null
null
UTF-8
R
false
false
4,154
r
mtbls520_18_phylogeny.r
#!/usr/bin/env Rscript # ---------- Load R environment ---------- # Setup R error handling to go to stderr options(show.error.messages=F, error=function() { cat(geterrmessage(), file=stderr()); q("no",1,F) } ) # Set proper locale loc <- Sys.setlocale("LC_MESSAGES", "en_US.UTF-8") loc <- Sys.setlocale(category="LC_ALL", locale="C") # Set options options(encoding="UTF-8") options(stringAsfactors=FALSE, useFancyQuotes=FALSE) # Take in trailing command line arguments args <- commandArgs(trailingOnly=TRUE) if (length(args) < 4) { print("Error! No or not enough arguments given.") print("Usage: $0 input.rdata moss_phylo.tre procrustes.pdf phylogeny.pdf") quit(save="no", status=1, runLast=FALSE) } # Load R environment load(file=args[1]) args <- commandArgs(trailingOnly=TRUE) # Load libraries library(vegan) library(ape) library(pvclust) library(dendextend) library(cba) library(phangorn) # ---------- Phylogeny ---------- # Read phylogenetic tree phylo_tree <- read.tree(args[2]) # Replace names with species codes phylo_index <- match(substr(phylo_tree$tip.label,1,3), as.character(lapply(X=species_names, FUN=function(x) { x <- substr(x,1,3) }))) phylo_tree$tip.label <- as.character(species_names[phylo_index]) # Cophenetic distance matrix, needed for mpd and mntd calculations below phylo_dist <- cophenetic.phylo(phylo_tree) # Distance matrix of phylogenetic tree using Bray-Curtis phylo_dist <- vegdist(phylo_dist, method="bray") # Hierarchical clustering phylo_hclust <- hclust(phylo_dist, method="complete") # Merge feat_list for species from samples feat_list_species <- NULL for (i in species_names) feat_list_species <- rbind(feat_list_species, apply(X=feat_list[species==i,], MARGIN=2, FUN=function(x) { median(x) } )) rownames(feat_list_species) <- species_names # Reorder rows according to phylogenetic tree order feat_list_species <- feat_list_species[phylo_index,] # Distance matrix of feat_list using Bray-Curtis feat_dist <- vegdist(feat_list_species, method="bray") # Hierarchical clustering feat_hclust <- hclust(feat_dist, method="complete") # Optimal order feat_opti <- order.optimal(feat_dist, feat_hclust$merge) feat_oclust <- feat_hclust feat_oclust$merge <- feat_opti$merge feat_oclust$order <- feat_opti$order # pos-mode: Manually rotate "Polstr" + "Plaund" branches if (polarity == "positive") { feat_oclust <- reorder(feat_oclust, c(1, 2, 4, 5, 3, 9, 6, 8, 7)) } # neg-mode: Manually rotate branches if (polarity == "negative") { feat_oclust <- reorder(feat_oclust, c(1, 2, 3, 6, 4, 8, 7, 5, 9)) } # Procrustes analysis model_procrust <- protest(X=phylo_dist, Y=feat_dist, permutations=10000) pdf(file=args[3], encoding="ISOLatin1", pointsize=10, width=5, height=5, family="Helvetica") plot(model_procrust) dev.off() # Mantel test model_mantel <- mantel(xdis=phylo_dist, ydis=feat_dist, method="pearson", permutations=10000) # Correlation tests model_cor <- cor(phylo_dist, feat_dist, method="pearson") model_cop <- cor_cophenetic(hclust(phylo_dist), hclust(feat_dist), method="pearson") # Robinson-Foulds metric RF.dist(phylo_tree, as.phylo(feat_oclust), normalize=TRUE, check.labels=TRUE, rooted=TRUE) # Plot phylogenetic tree pdf(args[4], encoding="ISOLatin1", pointsize=12, width=8, height=5, family="Helvetica") par(mfrow=c(1,2), mar=c(1,1,2,1), cex=1.0) plot(phylo_tree, type="phylogram", direction="rightwards", x.lim=c(0,11), label.offset=0.4, use.edge.length=TRUE, show.tip.label=TRUE, tip.color=species_colors[phylo_index], font=2, main="") mtext(text="(a)", adj=0, line=0.5, font=2, cex=1.2) plot(as.phylo(feat_oclust), type="phylogram", direction="leftwards", x.lim=c(0,0.5), label.offset=0.01, use.edge.length=TRUE, show.tip.label=TRUE, tip.color=species_colors[phylo_index], font=2, main="") mtext(text="(b)", adj=0, line=0.5, font=2, cex=1.2) dev.off() # r = Mantel print(paste("Mantel statistic:", round(model_mantel$statistic,3))) # c = cor_cophenetic print(paste("Correlation:", round(model_cop,3))) # rf = Robinson-Foulds print(paste("Robinson-Foulds metric:", round(RF.dist(phylo_tree, as.phylo(feat_oclust), normalize=TRUE, check.labels=TRUE, rooted=TRUE), 3)))
6c6d9b21114f1cc4d6445d296450f5e6b788ae7e
a614846a4bfbb4432aaff0aca0105682e95e9167
/R/supplements/preprocess-Senkler2018.R
039af5a6dc7162be9ef9859ea8cd75af27abc3ea
[]
no_license
skinnider/CF-MS-searches
58044f1363186b43878b2971927e6da738b63663
0851000f90e0324f9363b50ed779af5a68a16e76
refs/heads/master
2023-04-09T09:35:33.057903
2020-10-10T21:35:41
2020-10-10T21:35:41
302,994,048
0
0
null
null
null
null
UTF-8
R
false
false
711
r
preprocess-Senkler2018.R
# Preprocess data originally reported in the supporting materials of # Senkler et al., Curr Biol 2018. setwd("~/git/CF-MS-searches") options(stringsAsFactors = F) library(tidyverse) library(magrittr) library(readxl) # read file dat = read.delim( "data/supplements/Senkler2018/proteinGroups_results.txt.gz") %>% filter(Potential.contaminant != '+', Reverse != '+', Only.identified.by.site != '+') # extract iBAQ mat = dat %>% dplyr::select(starts_with('iBAQ.')) %>% as.matrix() %>% set_rownames(dat[[1]]) # remove proteins never quantified mat %<>% extract(rowSums(. > 0) > 0, ) # save as RDS replicates = list(map = mat) saveRDS(replicates, 'data/supplements/PXD008974.rds')
98f568cd69893a6da8a4653d35547413dcd4d4a0
9aafde089eb3d8bba05aec912e61fbd9fb84bd49
/codeml_files/newick_trees_processed_and_cleaned/11551_0/rinput.R
f96591cce4ca3898c88e62290dfb378807eacc78
[]
no_license
DaniBoo/cyanobacteria_project
6a816bb0ccf285842b61bfd3612c176f5877a1fb
be08ff723284b0c38f9c758d3e250c664bbfbf3b
refs/heads/master
2021-01-25T05:28:00.686474
2013-03-23T15:09:39
2013-03-23T15:09:39
null
0
0
null
null
null
null
UTF-8
R
false
false
137
r
rinput.R
library(ape) testtree <- read.tree("11551_0.txt") unrooted_tr <- unroot(testtree) write.tree(unrooted_tr, file="11551_0_unrooted.txt")
db66ed94c7c2c06dad6d215c70e4d96b50e89c05
df7b3a1eb6f65ac3e576f8b49ad385cb0303f2b0
/R/cbat.R
5838e3489b7d5a6769bc75895213a5424d4f4245
[ "MIT" ]
permissive
ykunisato/senshuRmd
0f974443ae343fc8f963e718f1d3b1102dbd3ae5
2f60fda7269985917f7d3e0dacb47a8666eb4590
refs/heads/master
2022-04-01T17:43:42.117858
2022-03-15T03:54:14
2022-03-15T03:54:14
217,082,796
7
2
null
null
null
null
UTF-8
R
false
false
14,669
r
cbat.R
#' @title Set template files for CBAT #' @importFrom utils download.file #' @importFrom utils unzip #' @param task_name name of task #' @param jsPsych_version If you set a specific version number of jsPsych, #' set_jsPsych prepare a file with that version of jsPsych. #' @param use_rc If you don"t use the RC, set FALSE. #' @examples # set_cbat("stroop") #' @export set_cbat <- function(task_name = "task_name", jsPsych_version = "7.1.2", use_rc = TRUE){ #check exercises directory if(use_rc == TRUE){ dir_names_cwd = basename(list.dirs()) if(sum(dir_names_cwd == "exercises") >= 1){ path = paste0(getwd(),"/exercises") dir.create(file.path(path, task_name), showWarnings = FALSE) path = paste0(path,"/",task_name) }else{ stop(paste("Error! Run the code in the directory where the 'exercises' directory is located.")) } }else{ path = getwd() dir.create(file.path(path, task_name), showWarnings = FALSE) path = paste0(path,"/",task_name) } # prepare the files and directories if(jsPsych_version == "6.3.1"){ ## make demo-.html file tmp_html <- file(file.path(path, paste0("demo_",task_name,".html")), "w") writeLines("<!DOCTYPE html>", tmp_html) writeLines("<html>", tmp_html) writeLines(" <head>", tmp_html) writeLines(' <meta charset="UTF-8" />', tmp_html) writeLines(paste0(' <script src="',task_name,'/jspsych-',jsPsych_version,'/jspsych.js"></script>'), tmp_html) writeLines(paste0(' <script src="',task_name,'/jspsych-',jsPsych_version,'/plugins/jspsych-fullscreen.js"></script>'), tmp_html) writeLines(paste0(' <script src="',task_name,'/jspsych-',jsPsych_version,'/plugins/jspsych-html-keyboard-response.js"></script>'), tmp_html) writeLines(paste0(' <script src="',task_name,'/jspsych-',jsPsych_version,'/plugins/jspsych-html-button-response.js"></script>'), tmp_html) writeLines(paste0(' <script src="',task_name,'/jspsych-',jsPsych_version,'/plugins/jspsych-survey-likert.js"></script>'), tmp_html) writeLines(paste0(' <script src="',task_name,'/jspsych-',jsPsych_version,'/plugins/jspsych-survey-multi-choice.js"></script>'), tmp_html) writeLines(paste0(' <script src="',task_name,'/jspsych-',jsPsych_version,'/plugins/jspsych-survey-multi-select.js"></script>'), tmp_html) writeLines(paste0(' <script src="',task_name,'/jspsych-',jsPsych_version,'/plugins/jspsych-survey-text.js"></script>'), tmp_html) writeLines(paste0(' <link rel="stylesheet" href="',task_name,'/jspsych-',jsPsych_version,'/css/jspsych.css" />'), tmp_html) writeLines(" </head>", tmp_html) writeLines(" <body></body>", tmp_html) writeLines(paste0(' <script type="text/javascript" src="',task_name,'/demo_fullscreen.js"></script>'), tmp_html) writeLines(paste0(' <script type="text/javascript" src="',task_name,'/task.js"></script>'), tmp_html) writeLines(paste0(' <script type="text/javascript" src="',task_name,'/demo_run.js"></script>'), tmp_html) writeLines("</html>", tmp_html) close(tmp_html) ## make -.html file tmp_html <- file(file.path(path, paste0(task_name,".html")), "w") writeLines("<!DOCTYPE html>", tmp_html) writeLines("<html>", tmp_html) writeLines(" <head>", tmp_html) writeLines(' <meta charset="UTF-8" />', tmp_html) writeLines(paste0(' <script src="',task_name,'/jspsych-',jsPsych_version,'/jspsych.js"></script>'), tmp_html) writeLines(paste0(' <script src="',task_name,'/jspsych-',jsPsych_version,'/plugins/jspsych-fullscreen.js"></script>'), tmp_html) writeLines(paste0(' <script src="',task_name,'/jspsych-',jsPsych_version,'/plugins/jspsych-html-keyboard-response.js"></script>'), tmp_html) writeLines(paste0(' <script src="',task_name,'/jspsych-',jsPsych_version,'/plugins/jspsych-html-button-response.js"></script>'), tmp_html) writeLines(paste0(' <script src="',task_name,'/jspsych-',jsPsych_version,'/plugins/jspsych-survey-likert.js"></script>'), tmp_html) writeLines(paste0(' <script src="',task_name,'/jspsych-',jsPsych_version,'/plugins/jspsych-survey-multi-choice.js"></script>'), tmp_html) writeLines(paste0(' <script src="',task_name,'/jspsych-',jsPsych_version,'/plugins/jspsych-survey-multi-select.js"></script>'), tmp_html) writeLines(paste0(' <script src="',task_name,'/jspsych-',jsPsych_version,'/plugins/jspsych-survey-text.js"></script>'), tmp_html) writeLines(' <script src="jatos.js"></script>', tmp_html) writeLines(paste0(' <link rel="stylesheet" href="',task_name,'/jspsych-',jsPsych_version,'/css/jspsych.css" />'), tmp_html) writeLines(" </head>", tmp_html) writeLines(" <body></body>", tmp_html) writeLines(paste0(' <script type="text/javascript" src="',task_name,'/jatos_fullscreen.js"></script>'), tmp_html) writeLines(paste0(' <script type="text/javascript" src="',task_name,'/task.js"></script>'), tmp_html) writeLines(paste0(' <script type="text/javascript" src="',task_name,'/jatos_run.js"></script>'), tmp_html) writeLines("</html>", tmp_html) close(tmp_html) ## make directory of repository dir.create(file.path(path, task_name), showWarnings = FALSE) ## download jsPsych temp_jsPsych <- tempfile() download.file(paste0('https://github.com/jspsych/jsPsych/releases/download/v',jsPsych_version,'/jspsych-',jsPsych_version,'.zip'),temp_jsPsych) unzip(temp_jsPsych, exdir = file.path(path, task_name)) unlink(temp_jsPsych) ## download js files file_path <- paste0(path,"/",task_name) download.file("https://raw.githubusercontent.com/ykunisato/template-jsPsych-task/main/template-jsPsych6.3/name_of_repository/task.js",paste0(file_path,"/task.js")) download.file("https://raw.githubusercontent.com/ykunisato/template-jsPsych-task/main/template-jsPsych6.3/name_of_repository/jatos_run.js",paste0(file_path,"/jatos_run.js")) download.file("https://raw.githubusercontent.com/ykunisato/template-jsPsych-task/main/template-jsPsych6.3/name_of_repository/jatos_fullscreen.js",paste0(file_path,"/jatos_fullscreen.js")) download.file("https://raw.githubusercontent.com/ykunisato/template-jsPsych-task/main/template-jsPsych6.3/name_of_repository/demo_run.js",paste0(file_path,"/demo_run.js")) download.file("https://raw.githubusercontent.com/ykunisato/template-jsPsych-task/main/template-jsPsych6.3/name_of_repository/demo_fullscreen.js",paste0(file_path,"/demo_fullscreen.js")) ## make stimli directory and picture dir.create(file.path(file_path, "stimuli"), showWarnings = FALSE) stim_path <- paste0(file_path,"/stimuli") download.file("https://raw.githubusercontent.com/ykunisato/template-jsPsych-task/main/template-jsPsych6.3/name_of_repository/stimuli/reward.jpeg",paste0(stim_path,"/reward.jpeg")) download.file("https://raw.githubusercontent.com/ykunisato/template-jsPsych-task/main/template-jsPsych6.3/name_of_repository/stimuli/punishment.jpeg",paste0(stim_path,"/punishment.jpeg")) download.file("https://raw.githubusercontent.com/ykunisato/template-jsPsych-task/main/template-jsPsych6.3/name_of_repository/stimuli/s1.jpeg",paste0(stim_path,"/s1.jpeg")) download.file("https://raw.githubusercontent.com/ykunisato/template-jsPsych-task/main/template-jsPsych6.3/name_of_repository/stimuli/s1s.jpeg",paste0(stim_path,"/s1s.jpeg")) download.file("https://raw.githubusercontent.com/ykunisato/template-jsPsych-task/main/template-jsPsych6.3/name_of_repository/stimuli/s2.jpeg",paste0(stim_path,"/s2.jpeg")) download.file("https://raw.githubusercontent.com/ykunisato/template-jsPsych-task/main/template-jsPsych6.3/name_of_repository/stimuli/s2s.jpeg",paste0(stim_path,"/s2s.jpeg")) }else if(substr(jsPsych_version, 1, 1)=="7"){ ## make demo-.html file tmp_html <- file(file.path(path, paste0("demo_",task_name,".html")), "w") writeLines("<!DOCTYPE html>", tmp_html) writeLines("<html>", tmp_html) writeLines(" <head>", tmp_html) writeLines(' <meta charset="UTF-8" />', tmp_html) writeLines(paste0(' <script src="',task_name,'/jspsych/dist/jspsych.js"></script>'), tmp_html) writeLines(paste0(' <script src="',task_name,'/jspsych/dist/plugin-fullscreen.js"></script>'), tmp_html) writeLines(paste0(' <script src="',task_name,'/jspsych/dist/plugin-html-keyboard-response.js"></script>'), tmp_html) writeLines(paste0(' <script src="',task_name,'/jspsych/dist/plugin-html-button-response.js"></script>'), tmp_html) writeLines(paste0(' <script src="',task_name,'/jspsych/dist/plugin-survey-likert.js"></script>'), tmp_html) writeLines(paste0(' <script src="',task_name,'/jspsych/dist/plugin-survey-multi-choice.js"></script>'), tmp_html) writeLines(paste0(' <script src="',task_name,'/jspsych/dist/plugin-survey-multi-select.js"></script>'), tmp_html) writeLines(paste0(' <script src="',task_name,'/jspsych/dist/plugin-survey-text.js"></script>'), tmp_html) writeLines(paste0(' <link href="',task_name,'/jspsych/dist/jspsych.css" rel="stylesheet" type="text/css" />'), tmp_html) writeLines(" </head>", tmp_html) writeLines(" <body></body>", tmp_html) writeLines(paste0(' <script type="text/javascript" src="',task_name,'/demo_jspsych_init.js"></script>'), tmp_html) writeLines(paste0(' <script type="text/javascript" src="',task_name,'/task.js"></script>'), tmp_html) writeLines(paste0(' <script type="text/javascript" src="',task_name,'/demo_jspsych_run.js"></script>'), tmp_html) writeLines("</html>", tmp_html) close(tmp_html) ## make -.html file tmp_html <- file(file.path(path, paste0(task_name,".html")), "w") writeLines("<!DOCTYPE html>", tmp_html) writeLines("<html>", tmp_html) writeLines(" <head>", tmp_html) writeLines(' <meta charset="UTF-8" />', tmp_html) writeLines(paste0(' <script src="',task_name,'/jspsych/dist/jspsych.js"></script>'), tmp_html) writeLines(paste0(' <script src="',task_name,'/jspsych/dist/plugin-fullscreen.js"></script>'), tmp_html) writeLines(paste0(' <script src="',task_name,'/jspsych/dist/plugin-html-keyboard-response.js"></script>'), tmp_html) writeLines(paste0(' <script src="',task_name,'/jspsych/dist/plugin-html-button-response.js"></script>'), tmp_html) writeLines(paste0(' <script src="',task_name,'/jspsych/dist/plugin-survey-likert.js"></script>'), tmp_html) writeLines(paste0(' <script src="',task_name,'/jspsych/dist/plugin-survey-multi-choice.js"></script>'), tmp_html) writeLines(paste0(' <script src="',task_name,'/jspsych/dist/plugin-survey-multi-select.js"></script>'), tmp_html) writeLines(paste0(' <script src="',task_name,'/jspsych/dist/plugin-survey-text.js"></script>'), tmp_html) writeLines(' <script src="jatos.js"></script>', tmp_html) writeLines(paste0(' <link href="',task_name,'/jspsych/dist/jspsych.css" rel="stylesheet" type="text/css" />'), tmp_html) writeLines(" </head>", tmp_html) writeLines(" <body></body>", tmp_html) writeLines(paste0(' <script type="text/javascript" src="',task_name,'/jatos_jspsych_init.js"></script>'), tmp_html) writeLines(paste0(' <script type="text/javascript" src="',task_name,'/task.js"></script>'), tmp_html) writeLines(paste0(' <script type="text/javascript" src="',task_name,'/jatos_jspsych_run.js"></script>'), tmp_html) writeLines("</html>", tmp_html) close(tmp_html) ## make directory of repository dir.create(file.path(path, task_name), showWarnings = FALSE) ## download jsPsych temp_jsPsych <- tempfile() if(jsPsych_version=="7.0.0"){ download.file(paste0('https://github.com/jspsych/jsPsych/releases/download/jspsych@7.0.0/jspsych-7.0.0-dist.zip'),temp_jsPsych) }else{ download.file(paste0('https://github.com/jspsych/jsPsych/releases/download/jspsych@',jsPsych_version,'/jspsych.zip'),temp_jsPsych) } unzip(temp_jsPsych, exdir = file.path(path, task_name,"jspsych")) unlink(temp_jsPsych) ## download js files file_path <- paste0(path,"/",task_name) download.file(paste0("https://raw.githubusercontent.com/ykunisato/template-jsPsych-task/main/template-jsPsych",substr(jsPsych_version, 1, 3),"/name_of_repository/task.js"),paste0(file_path,"/task.js")) download.file(paste0("https://raw.githubusercontent.com/ykunisato/template-jsPsych-task/main/template-jsPsych",substr(jsPsych_version, 1, 3),"/name_of_repository/demo_jspsych_init.js"),paste0(file_path,"/demo_jspsych_init.js")) download.file(paste0("https://raw.githubusercontent.com/ykunisato/template-jsPsych-task/main/template-jsPsych",substr(jsPsych_version, 1, 3),"/name_of_repository/demo_jspsych_run.js"),paste0(file_path,"/demo_jspsych_run.js")) download.file(paste0("https://raw.githubusercontent.com/ykunisato/template-jsPsych-task/main/template-jsPsych",substr(jsPsych_version, 1, 3),"/name_of_repository/jatos_jspsych_init.js"),paste0(file_path,"/jatos_jspsych_init.js")) download.file(paste0("https://raw.githubusercontent.com/ykunisato/template-jsPsych-task/main/template-jsPsych",substr(jsPsych_version, 1, 3),"/name_of_repository/jatos_jspsych_run.js"),paste0(file_path,"/jatos_jspsych_run.js")) ## make stimli directory and picture dir.create(file.path(file_path, "stimuli"), showWarnings = FALSE) stim_path <- paste0(file_path,"/stimuli") download.file(paste0("https://raw.githubusercontent.com/ykunisato/template-jsPsych-task/main/template-jsPsych",substr(jsPsych_version, 1, 3),"/name_of_repository/stimuli/reward.jpeg"),paste0(stim_path,"/reward.jpeg")) download.file(paste0("https://raw.githubusercontent.com/ykunisato/template-jsPsych-task/main/template-jsPsych",substr(jsPsych_version, 1, 3),"/name_of_repository/stimuli/punishment.jpeg"),paste0(stim_path,"/punishment.jpeg")) download.file(paste0("https://raw.githubusercontent.com/ykunisato/template-jsPsych-task/main/template-jsPsych",substr(jsPsych_version, 1, 3),"/name_of_repository/stimuli/s1.jpeg"),paste0(stim_path,"/s1.jpeg")) download.file(paste0("https://raw.githubusercontent.com/ykunisato/template-jsPsych-task/main/template-jsPsych",substr(jsPsych_version, 1, 3),"/name_of_repository/stimuli/s1s.jpeg"),paste0(stim_path,"/s1s.jpeg")) download.file(paste0("https://raw.githubusercontent.com/ykunisato/template-jsPsych-task/main/template-jsPsych",substr(jsPsych_version, 1, 3),"/name_of_repository/stimuli/s2.jpeg"),paste0(stim_path,"/s2.jpeg")) download.file(paste0("https://raw.githubusercontent.com/ykunisato/template-jsPsych-task/main/template-jsPsych",substr(jsPsych_version, 1, 3),"/name_of_repository/stimuli/s2s.jpeg"),paste0(stim_path,"/s2s.jpeg")) } }
17b8ae0afd75db9df279b75b2b82291b1eeae8e3
98c40fe72bfe9caafc3db5ca0a2c0944cad33988
/man/cutoff.Rd
6e26c2776cef2da629ff32393dd68ee41bd636d1
[]
no_license
datawookie/emayili
c91d38dc5bf0fc38cff45260dc0ba99bce7e754f
cb0f2f7e6c8738a30ddd88834abd88b63585244c
refs/heads/master
2023-09-01T00:02:36.105432
2023-08-30T10:49:01
2023-08-30T10:49:01
187,310,940
158
41
null
2023-08-03T06:52:34
2019-05-18T03:45:55
R
UTF-8
R
false
true
834
rd
cutoff.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/header-expires.R \name{cutoff} \alias{cutoff} \alias{expires} \alias{replyby} \title{Set or query message expiry or reply-by time} \usage{ expires(msg, datetime = NULL, tz = "") replyby(msg, datetime = NULL, tz = "") } \arguments{ \item{msg}{A message object.} \item{datetime}{Date and time.} \item{tz}{A character string specifying the time zone.} } \value{ A message object. } \description{ Functions to specify the time at which a message expires or by which a reply is requested. } \details{ Manipulate the \code{Expires} and \code{Reply-By} fields as specified in \href{https://www.ietf.org/rfc/rfc2156.txt}{RFC 2156}. } \examples{ envelope() \%>\% expires("2030-01-01 13:25:00", "UTC") envelope() \%>\% replyby("2021-12-25 06:00:00", "GMT") }
ab6eec1483b40483671588d84da8f92ed94bfdaa
9cc1af02c31ab3bdccd3822767121b56e6da4e68
/index_hoping_functions.R
d30e9cd276fe474f93ce95ea5ba603ccf2a294cd
[]
no_license
yy930/test
4e4146c889142909a9de0f1c218c36600a7e3e92
8558ee7544446e81cbaadc76c61bcee40ad89d64
refs/heads/master
2020-05-23T06:36:06.265372
2017-09-13T12:51:22
2017-09-13T12:51:22
56,673,274
0
0
null
null
null
null
UTF-8
R
false
false
33,501
r
index_hoping_functions.R
#heatmap for plate 1 visheatmap1<-function(.data, .title = "Number of shared clonotypes", .labs = c("Sample", "Sample"), .legend = "Shared clonotypes", .na.value = NA, .text = T, .scientific = FALSE, .signif.digits = 4, .size.text = 4, .no.legend = F, .no.labs = F) { if (has.class(.data, "data.frame")) { names <- .data[, 1] .data <- as.matrix(.data[, -1]) row.names(.data) <- names } if (is.null(colnames(.data))) { colnames(.data) <- paste0("C", 1:ncol(.data)) } if (is.null(row.names(.data))) { row.names(.data) <- paste0("C", 1:nrow(.data)) } .data[is.na(.data)] <- .na.value tmp <- as.data.frame(.data) tmp$name <- row.names(.data) m <- melt(tmp, id.var = c("name")) m[, 1] <- factor(m[, 1], levels = rev(rownames(.data))) m[, 2] <- factor(m[, 2], levels = colnames(.data)) .cg <- .colourblind.gradient(min(m$value), max(m$value)) #m$label <- format(m$value, scientific = .scientific, digits = .signif.digits) m$label <- as.vector(matrix(celltype$cell.type[1:96],nrow = 8, ncol=12, byrow=T))#!!!!!! p <- ggplot(m, aes(x = variable, y = name, fill = value)) p <- p + geom_tile(aes(fill = value), colour = "white") if (.text) { p <- p + geom_text(aes(fill = value, label = label), size = .size.text)#!!!!!!!!!! } p <- p + .cg p <- p + ggtitle(.title) + guides(fill = guide_colourbar(title = .legend)) + xlab(.labs[1]) + ylab(.labs[2]) + coord_fixed() + theme_linedraw() + theme(axis.text.x = element_text(angle = 90)) + scale_x_discrete(expand = c(0, 0)) + scale_y_discrete(expand = c(0, 0)) if (.no.legend) { p <- p + theme(legend.position = "none") } if (.no.labs) { p <- p + theme(axis.title.x = element_blank(), axis.title.y = element_blank()) } p } #heatmap for plate 2+3 visheatmap23<-function(.data, .title = "Number of shared clonotypes", .labs = c("Sample", "Sample"), .legend = "Shared clonotypes", .na.value = NA, .text = T, .scientific = FALSE, .signif.digits = 4, .size.text = 4, .no.legend = F, .no.labs = F) { if (has.class(.data, "data.frame")) { names <- .data[, 1] .data <- as.matrix(.data[, -1]) row.names(.data) <- names } if (is.null(colnames(.data))) { colnames(.data) <- paste0("C", 1:ncol(.data)) } if (is.null(row.names(.data))) { row.names(.data) <- paste0("C", 1:nrow(.data)) } .data[is.na(.data)] <- .na.value tmp <- as.data.frame(.data) tmp$name <- row.names(.data) m <- melt(tmp, id.var = c("name")) m[, 1] <- factor(m[, 1], levels = rev(rownames(.data))) m[, 2] <- factor(m[, 2], levels = colnames(.data)) .cg <- .colourblind.gradient(min(m$value), max(m$value)) #m$label <- format(m$value, scientific = .scientific, digits = .signif.digits) m$label <- as.vector(matrix(celltype$cell.type[97:288],nrow = 16, ncol=12, byrow=T))#!!!!!! p <- ggplot(m, aes(x = variable, y = name, fill = value)) p <- p + geom_tile(aes(fill = value), colour = "white") if (.text) { p <- p + geom_text(aes(fill = value, label = label), size = .size.text)#!!!!!!!!!! } p <- p + .cg p <- p + ggtitle(.title) + guides(fill = guide_colourbar(title = .legend)) + xlab(.labs[1]) + ylab(.labs[2]) + coord_fixed() + theme_linedraw() + theme(axis.text.x = element_text(angle = 90)) + scale_x_discrete(expand = c(0, 0)) + scale_y_discrete(expand = c(0, 0)) if (.no.legend) { p <- p + theme(legend.position = "none") } if (.no.labs) { p <- p + theme(axis.title.x = element_blank(), axis.title.y = element_blank()) } p } #heatmap for plate 4+5 visheatmap45<-function(.data, .title = "Number of shared clonotypes", .labs = c("Sample", "Sample"), .legend = "Shared clonotypes", .na.value = NA, .text = T, .scientific = FALSE, .signif.digits = 4, .size.text = 4, .no.legend = F, .no.labs = F) { if (has.class(.data, "data.frame")) { names <- .data[, 1] .data <- as.matrix(.data[, -1]) row.names(.data) <- names } if (is.null(colnames(.data))) { colnames(.data) <- paste0("C", 1:ncol(.data)) } if (is.null(row.names(.data))) { row.names(.data) <- paste0("C", 1:nrow(.data)) } .data[is.na(.data)] <- .na.value tmp <- as.data.frame(.data) tmp$name <- row.names(.data) m <- melt(tmp, id.var = c("name")) m[, 1] <- factor(m[, 1], levels = rev(rownames(.data))) m[, 2] <- factor(m[, 2], levels = colnames(.data)) .cg <- .colourblind.gradient(min(m$value), max(m$value)) #m$label <- format(m$value, scientific = .scientific, digits = .signif.digits) m$label <- as.vector(matrix(celltype$cell.type[289:480],nrow = 16, ncol=12, byrow=T))#!!!!!! p <- ggplot(m, aes(x = variable, y = name, fill = value)) p <- p + geom_tile(aes(fill = value), colour = "white") if (.text) { p <- p + geom_text(aes(fill = value, label = label), size = .size.text)#!!!!!!!!!! } p <- p + .cg p <- p + ggtitle(.title) + guides(fill = guide_colourbar(title = .legend)) + xlab(.labs[1]) + ylab(.labs[2]) + coord_fixed() + theme_linedraw() + theme(axis.text.x = element_text(angle = 90)) + scale_x_discrete(expand = c(0, 0)) + scale_y_discrete(expand = c(0, 0)) if (.no.legend) { p <- p + theme(legend.position = "none") } if (.no.labs) { p <- p + theme(axis.title.x = element_blank(), axis.title.y = element_blank()) } p } .colourblind.gradient <- function (.min = NA, .max = NA, .colour = F) { # cs <- c("#FFFFD9", "#41B6C4", "#225EA8") # cs <- c("#FFFFBB", "#41B6C4", "#225EA8") # cs <- c("#FFBB00", "#41B6C4", "#225EA8") <- old version # cs <- c("#FF4B20", "#FFB433", "#C6EDEC", "#85CFFF", "#0348A6") # cs <- c("#FF4B20", "#FFB433", "#C6FDEC", "#7AC5FF", "#0348A6") # scale_fill_gradientn(guide='colourbar', colours=c("#0072B2", "#EEEEEE", "#D55E00") cs <- c(c("#0072B2", "#EEEEEE", "#D55E00")) if (!is.na(.min)) { if (.colour) { scale_colour_gradientn(limits = c(.min, .max), guide='colorbar', colours = cs, na.value = 'grey60') } else { scale_fill_gradientn(limits = c(.min, .max), guide='colorbar', colours = cs, na.value = 'grey60') } } else { if (.colour) { scale_colour_gradientn(colours = cs, na.value = 'grey60') } else { scale_fill_gradientn(colours = cs, na.value = 'grey60') } } } #function to rename files getfile <- function(taskid){ letter = c("A","B","C","D","E","F","G","H") num = c("1","2","3","4","5","6","7","8","9","10","11","12") if (as.numeric(taskid)<97) {if (as.numeric(taskid) %% 12 == 0) { l=letter[as.numeric(taskid)/12] n="12"} else{ l = letter[as.numeric(taskid)/12+1] n = num[as.numeric(taskid)%%12]} return (paste("1",l,n,sep="")) } if (as.numeric(taskid)>96){ smalln=as.numeric(taskid)-96 if (smalln%%12 == 0){ l = letter[smalln/12] n="12" } else{ l = letter[smalln/12+1] n = num[smalln%%12] } return (paste("2",l,n,sep="")) } } #function to get a list of cells with converted names using function "getfile" getfilelist<-function(input_file_list){ out_file_list=vector('character') for (infile in input_file_list){ out_file_list<-c(out_file_list,getfile(infile)) } return (out_file_list) } #function to aggregate V_GENEs agg_v_gene<-function(v_cell_tpm){ v_cell_tpm$V_GENE<-str_split_fixed(v_cell_tpm$V_GENE,pattern ="[*]",n=2)[,1] v_cell_tpm$flag<-paste(v_cell_tpm$V_GENE,v_cell_tpm$CellID,sep='|') agg_v<-aggregate(TPM~flag,data=v_cell_tpm,FUN=sum) agg_v$V_GENE<-str_split_fixed(agg_v$flag,pattern ="[|]",n=2)[,1] agg_v$CellID<-str_split_fixed(agg_v$flag,pattern ="[|]",n=2)[,2] agg_v<-agg_v[,c("V_GENE","CellID","TPM")] return(agg_v) } #function to get expression in plate use={"tcr","v","bcr","vj","aa"} expr_mat<-function(plateID,geneID,use){ if (use=="v") { cells<-vlist[[plateID]][geneID,3] tpms<-vlist[[plateID]][geneID,4] } if (use=="tcr"){ cells<-tcrlist[[plateID]][tcrID,3] tpms<-tcrlist[[plateID]][tcrID,4] } if (use=="vj"){ cells<-vjlist[[plateID]][geneID,3] tpms<-vjlist[[plateID]][geneID,4] } if (use=="bcr") { cells<-bcrlist[[plateID]][geneID,3] tpms<-bcrlist[[plateID]][geneID,4] } if (use=="aa") { cells<-sbcrlist[[plateID]][geneID,3] tpms<-sbcrlist[[plateID]][geneID,4] } mat_plate<-matrix(nrow=8,ncol=12,dimnames=list(c("A","B","C","D","E","F","G","H"),as.character(1:12))) vec_cell<-strsplit(cells,split = ",")[[1]] vec_cellrow<-gsub("([0-9]+)", "",vec_cell) vec_cellcol<-gsub(".*[A-Z]", "", vec_cell) vec_tpm <-as.numeric(strsplit(tpms,split = ",")[[1]]) #cell_tpm_mat<-data.frame(vec_cellrow,vec_cellcol,vec_tpm) for (i in (1:length(vec_cell))){ row_id=which(rownames(mat_plate)==vec_cellrow[i]) col_id=which(colnames(mat_plate)==vec_cellcol[i]) mat_plate[row_id,col_id]<-vec_tpm[i] } mat_plate<-as.numeric(mat_plate) mat<-matrix(log2(as.numeric(mat_plate)+1),8,12) rownames(mat)<-c("A","B","C","D","E","F","G","H") colnames(mat)<-as.character(1:12) return (mat) } expr_matrix<-function(vec_cell,vec_ratio,plate=1){ mat_plate<-matrix(nrow=8,ncol=12,dimnames=list(c("A","B","C","D","E","F","G","H"),as.character(1:12))) vec_cellrow<-gsub("([0-9]+)$", "", vec_cell) vec_cellcol<-gsub("[^\\d]+", "", vec_cell, perl=TRUE) for (i in (1:length(vec_cell))){ row_id=which(rownames(mat_plate)==vec_cellrow[i]) col_id=which(colnames(mat_plate)==vec_cellcol[i]) mat_plate[row_id,col_id]<-vec_ratio[i] } mat_plate[mat_plate==1]<-0 # mat_plate[is.na(mat_plate)|]<-0 return (mat_plate) } expr_2matrix<-function(vec_cell,vec_ratio,plate=23){ ifelse(plate==23, mat_plate<-matrix(nrow=16,ncol=12,dimnames=list(c("1A","1B","1C","1D","1E","1F","1G","1H","2A","2B","2C","2D","2E","2F","2G","2H"),as.character(1:12))), mat_plate<-matrix(nrow=16,ncol=12,dimnames=list(c("3A","3B","3C","3D","3E","3F","3G","3H","4A","4B","4C","4D","4E","4F","4G","4H"),as.character(1:12)))) vec_cellrow<-gsub("([0-9]+)$", "", vec_cell) vec_cellcol<-gsub("[^\\d]+", "", gsub("^([0-9]+)", "",vec_cell), perl=TRUE) for (i in (1:length(vec_cell))){ row_id=which(rownames(mat_plate)==vec_cellrow[i]) col_id=which(colnames(mat_plate)==vec_cellcol[i]) mat_plate[row_id,col_id]<-vec_ratio[i] } mat_plate[mat_plate==1]<-0 return (mat_plate) } #function to get input variable name get_input_name <- function(v1) { deparse(substitute(v1)) } addstar<-function(x){a=paste("*",x,sep = "") return(a)} cat<-function(x){return (paste(x,collapse = ","))} #function to identify sources!crosspos,celltype=T,tpm>2^9) # find_source_1plate<-function(tcr){ # tcr$source<-"" # cell_list<-str_split(tcr$cells,",") # tpm_list<-str_split(tcr$TPMs,",") # for (tcrind in 1:length(cell_list)){ # rows<-substr(cell_list[[tcrind]],1,1) # columns<-substring(cell_list[[tcrind]],2) # freqtable_row<-table(rows)>1 # common_rows<-names(freqtable_row[freqtable_row=="TRUE"]) # freqtable_col<-table(columns)>1 # common_columns<-names(freqtable_col[freqtable_col=="TRUE"]) # if (length(common_columns)==0|length(common_rows)==0){ # maxcellind<-which.max(tpm_list[[tcrind]]) # cell_type<-celltype$cell.type[celltype$well==paste(rows[maxcellind],columns[maxcellind],sep = "")]##!! # if (cell_type=="T"){ # tcr$source[tcrind]<-paste(tcr$source[tcrind],paste(rows[maxcellind],columns[maxcellind],sep = ""),sep = ",") # } # }else{ # # for (cellind in 1:length(cell_list[[tcrind]])){ # # cell_type<-celltype$cell.type[celltype$well==paste(rows[cellind],columns[cellind],sep = "")]##!! # # tpm<-tpm_list[[tcrind]][cellind] # # if (rows[cellind]%in%common_rows && columns[cellind]%in%common_columns && # # cell_type=="T" && # # tpm%in%as.character(sort(as.numeric(tpm_list[[tcrind]]), decreasing=TRUE)[1:(length(cell_list[[tcrind]])*0.3)])) # # { # # tcr$source[tcrind]<-paste(tcr$source[tcrind],paste(common_rows,common_columns,sep = ""),sep = ",") # # } # # } # cross_pos<-sort(apply(expand.grid(common_rows,common_columns), 1, paste, collapse = "", sep = "")) # cross_cells<-cell_list[[tcrind]][cell_list[[tcrind]]%in%cross_pos] # source_cells<-cross_cells[as.numeric(tpm_list[[tcrind]][match(cross_cells,cell_list[[tcrind]])])>2^6]#512 # source_cells<-source_cells[celltype$cell.type[match(source_cells,celltype$well)]=="T"] # tcr$source[tcrind]<-paste(tcr$source[tcrind],paste(source_cells, collapse = ','),sep = ",") # } # } # tcr$source<-gsub("^,","",tcr$source) # return(tcr) # } #function to identify sources find_source_plate<-function(tcr,type="T")#type="P" {tcr$source<-"" for (tcrind in 1:length(tcr$cells)){ source_cells="" cell_vec<-unlist(str_split(tcr$cells[tcrind],",")) tpm_vec<-as.numeric(unlist(str_split(tcr$TPMs[tcrind],","))) rows<-gsub("([0-9]+)$", "",cell_vec) freqtable_row<-table(rows)>1 common_rows<-names(freqtable_row[freqtable_row=="TRUE"]) columns<-gsub("[^\\d]+", "",gsub("^([0-9]+)","",cell_vec),perl=TRUE) freqtable_col<-table(columns)>1 common_columns<-names(freqtable_col[freqtable_col=="TRUE"]) if (length(common_columns)+length(common_rows)>0){#number of common lines if (length(common_columns)==0|length(common_rows)==0){#cells in the same column(row) maxcellind<-which.max(tpm_vec) tpm_source<-as.numeric(tpm_vec[maxcellind]) well<-paste(rows[maxcellind],columns[maxcellind],sep = "") cell_type<-celltype$cell.type[celltype$well==well]##!! if (type=="T"){ if (cell_type=="T" && tpm_source>2^5 && all(tpm_source>5*tpm_vec[!cell_vec %in% c(well,"A1","1A1","2A1","3A1","4A1")])) {tcr$source[tcrind]<-paste(tcr$source[tcrind],well,sep = ",")}} else if(type=="P"){ if (cell_type=="P" && tpm_source>2^5 && all(tpm_source>5*tpm_vec[!cell_vec %in% c(well,"A1","1A1","2A1","3A1","4A1")])) {tcr$source[tcrind]<-paste(tcr$source[tcrind],well,sep = ",")}} }else{#cells in multiple columns(rows) cross_pos<-sort(apply(expand.grid(common_rows,common_columns), 1, paste, collapse = "", sep = "")) cross_cells<-cell_vec[cell_vec%in%cross_pos] source_cells<-cross_cells[as.numeric(tpm_vec[match(cross_cells,cell_vec)])>2^5]#512 if (length(source_cells)>0){ scells<-source_cells source_tpms<-tpm_vec[match(source_cells,cell_vec)] if(exists("cells_in_line_sources")){rm(cells_in_line_sources)} for (i in 1:length(source_cells)){ ifelse(length(source_cells)==1,scell<-source_cells,scell<-source_cells[i]) ifelse(length(source_cells)==1,source_tpm<-as.numeric(source_tpms),source_tpm<-as.numeric(source_tpms[i])) source_row<-gsub("([0-9]+)$", "",scell) source_column<-gsub("[^\\d]+", "",gsub("^([0-9]+)","",scell),perl=TRUE) is_cells_in_line<-(rows==source_row|columns==source_column) cells_in_line<-cell_vec[is_cells_in_line] ifelse(exists("cells_in_line_sources"),cells_in_line_sources<-c(cells_in_line_sources,cells_in_line),cells_in_line_sources<-cells_in_line) tpm_in_line<-as.numeric(tpm_vec[match(cells_in_line,cell_vec)]) if (!all(source_tpm>5*tpm_in_line[!cells_in_line %in% c(cells_in_line_sources,"A1","1A1","2A1","3A1","4A1")]) | source_tpm<2^5){ scells<-scells[scells != scell]#remove scell from source_cells cells_in_line_sources[!cells_in_line_sources%in%cells_in_line] } } ifelse(type=="T",source_cells<-scells[celltype$cell.type[match(scells,celltype$well)]=="T"], source_cells<-scells[celltype$cell.type[match(scells,celltype$well)]=="P"]) } } } tcr$source[tcrind]<-paste(source_cells,collapse = ",") } return(tcr) } #add a list of source_cells for each V_genes in v1 append_subset_v<-function(tcr_source,v){ v_gene_vec<-str_split_fixed(tcr_source$TCR,"_",2)[,1]#[nchar(tcr1_source$source)!=0] tcr_source$V_GENE<-v_gene_vec sv<-v[str_split_fixed(v$V_GENE,"_",2)[,1] %in% v_gene_vec,] sv$V_GENE<-str_split_fixed(sv$V_GENE,"_",2)[,1] sv<-merge(sv,aggregate(source~V_GENE,data = tcr_source,FUN = c),by="V_GENE") sv$source<-lapply(sv$source,function(x){paste(x,collapse = ",")}) return(sv) } get_potential_source1<-function(tcr_source,sv) {potential_source<-rep(NA,dim(sv)[1]) v_vec<-unique(str_split_fixed(tcr_source$TCR,"_",2)[,1]) v_vec[1]<-"TRAV38-2_DV8"########only plate1 for (i in 1:length(v_vec)){ acell<-sv$cells[which(sv$V_GENE==v_vec[i])] acell<-unlist(str_split(acell,",")) is_t<-celltype$cell.type[match(acell,celltype$well)]=="T" atpm<-sv$TPMs[which(sv$V_GENE==v_vec[i])] atpm<-as.numeric(unlist(str_split(atpm,","))) is_hightpm<-atpm>2^5 rows<-gsub("([0-9]+)$", "", acell) columns<-gsub("[^\\d]+", "", acell, perl=TRUE) is_spread<-unlist(lapply(rows,function(x) length(x[rows==x])>1))&unlist(lapply(columns,function(x) length(x[columns==x])>1)) potential_source[i]<-paste(acell[is_t&is_hightpm&is_spread],collapse = ",") } return(potential_source) } get_potential_source23<-function(tcr_source,sv) {potential_source<-rep(NA,dim(sv)[1]) v_vec<-unique(str_split_fixed(tcr_source$TCR,"_",2)[,1]) for (i in 1:length(v_vec)){ acell<-sv$cells[which(sv$V_GENE==v_vec[i])] acell<-unlist(str_split(acell,",")) # acell[!grepl("[*]",acell)]<-paste("1",acell[!grepl("[*]",acell)],sep = "") # acell<-gsub("[*]","2",acell) is_t<-celltype$cell.type[match(acell,celltype$well)]=="T" atpm<-sv$TPMs[which(sv$V_GENE==v_vec[i])] atpm<-as.numeric(unlist(str_split(atpm,","))) is_hightpm<-atpm>2^5 rows<-gsub("([0-9]+)$", "", acell) columns<-gsub("[^\\d]+", "", acell, perl=TRUE) is_spread<-unlist(lapply(rows,function(x) length(x[rows==x])>1))&unlist(lapply(columns,function(x) length(x[columns==x])>1)) potential_source[i]<-paste(acell[is_t&is_hightpm&is_spread],collapse = ",") } return(potential_source) } get_potential_source45<-function(tcr_source,sv) {potential_source<-rep(NA,dim(sv)[1]) v_vec<-unique(str_split_fixed(tcr_source$TCR,"_",2)[,1]) for (i in 1:length(v_vec)){ acell<-sv$cells[which(sv$V_GENE==v_vec[i])] acell<-unlist(str_split(acell,",")) # acell[!grepl("[*]",acell)]<-paste("3",acell[!grepl("[*]",acell)],sep = "") # acell<-gsub("[*]","4",acell) is_t<-celltype$cell.type[match(acell,celltype$well)]=="T" atpm<-sv$TPMs[which(sv$V_GENE==v_vec[i])] atpm<-as.numeric(unlist(str_split(atpm,","))) is_hightpm<-atpm>2^5 rows<-gsub("([0-9]+)$", "", acell) columns<-gsub("[^\\d]+", "", acell, perl=TRUE) is_spread<-unlist(lapply(rows,function(x) length(x[rows==x])>1))&unlist(lapply(columns,function(x) length(x[columns==x])>1)) potential_source[i]<-paste(acell[is_t&is_hightpm&is_spread],collapse = ",") } return(potential_source) } #to check if a cell is source for v gene check_source<-function(gene,cell_list,use="vsourcelist")#use=tcrsourcelist,vsourcelist,bcrsourcelist,sbcrsourcelist,ntbcrsourcelist {cell_list<-unlist(strsplit(cell_list,split=",")) n=length(cell_list) ifs<-rep(NA,n) for (i in 1:n){ if (!is.na(cell_list[1])){ scells<-NA if(use=="vsourcelist"){ifs[i]<-gene%in%sourcelist[cell_list[i],]} else if(use=="tcrsourcelist"){ ifelse(grepl("^TRA",gene),ab<-2,ab<-3) ifs[i]<-gene%in%tcrsourcelist[cell_list[i],]|is.na(tcrsourcelist[cell_list[i],ab]) } else if(use=="bcrsourcelist"){ifs[i]<-gene%in%bcrsourcelist[cell_list[i],]} else if(use=="sbcrsourcelist"){ifs[i]<-gene%in%sbcrsourcelist[cell_list[i],]} else if(use=="ntbcrsourcelist"){ifs[i]<-gene%in%ntbcrsourcelist[cell_list[i],]} scells<-paste(cell_list[ifs],collapse = ",") } } return (scells) } #filter non_source filter_non_source<-function(gene,cell_list,use)#use=tcrsourcelist,vsourcelist,bcrsourcelist,sbcrsourcelist,ntbcrsourcelist {#cell_list<-unlist(strsplit(cell_list,split=",")) n=length(cell_list) ifs<-rep(NA,n) for (i in 1:n){ if (!is.na(cell_list[1])){ scells<-NA if(use=="v"){ifs[i]<-!gene%in%sourcelist[cell_list[i],]} else if(use=="tcr"){ ifelse(grepl("^TRA",gene),ab<-2,ab<-3) ifs[i]<-!gene%in%tcrsourcelist[cell_list[i],] } else if(use=="bcr"){!ifs[i]<-gene%in%bcrsourcelist[cell_list[i],]} else if(use=="aa"){!ifs[i]<-gene%in%sbcrsourcelist[cell_list[i],]} else if(use=="nt"){!ifs[i]<-gene%in%ntbcrsourcelist[cell_list[i],]} scells<-paste(cell_list[ifs],collapse = ",") } } return (scells) } #get expression array from v gene$filtered_source get_array<-function(sv,n_plate="T"){ source_cells<-unlist(str_split(paste(sv$filted_source[sv$filted_source!=""],collapse = ","),",")) ifelse(n_plate=="T",vexpr<-array(0,dim = c(16,12,length(source_cells))),vexpr<-array(0,dim = c(8,12,length(source_cells)))) k=1 for (i in 1:length(sv$filted_source)){#loop through all v genes in sv if(!is.na(sv$filted_source[i])&&sv$filted_source[i]!=""){ cell_vec<-unlist(str_split(sv$cells[[i]],",")) tpm_vec<-unlist(str_split(sv$TPMs[[i]],",")) source_cell_vec<-unlist(str_split(sv$filted_source[[i]],",")) source_cell_vec<-gsub("^[1,3]","",source_cell_vec) source_cell_vec<-gsub("^[2,4]","*",source_cell_vec) source_tpm_vec<-tpm_vec[cell_vec%in%source_cell_vec] rows<-gsub("([0-9]+)$", "",cell_vec) columns<-gsub("[^\\d]+", "",cell_vec,perl=TRUE) if (length(source_cell_vec)==1){#only one source cell id<-which(cell_vec==source_cell_vec) tpm_source<-tpm_vec[id] l<-rows%in%(gsub("([0-9]+)$", "",source_cell_vec))|columns%in%gsub("[^\\d]+", "",source_cell_vec,perl=TRUE) cells_line<-cell_vec[l]#cells in the same row|column with the source allrowcells<-paste(gsub("([0-9]+)$", "",source_cell_vec),1:12,sep="") ifelse(n_plate=="F", allcolumncells<-paste(c("A","B","C","D","E","F","G","H"),gsub("[^\\d]+", "",source_cell_vec,perl=TRUE),sep=""), allcolumncells<-paste(c("A","B","C","D","E","F","G","H","*A","*B","*C","*D","*E","*F","*G","*H"),gsub("[^\\d]+", "",source_cell_vec,perl=TRUE),sep="")) tpm_vec_line<-c(tpm_vec[l],rep(0,length(setdiff(union(allcolumncells,allrowcells),cells_line)))) cells_line<-c(cells_line,setdiff(union(allcolumncells,allrowcells),cells_line)) ratios<-as.numeric(tpm_vec_line)/as.numeric(tpm_source) ifelse(n_plate=="F",vexpr[,,k]<-expr_matrix(cells_line,ratios),vexpr[,,k]<-expr_2matrix(cells_line,ratios)) k=k+1 } else{#multiple sources for (j in 1:length(source_cell_vec)){ tpm_vec<-unlist(str_split(sv$TPMs[[i]],",")) id<-which(cell_vec==source_cell_vec[j]) tpm_source<-tpm_vec[id] is_cells_in_row<-rows==(gsub("([0-9]+)$", "",source_cell_vec[j])) is_cells_in_col<-columns==gsub("[^\\d]+", "",source_cell_vec[j],perl=TRUE) is_cells_in_line<-is_cells_in_row|is_cells_in_col cell_in_line<-cell_vec[is_cells_in_line]#cells in the same row|column with the source:source_cell_vec[j] tpm_in_line<-tpm_vec[is_cells_in_line] for (t in cell_in_line) { if (t!=source_cell_vec[j]){ t_row<-gsub("([0-9]+)$", "",t) t_col<-regmatches(t, regexpr("\\d$", t)) is_sources_in_row<-gsub("([0-9]+)$", "",source_cell_vec)==t_row is_sources_in_col<-gsub("[^\\d]+", "",source_cell_vec, perl=TRUE)==t_col if ((sum(is_sources_in_row)+sum(is_sources_in_col))>1) { perc_tpm<-as.numeric(tpm_source)/sum(as.numeric(source_tpm_vec[is_sources_in_row|is_sources_in_col])) tpm_in_line[match(t,cell_in_line)]<-as.numeric(tpm_in_line[match(t,cell_in_line)])*perc_tpm } } } allrowcells<-paste(gsub("([0-9]+)$", "",source_cell_vec[j]),1:12,sep="") ifelse(n_plate=="F", allcolumncells<-paste(c("A","B","C","D","E","F","G","H"),gsub("[^\\d]+", "",source_cell_vec[j],perl=TRUE),sep=""), allcolumncells<-paste(c("A","B","C","D","E","F","G","H","*A","*B","*C","*D","*E","*F","*G","*H"),gsub("[^\\d]+", "",source_cell_vec[j],perl=TRUE),sep="")) app_tpm_in_line<-c(tpm_in_line,rep(0,length(setdiff(union(allcolumncells,allrowcells),cell_in_line)))) app_cell_in_line<-c(cell_in_line,setdiff(union(allrowcells,allcolumncells),cell_in_line)) ratios<-as.numeric(app_tpm_in_line)/as.numeric(tpm_source) ratios[which(app_cell_in_line==source_cell_vec[j])]<-0 ifelse(n_plate=="F",vexpr[,,k]<-expr_matrix(app_cell_in_line,ratios),vexpr[,,k]<-expr_2matrix(app_cell_in_line,ratios)) k=k+1 } } } } return(vexpr) } #get expression array from tcr_source$source get_array_tcr<-function(tcr_source,n_plate="T") {source_cells<-unlist(str_split(paste(tcr_source$source[tcr_source$source!=""],collapse = ","),",")) ifelse(n_plate=="T",tcr_array<-array(0,dim = c(16,12,length(source_cells))),tcr_array<-array(0,dim = c(8,12,length(source_cells)))) k=1 for (i in 1:length(tcr_source$source)){ cell_vec<-unlist(str_split(tcr_source$cells[[i]],",")) tpm_vec<-unlist(str_split(tcr_source$TPMs[[i]],",")) source_cell_vec<-unlist(str_split(tcr_source$source[[i]],",")) source_cell_vec<-gsub("^[1,3]","",source_cell_vec) source_cell_vec<-gsub("^[2,4]","*",source_cell_vec) source_tpm_vec<-tpm_vec[cell_vec%in%source_cell_vec] rows<-gsub("([0-9]+)$", "",cell_vec) columns<-gsub("[^\\d]+", "",cell_vec,perl=TRUE) if (source_cell_vec!=""&&length(source_cell_vec)==1){#only one source cell id<-which(cell_vec==source_cell_vec) tpm_source<-tpm_vec[id] l<-rows%in%(gsub("([0-9]+)$", "",source_cell_vec))|columns%in%gsub("[^\\d]+", "",source_cell_vec,perl=TRUE) cells_line<-cell_vec[l]#cells in the same row|column with the source allrowcells<-paste(gsub("([0-9]+)$", "",source_cell_vec),1:12,sep="") ifelse(n_plate=="F", allcolumncells<-paste(c("A","B","C","D","E","F","G","H"),gsub("[^\\d]+", "",source_cell_vec,perl=TRUE),sep=""), allcolumncells<-paste(c("A","B","C","D","E","F","G","H","*A","*B","*C","*D","*E","*F","*G","*H"),gsub("[^\\d]+", "",source_cell_vec,perl=TRUE),sep="")) tpm_vec_line<-c(tpm_vec[l],rep(0,length(setdiff(union(allcolumncells,allrowcells),cells_line)))) cells_line<-c(cells_line,setdiff(union(allcolumncells,allrowcells),cells_line)) ratios<-as.numeric(tpm_vec_line)/as.numeric(tpm_source) ifelse(n_plate=="F",tcr_array[,,k]<-expr_matrix(cells_line,ratios),tcr_array[,,k]<-expr_2matrix(cells_line,ratios)) k=k+1 }else if(source_cell_vec!=""&&length(source_cell_vec)>1){#multiple source cell for (j in 1:length(source_cell_vec)){ tpm_vec<-unlist(str_split(tcr_source$TPMs[[i]],",")) id<-which(cell_vec==source_cell_vec[j]) tpm_source<-tpm_vec[id] is_cells_in_row<-rows==(gsub("([0-9]+)$", "",source_cell_vec[j])) is_cells_in_col<-columns==gsub("[^\\d]+", "",source_cell_vec[j],perl=TRUE) is_cells_in_line<-is_cells_in_row|is_cells_in_col cell_in_line<-cell_vec[is_cells_in_line]#cells in the same row|column with the source:source_cell_vec[j] tpm_in_line<-tpm_vec[is_cells_in_line] for (t in cell_in_line) { if (t!=source_cell_vec[j]){ t_row<-gsub("([0-9]+)$", "",t) t_col<-regmatches(t, regexpr("\\d$", t)) is_sources_in_row<-gsub("([0-9]+)$", "",source_cell_vec)==t_row is_sources_in_col<-gsub("[^\\d]+", "",source_cell_vec)==t_col if ((sum(is_sources_in_row)+sum(is_sources_in_col))>1) { perc_tpm<-as.numeric(tpm_source)/sum(as.numeric(source_tpm_vec[is_sources_in_row|is_sources_in_col])) tpm_in_line[match(t,cell_in_line)]<-as.numeric(tpm_in_line[match(t,cell_in_line)])*perc_tpm } } } allrowcells<-paste(gsub("([0-9]+)$", "",source_cell_vec[j]),1:12,sep="") ifelse(n_plate=="F", allcolumncells<-paste(c("A","B","C","D","E","F","G","H"),gsub("[^\\d]+", "",source_cell_vec[j],perl=TRUE),sep=""), allcolumncells<-paste(c("A","B","C","D","E","F","G","H","*A","*B","*C","*D","*E","*F","*G","*H"),gsub("[^\\d]+", "",source_cell_vec[j],perl=TRUE),sep="")) app_tpm_in_line<-c(tpm_in_line,rep(0,length(setdiff(union(allcolumncells,allrowcells),cell_in_line)))) app_cell_in_line<-c(cell_in_line,setdiff(union(allrowcells,allcolumncells),cell_in_line)) ratios<-as.numeric(app_tpm_in_line)/as.numeric(tpm_source) ratios[which(app_cell_in_line==source_cell_vec[j])]<-0 ifelse(n_plate=="F",tcr_array[,,k]<-expr_matrix(app_cell_in_line,ratios),tcr_array[,,k]<-expr_2matrix(app_cell_in_line,ratios)) k=k+1 } } } return(tcr_array) } collect_rows<-function(array,array_use=""){ ifelse(array_use=="",n<-dim(array)[3],n<-length(array_use)) target_rows<-matrix(NA,nrow = n,ncol = 12) row_freq<-rep(0,dim(array)[1]) row_ids<-NA for (i in 1:n){ row_idx<-which(rowSums(array[,,i])>=0) row_freq[row_idx]=row_freq[row_idx]+1 target_rows[i,]<-array[,,i][row_idx,] ifelse(is.na(row_ids),row_ids<-row_idx,row_ids<-c(row_ids,row_idx)) } return(list(target_rows,row_freq,row_ids)) } collect_cols<-function(array,array_use=""){ ifelse(array_use=="",n<-dim(array)[3],n<-length(array_use)) k<-dim(array)[1] target_columns<-matrix(NA,nrow = k,ncol = n) col_freq<-rep(0,12) col_ids<-NA for (i in 1:n){ col_idx<-which(colSums(array[,,i])>=0) col_freq[col_idx]=col_freq[col_idx]+1 target_columns[,i]<-array[,,i][,col_idx] ifelse(is.na(col_ids),col_ids<-col_idx,col_ids<-c(col_ids,col_idx)) } return(list(target_columns,col_freq,col_ids)) } #correct the sequences such that allow one nt mismatch if BCRs with the same V_J collapse_xnt_mismatch<-function(bcr,num_nt){ bcr$V<-str_split_fixed(bcr$ReceptorID, "_", 3)[,1] bcr$N<-str_split_fixed(bcr$ReceptorID, "_", 3)[,2] bcr$J<-str_split_fixed(bcr$ReceptorID, "_", 3)[,3] bcr$V_J<-paste(bcr$V,bcr$J,sep='_') #bcr$topTPM<-unlist(lapply(str_split(bcr$TPM,","),function(x) max(as.numeric(x)))) for (i in unique(bcr$V_J)){ ids<-which(bcr$V_J==i) if (length(ids)>1){ # pairp=combn(bcr$ReceptorID[ids],2) #ind_maxtpm<-which.max(bcr[ids,]$topTPM) ind_maxtpm<-which.max(bcr[ids,]$TPM) # ref<-bcr[ids,]$N[ind_maxtpm] #ref<-bcr[ind_maxtpm,]$full_sequence?????? ref<-bcr[ids,]$CDR3nt[ind_maxtpm] refaa<-bcr[ids,]$CDR3aa[ind_maxtpm] ids <- ids[-ind_maxtpm] for (j in ids) { # if (adist(bcr$N[j],ref)<=num_nt) if (adist(bcr$CDR3nt[j],ref)<=num_nt) { # bcr$N[j]<-ref #change the nt seq bcr$CDR3nt[j]<-ref bcr$CDR3aa[j]<-refaa } } } } bcr<-bcr[,-which(names(bcr)%in%c("V","N","J","V_J"))] return(bcr)} # # bcr$ReceptorID<-paste(bcr$V,bcr$N,bcr$J,sep = "_") # bcr$Freq<-as.numeric(bcr$Freq) # # v1 <- aggregate(Freq~ReceptorID,data=bcr,FUN=sum) # # v2 <- aggregate(cells~ReceptorID,data=bcr,FUN=c) # # v3 <- aggregate(TPMs~ReceptorID,data=bcr,FUN=c) # # bcr <- merge(v1, v2, by="ReceptorID") # # bcr <- merge(bcr, v3, by="ReceptorID") # v1 <- aggregate(Freq~full_sequence,data=bcr,FUN=sum) # v2 <- aggregate(cells~full_sequence,data=bcr,FUN=c) # v3 <- aggregate(TPMs~full_sequence,data=bcr,FUN=c) # bcr <- merge(v1, v2, by="full_sequence") # bcr <- merge(bcr, v3, by="full_sequence") # for (i in 1:dim(bcr)[1]){ # if (length(unlist(bcr$cells[i]))>1){ # cells<-unlist(str_split(paste(unlist(bcr$cells[i]),collapse =","),",")) # if(length(unique(cells))<length(cells)){ # tpms<-as.numeric(unlist(str_split(paste(unlist(bcr$TPMs[i]),collapse =","),","))) # df<-data.frame(cells,tpms) # adf<-aggregate(tpms~cells,data = df, FUN=sum) # bcr$cells[i]<-paste((adf$cells),collapse =",") # bcr$TPMs[i]<-paste((adf$tpms),collapse =",") # }else{ # bcr$cells[i]<-paste(unlist(bcr$cells[i]),collapse =",") # bcr$TPMs[i]<-paste(unlist(bcr$TPMs[i]),collapse =",") # } # } # else # { bcr$cells[i]<-unlist(bcr$cells[i]) # bcr$TPMs[i]<-unlist(bcr$TPMs[i]) # } # } # bcr$cells<-unlist(bcr$cells) # bcr$TPMs<-unlist(bcr$TPMs) # return(bcr) # } merge_seq<-function(bracer,bracer_seq){ bracer<-bracer[order(bracer[,1], bracer[,2]), ] bracer_seq<-bracer_seq[order(bracer_seq[,1], bracer_seq[,2]), ] bracer<-cbind(bracer,bracer_seq$Sequence) colnames(bracer)[4]<-"sequence" return(bracer) }
65c8fa5f386413800dcae68bdc4df37ff4eedcbf
f3fbe9e4f49764e088531485f14c8f0962569420
/R-code/do_crisscross_hanning_50_wosa.R
9f2ba5096cc91b91f053a45436b9013d65652d84
[]
no_license
dmn001/sauts
d3a678091a081679561db2ada077a7dc9630847d
2797e0ab943fb02ebea82df32bd1cc2748c54dcc
refs/heads/master
2023-04-30T12:13:14.502267
2021-05-22T16:11:15
2021-05-22T16:11:15
369,851,701
0
0
null
null
null
null
UTF-8
R
false
false
386
r
do_crisscross_hanning_50_wosa.R
### generate crisscross for WOSA with Hanning data taper and 50% overlap do_crisscross_hanning_50_wosa <- function(the_taper,N_B,n_or_block_starts,delta_t=1) { edof <- 36*N_B^2/(19*N_B-1) return(list(up = 10*log10(edof/qchisq(0.025,edof)), down = -10*log10(edof/qchisq(0.975,edof)), width = B_H(the_taper,delta_t), edof=edof)) }
00f5e526179ed11de4ee6b7e06d9cc8ddb0432bd
1f19663b2f7daf18abda91a926fd8e08cb83dc8d
/R/createConnection.R
e83cb0c77622eced30e84993faf865d405e2230f
[]
no_license
horlar1/R.Deploymodel
335dbaffb3a06382ceb3223cfc2ac84ca94955cd
01c4bdb670580f36e4eeb1625c9ef926f7be149f
refs/heads/master
2020-12-05T13:19:54.807811
2020-01-07T12:14:32
2020-01-07T12:14:32
232,123,601
2
0
null
2020-01-07T12:14:33
2020-01-06T14:56:57
R
UTF-8
R
false
false
1,046
r
createConnection.R
#' Create a connection to the server #' @param server server name for authentication (charcter string) #' @param database database name #' @param username username for authentication #' @param password for authenitication (if required) #' @export #' @importFrom RODBC odbcDriverConnect #' @seealso \code{\link[RODBC]{odbcConnect}} #' @examples \dontrun{ #' # don't run this sript #' con = createConnection(server = "",database = "",username="",password="") #' } createConnection <- function(server,database,username,password){ if(missing(server)) stop("missing argument 'server name'") if(missing(database)) stop("missing argument 'database name'") if(missing(username)) stop("missing argument 'username'") if(missing(password)) stop("missing argument 'password'") dbconnection<- odbcDriverConnect(paste0("Driver=ODBC Driver 13 for SQL Server; Server=",server,"; Database=",database,"; Uid=",username,"; Pwd=",password,"")) return(dbconnection) }
c732858b6414c90f00b0a0d35a9f3659028f4609
1c4caaa37a9aaeac8c0fa73a417503d6ed05ef53
/inst/scripts/fig2a.R
7a1cd60a5d008c4db093699d8218f3c9fe0e9a03
[]
no_license
metamaden/recountmethylation_manuscript_supplement
08996bf66fa0ad920b35107105d27b94663fb275
4a254783b8933411a80032e33549ae94c1544ad6
refs/heads/master
2020-12-27T09:22:39.405834
2020-10-09T06:27:08
2020-10-09T06:27:08
237,849,928
1
0
null
null
null
null
UTF-8
R
false
false
1,656
r
fig2a.R
#!/usr/bin/env R # Make figure 2A, BeadArray controls stacked barplot # of sample performance outcomes. library(ggplot2) library(ggforce) library(data.table) library(recountmethylationManuscriptSupplement) pkgname <- "recountmethylationManuscriptSupplement" tables.dir <- system.file("extdata", "tables", package = pkgname) #---------- # load data #---------- fn <- "table-s2_qcmd-allgsm.csv" qcmd <- fread(file.path(tables.dir, fn), sep = ",", data.table = FALSE) which.bacol <- which(grepl("^ba.*", colnames(qcmd))) bat <- qcmd[,c(1, which.bacol)] colnames(bat) <- gsub("^ba\\.", "", colnames(bat)) #--------------- # make plot data #--------------- tr <- bathresh(bat) dfplot <- matrix(nrow = 0, ncol = 3) for(c in colnames(tr)[2:18]){ num.pass <- length(which(tr[,c] == "PASS")) num.fail <- length(which(tr[,c] == "FAIL")) dfplot = rbind(dfplot, matrix(c(num.pass, "ABOVE", c), nrow = 1)) dfplot = rbind(dfplot, matrix(c(num.fail, "BELOW", c), nrow = 1)) } dfplot = as.data.frame(dfplot, stringsAsFactors = F) dfplot[,1] = as.numeric(dfplot[,1]) colnames(dfplot) = c("Num. Samples", "Thresh. Count", "Metric") dfi = dfplot[dfplot[,2] == "BELOW",] dfplot$Metric = factor(dfplot$Metric, levels = dfi[,3][rev(order(dfi[,1]))]) #---------- # make plot #---------- fig2a <- ggplot(dfplot, aes(x = `Metric`, y = `Num. Samples`, fill = `Thresh. Count`)) + geom_bar(stat = 'identity') + scale_fill_manual(values = c("limegreen", "red")) + theme_bw() + theme(axis.text.x = element_text(angle = 90, hjust = 1)) + facet_zoom(ylim = c(0, 2500), zoom.data = ifelse(a <= 10, NA, FALSE)) + xlab("BeadArray Metric") + ylab("Number of\nSamples")
9fc80399c7534fd73f76b00ab61f1c964470c154
3ea675eb05c11dd66e095eb4713308616e0036ed
/cachematrix.R
1ba52409b7b2df3e44e648314daca015de6a1c06
[]
no_license
Khizermark/ProgrammingAssignment2
a8a7c4d63f6c205319f22e05d0e0e3df47125097
3b033a9f148593a80d5db81e3a63e99ba2e59e3e
refs/heads/master
2021-01-15T22:28:23.136012
2015-02-22T20:14:42
2015-02-22T20:14:42
31,175,968
0
0
null
2015-02-22T19:20:12
2015-02-22T19:20:10
null
UTF-8
R
false
false
1,833
r
cachematrix.R
####################################################################### ############ Describing Each Steps as it goes!!######################## ####################################################################### makeCacheMatrix <- function(x = matrix()) { inverse <- matrix() ## Creating variable for storing inverse... ## By default inverse will have NAs setmatrix <- function(y){ ## Storing the Matrix in X x <<- y m <<- matrix() ## Variable for inverse } getmatrix <- function() x ## Function to get the value of Matrix setinverse <- function(inverse) m <<- inverse ## Function to store the value of inverse getinverse <- function() inverse ## Function to get value of inverse list(setmatrix = setmatrix, getmatrix = getmatrix, setinverse = setinverse, ## List which returns all the above getinverse = getinverse) } cacheSolve <- function(x, ...) { ## Returns a matrix that is the inverse of 'x' m <- x$getinverse() ## Getting the value of inverse.... if(!is.na(m)) { ## Checking whether m is empty matrix message("getting inverse of required matrix") return(m) ## if m is not empty, its value is returned, X } ## Otherwise, it is computed in following lines data <- x$getmatrix() ## Getting Matrix Data m <- solve(data, ...) ## Solving for inverse of required matrix x$setinverse(m) ## Storing that inverse value in m m ## Returning the inverse matrix m }
7c6c2abd44dea43bd28158f83ec8414079101386
0b5d4f07fb7c6c1b574503877389f1ca4949a23d
/tests/testthat/test_aresimcn.R
29c143b519bd38850463cab74a58248f0ae7afde
[]
no_license
joemckean/mathstat
0673c5f97064b8f4ac77d21ce3f10062e98b91f6
5e008df47b5549730c5e219b62c2cec55ecf3c3f
refs/heads/master
2020-04-08T14:34:52.117179
2019-04-22T17:58:40
2019-04-22T17:58:40
159,443,068
2
0
null
null
null
null
UTF-8
R
false
false
1,978
r
test_aresimcn.R
# Test for aresimcn function Returns: An error message if any # tests fail context("aresimcn") test_that("edge cases", { expect_error(aresimcn(Inf), "argument 1 cannot include an Inf or -Inf") expect_error(aresimcn(n = -1), "argument 1 must be positive") expect_error(aresimcn(n = 50, nsims = Inf), "argument 2 cannot include an Inf or -Inf") expect_error(aresimcn(n = 50, nsims = -1), "argument 2 must be positive") expect_error(aresimcn(n = 50, eps = -1), "input argument 'eps' must be between zero and one") expect_error(aresimcn(n = 50, eps = 1), "input argument 'eps' must be between zero and one") expect_error(aresimcn(n = 50, nsims = 100, eps = Inf), "argument 3 cannot include an Inf or -Inf") expect_error(aresimcn(n = 50, nsims = 100, vc = -1), "argument 4 must be positive") expect_error(aresimcn(n = 50, vc = Inf), "argument 4 cannot include an Inf or -Inf") }) test_that("input", { # Checking invalid input for n expect_error(aresimcn(n = 0), "argument 1 must be numeric and non-zero") expect_error(aresimcn(n = NA), "argument 1 must be a number") expect_error(aresimcn(n = NA), "argument 1 must be numeric and non-zero") expect_error(aresimcn(n = NA), "argument 1 must be positive") # Checking invalid input for nsims expect_error(aresimcn(nsims = NA), "argument 2 must be a number") expect_error(aresimcn(nsims = NA), "argument 2 must be numeric and non-zero") expect_error(aresimcn(nsims = NA), "argument 2 must be positive") # Checking invalid input for eps expect_error(aresimcn(n = 50, eps = NA), "argument 3 must be a number") # Checking invalid input for vc expect_error(aresimcn(n = 50, vc = NA), "argument 4 must be positive") expect_error(aresimcn(n = 50, vc = NA), "argument 4 must be a number") }) test_that("output", { expect_equal(is.numeric(aresimcn(30, 100, 0.25, 3)), TRUE) expect_equal(is.vector(aresimcn(30, 100, 0.25, 3)), TRUE) expect_equal(length(aresimcn(30, 100, 0.25, 3)), 1) })
1cc26a66aef7c2154365e53da1b841f98640b355
ffdea92d4315e4363dd4ae673a1a6adf82a761b5
/data/genthat_extracted_code/spdep/examples/autocov_dist.Rd.R
0de782b567262c5042512492b31b51082d8d3f52
[]
no_license
surayaaramli/typeRrh
d257ac8905c49123f4ccd4e377ee3dfc84d1636c
66e6996f31961bc8b9aafe1a6a6098327b66bf71
refs/heads/master
2023-05-05T04:05:31.617869
2019-04-25T22:10:06
2019-04-25T22:10:06
null
0
0
null
null
null
null
UTF-8
R
false
false
1,477
r
autocov_dist.Rd.R
library(spdep) ### Name: autocov_dist ### Title: Distance-weighted autocovariate ### Aliases: autocov_dist ### Keywords: spatial ### ** Examples if (require(rgdal, quietly=TRUE)) { example(columbus, package="spData") xy <- cbind(columbus$X, columbus$Y) ac1a <- autocov_dist(columbus$CRIME, xy, nbs=10, style="B", type="one") acinva <- autocov_dist(columbus$CRIME, xy, nbs=10, style="B", type="inverse") acinv2a <- autocov_dist(columbus$CRIME, xy, nbs=10, style="B", type="inverse.squared") plot(ac1a ~ columbus$CRIME, pch=16, asp=1) points(acinva ~ columbus$CRIME, pch=16, col="red") points(acinv2a ~ columbus$CRIME, pch=16, col="blue") abline(0,1) nb <- dnearneigh(xy, 0, 10) lw <- nb2listw(nb, style="B") ac1b <- lag(lw, columbus$CRIME) all.equal(ac1b, ac1a) nbd <- nbdists(nb, xy) gl <- lapply(nbd, function(x) 1/x) lw <- nb2listw(nb, glist=gl) acinvb <- lag(lw, columbus$CRIME) all.equal(acinvb, acinva) gl2 <- lapply(nbd, function(x) 1/(x^2)) lw <- nb2listw(nb, glist=gl2) acinv2b <- lag(lw, columbus$CRIME) all.equal(acinv2b, acinv2a) glm(CRIME ~ HOVAL + ac1b, data=columbus, family="gaussian") spautolm(columbus$CRIME ~ HOVAL, data=columbus, listw=nb2listw(nb, style="W")) xy <- SpatialPoints(xy) acinva <- autocov_dist(columbus$CRIME, xy, nbs=10, style="W", type="inverse") nb <- dnearneigh(xy, 0, 10) nbd <- nbdists(nb, xy) gl <- lapply(nbd, function(x) 1/x) lw <- nb2listw(nb, glist=gl) acinvb <- lag(lw, columbus$CRIME) all.equal(acinvb, acinva) }
a439023752a853ca1363c26525a8fe02feec7727
13ce5625673daf9a82cda276f5a1bee58ba1dcd1
/man/reduce_space.Rd
2cc33a880cdf5de2cbb7abf2a025d83e55b57571
[ "Apache-2.0" ]
permissive
edzer/gdalcubes_R
afe19d9e97f695e7838fb6ab4719fc50f2a04d34
ed4b705a095eb23fb47017e339b8fb0e0a7a9ec9
refs/heads/master
2020-04-16T04:26:03.878484
2019-01-10T15:36:47
2019-01-10T15:36:47
165,266,870
0
1
null
2019-01-11T15:37:54
2019-01-11T15:37:54
null
UTF-8
R
false
true
1,178
rd
reduce_space.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/streaming.R \name{reduce_space} \alias{reduce_space} \title{Apply a function over space and bands in a four-dimensional (band, time, y, x) array} \usage{ reduce_space(x, FUN, ...) } \arguments{ \item{x}{four-dimensional input bands with dimension order band, time, y, x} \item{FUN}{function which receives one spatial slice in a three-dimensional array with dimensions bands, y, x as input} \item{...}{further arguments passed to FUN} } \description{ Apply a function over space and bands in a four-dimensional (band, time, y, x) array } \details{ FUN is expected to produce a numeric vector (or scalar) where elements are interpreted as new bands in the result } \note{ This is a helper function that uses the same dimension ordering as gdalcubes streaming. It can be used to simplify the application of R functions e.g. over spatial slices in a data cube. } \examples{ \dontrun{ load(system.file("extdata","sample_chunk.Rdata", package="gdalcubes")) y = reduce_space(sample_chunk, function(x) { ndvi <- (x[8,,]-x[4,,])/(x[8,,]+x[4,,]) return(c(min(ndvi, na.rm=TRUE),max(ndvi, na.rm=T))) })} }
7b494e17cbb7fb8117e9c69635edce784a19872e
41f4fdf3a3bedacc3b5905169dbf5af1e4fc44b6
/6205_nsamplemean.R
885fa399ff8ab9b435e1dd0f6d84a7d42ae2dec0
[]
no_license
henrylankin/stat6205
a62867099ca8731a01c31b2f28190bbc7a22c1d7
c846a4f25c74e255a9277102195c2c2598a6b9d8
refs/heads/master
2021-01-23T05:15:14.237114
2017-03-27T04:47:22
2017-03-27T04:47:22
86,292,289
0
0
null
null
null
null
UTF-8
R
false
false
410
r
6205_nsamplemean.R
# 6205 normal sample mean distribution plot mu <- 50 sigma <- 6 x <- seq(mu-3*sigma, mu+3*sigma, by=1) plot(x, dnorm(x,50,6), type = 'l', lty = 'dotted', col = 'red', ylim = c(0,0.5), ylab = 'density') x1 <- seq(50-6, 50+6, by=0.1) lines(x1, dnorm(x1, 50, 6/3), type = 'l', lty = 'dashed', col = 'blue') x2 <- seq(50-3, 50+3, by = 0.005) lines(x2, dnorm(x2, 50, 1), type = "l", lty = "twodash", col = "green")
3ead8fa5b4bd1058f8fb5c5207a71f8e69086f22
1b850eb94c23ee80867279b7ce834e6e9502acc2
/Aries_Web/public/recommend/zxz/diazo/js-built/interaction/cbtview-build2013031.js
4254a6ff54998a6cc648c0aeb33ab6f9dda471d0
[]
no_license
zoeyYan/pro1
b64dc8b655224d7f5f450ea63541016c929097c9
4fe3571cba6e1143d0ad11297b52e8b3b1dc6d81
refs/heads/master
2021-01-10T01:51:23.920569
2016-01-18T02:46:53
2016-01-18T02:46:53
49,711,000
1
1
null
null
null
null
UTF-8
R
false
true
624,901
js
cbtview-build2013031.js
/*! jQuery v@1.8.1 jquery.com | jquery.org/license */ /*! @source http://purl.eligrey.com/github/classList.js/blob/master/classList.js*/ /*! * reveal.js * http://lab.hakim.se/reveal-js * MIT licensed * * Copyright (C) 2013 Hakim El Hattab, http://hakim.se */ /** * Bootstrap.js by @fat & @mdo * plugins: bootstrap-transition.js, bootstrap-modal.js, bootstrap-dropdown.js, bootstrap-scrollspy.js, bootstrap-tab.js, bootstrap-tooltip.js, bootstrap-popover.js, bootstrap-affix.js, bootstrap-alert.js, bootstrap-button.js, bootstrap-collapse.js, bootstrap-carousel.js, bootstrap-typeahead.js * Copyright 2012 Twitter, Inc. * http://www.apache.org/licenses/LICENSE-2.0.txt */ // (c) 2010-2012 Jeremy Ashkenas, DocumentCloud Inc. // Backbone may be freely distributed under the MIT license. // For all details and documentation: // http://backbonejs.org /*! * VERSION: beta 1.9.1 * DATE: 2013-03-19 * JavaScript (ActionScript 3 and 2 also available) * UPDATES AND DOCS AT: http://www.greensock.com * * Includes all of the following: TweenLite, TweenMax, TimelineLite, TimelineMax, easing.EasePack, plugins.CSSPlugin, plugins.RoundPropsPlugin, plugins.BezierPlugin * * @license Copyright (c) 2008-2013, GreenSock. All rights reserved. * This work is subject to the terms in http://www.greensock.com/terms_of_use.html or for * Club GreenSock members, the software agreement that was issued with your membership. * * @author: Jack Doyle, jack@greensock.com **/ /** * @license RequireJS text 2.0.5+ Copyright (c) 2010-2012, The Dojo Foundation All Rights Reserved. * Available via the MIT or new BSD license. * see: http://github.com/requirejs/text for details */ /*! * MediaElement.js * HTML5 <video> and <audio> shim and player * http://mediaelementjs.com/ * * Creates a JavaScript object that mimics HTML5 MediaElement API * for browsers that don't understand HTML5 or can't play the provided codec * Can play MP4 (H.264), Ogg, WebM, FLV, WMV, WMA, ACC, and MP3 * * Copyright 2010-2013, John Dyer (http://j.hn) * License: MIT * */ /*! * MediaElementPlayer * http://mediaelementjs.com/ * * Creates a controller bar for HTML5 <video> add <audio> tags * using jQuery and MediaElement.js (HTML5 Flash/Silverlight wrapper) * * Copyright 2010-2013, John Dyer (http://j.hn/) * License: MIT * */ /*! jQuery UI - v1.9.2 - 2013-07-10 * http://jqueryui.com * Includes: jquery.ui.core.js, jquery.ui.widget.js, jquery.ui.mouse.js, jquery.ui.position.js, jquery.ui.draggable.js, jquery.ui.droppable.js, jquery.ui.resizable.js, jquery.ui.selectable.js, jquery.ui.sortable.js, jquery.ui.effect.js, jquery.ui.effect-blind.js, jquery.ui.effect-bounce.js, jquery.ui.effect-clip.js, jquery.ui.effect-drop.js, jquery.ui.effect-explode.js, jquery.ui.effect-fade.js, jquery.ui.effect-fold.js, jquery.ui.effect-highlight.js, jquery.ui.effect-pulsate.js, jquery.ui.effect-scale.js, jquery.ui.effect-shake.js, jquery.ui.effect-slide.js, jquery.ui.effect-transfer.js * Copyright 2013 jQuery Foundation and other contributors Licensed MIT */ /*! * screenfull * v1.0.4 - 2013-05-26 * https://github.com/sindresorhus/screenfull.js * (c) Sindre Sorhus; MIT License */ function onYouTubePlayerAPIReady(){mejs.YouTubeApi.iFrameReady()}function onYouTubePlayerReady(e){mejs.YouTubeApi.flashReady(e)}(function(e,t){function n(e){var t=dt[e]={};return Y.each(e.split(tt),function(e,n){t[n]=!0}),t}function r(e,n,r){if(r===t&&e.nodeType===1){var i="data-"+n.replace(mt,"-$1").toLowerCase();r=e.getAttribute(i);if(typeof r=="string"){try{r=r==="true"?!0:r==="false"?!1:r==="null"?null:+r+""===r?+r:vt.test(r)?Y.parseJSON(r):r}catch(s){}Y.data(e,n,r)}else r=t}return r}function i(e){var t;for(t in e){if(t==="data"&&Y.isEmptyObject(e[t]))continue;if(t!=="toJSON")return!1}return!0}function s(){return!1}function o(){return!0}function u(e){return!e||!e.parentNode||e.parentNode.nodeType===11}function a(e,t){do e=e[t];while(e&&e.nodeType!==1);return e}function f(e,t,n){t=t||0;if(Y.isFunction(t))return Y.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return Y.grep(e,function(e,r){return e===t===n});if(typeof t=="string"){var r=Y.grep(e,function(e){return e.nodeType===1});if(Bt.test(t))return Y.filter(t,r,!n);t=Y.filter(t,r)}return Y.grep(e,function(e,r){return Y.inArray(e,t)>=0===n})}function l(e){var t=It.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}function c(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function h(e,t){if(t.nodeType!==1||!Y.hasData(e))return;var n,r,i,s=Y._data(e),o=Y._data(t,s),u=s.events;if(u){delete o.handle,o.events={};for(n in u)for(r=0,i=u[n].length;r<i;r++)Y.event.add(t,n,u[n][r])}o.data&&(o.data=Y.extend({},o.data))}function p(e,t){var n;if(t.nodeType!==1)return;t.clearAttributes&&t.clearAttributes(),t.mergeAttributes&&t.mergeAttributes(e),n=t.nodeName.toLowerCase(),n==="object"?(t.parentNode&&(t.outerHTML=e.outerHTML),Y.support.html5Clone&&e.innerHTML&&!Y.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):n==="input"&&Kt.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):n==="option"?t.selected=e.defaultSelected:n==="input"||n==="textarea"?t.defaultValue=e.defaultValue:n==="script"&&t.text!==e.text&&(t.text=e.text),t.removeAttribute(Y.expando)}function d(e){return typeof e.getElementsByTagName!="undefined"?e.getElementsByTagName("*"):typeof e.querySelectorAll!="undefined"?e.querySelectorAll("*"):[]}function v(e){Kt.test(e.type)&&(e.defaultChecked=e.checked)}function m(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=yn.length;while(i--){t=yn[i]+n;if(t in e)return t}return r}function g(e,t){return e=t||e,Y.css(e,"display")==="none"||!Y.contains(e.ownerDocument,e)}function y(e,t){var n,r,i=[],s=0,o=e.length;for(;s<o;s++){n=e[s];if(!n.style)continue;i[s]=Y._data(n,"olddisplay"),t?(!i[s]&&n.style.display==="none"&&(n.style.display=""),n.style.display===""&&g(n)&&(i[s]=Y._data(n,"olddisplay",S(n.nodeName)))):(r=nn(n,"display"),!i[s]&&r!=="none"&&Y._data(n,"olddisplay",r))}for(s=0;s<o;s++){n=e[s];if(!n.style)continue;if(!t||n.style.display==="none"||n.style.display==="")n.style.display=t?i[s]||"":"none"}return e}function b(e,t,n){var r=cn.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function w(e,t,n,r){var i=n===(r?"border":"content")?4:t==="width"?1:0,s=0;for(;i<4;i+=2)n==="margin"&&(s+=Y.css(e,n+gn[i],!0)),r?(n==="content"&&(s-=parseFloat(nn(e,"padding"+gn[i]))||0),n!=="margin"&&(s-=parseFloat(nn(e,"border"+gn[i]+"Width"))||0)):(s+=parseFloat(nn(e,"padding"+gn[i]))||0,n!=="padding"&&(s+=parseFloat(nn(e,"border"+gn[i]+"Width"))||0));return s}function E(e,t,n){var r=t==="width"?e.offsetWidth:e.offsetHeight,i=!0,s=Y.support.boxSizing&&Y.css(e,"boxSizing")==="border-box";if(r<=0||r==null){r=nn(e,t);if(r<0||r==null)r=e.style[t];if(hn.test(r))return r;i=s&&(Y.support.boxSizingReliable||r===e.style[t]),r=parseFloat(r)||0}return r+w(e,t,n||(s?"border":"content"),i)+"px"}function S(e){if(dn[e])return dn[e];var t=Y("<"+e+">").appendTo(R.body),n=t.css("display");t.remove();if(n==="none"||n===""){rn=R.body.appendChild(rn||Y.extend(R.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!sn||!rn.createElement)sn=(rn.contentWindow||rn.contentDocument).document,sn.write("<!doctype html><html><body>"),sn.close();t=sn.body.appendChild(sn.createElement(e)),n=nn(t,"display"),R.body.removeChild(rn)}return dn[e]=n,n}function x(e,t,n,r){var i;if(Y.isArray(t))Y.each(t,function(t,i){n||En.test(e)?r(e,i):x(e+"["+(typeof i=="object"?t:"")+"]",i,n,r)});else if(!n&&Y.type(t)==="object")for(i in t)x(e+"["+i+"]",t[i],n,r);else r(e,t)}function T(e){return function(t,n){typeof t!="string"&&(n=t,t="*");var r,i,s,o=t.toLowerCase().split(tt),u=0,a=o.length;if(Y.isFunction(n))for(;u<a;u++)r=o[u],s=/^\+/.test(r),s&&(r=r.substr(1)||"*"),i=e[r]=e[r]||[],i[s?"unshift":"push"](n)}}function N(e,n,r,i,s,o){s=s||n.dataTypes[0],o=o||{},o[s]=!0;var u,a=e[s],f=0,l=a?a.length:0,c=e===jn;for(;f<l&&(c||!u);f++)u=a[f](n,r,i),typeof u=="string"&&(!c||o[u]?u=t:(n.dataTypes.unshift(u),u=N(e,n,r,i,u,o)));return(c||!u)&&!o["*"]&&(u=N(e,n,r,i,"*",o)),u}function C(e,n){var r,i,s=Y.ajaxSettings.flatOptions||{};for(r in n)n[r]!==t&&((s[r]?e:i||(i={}))[r]=n[r]);i&&Y.extend(!0,e,i)}function k(e,n,r){var i,s,o,u,a=e.contents,f=e.dataTypes,l=e.responseFields;for(s in l)s in r&&(n[l[s]]=r[s]);while(f[0]==="*")f.shift(),i===t&&(i=e.mimeType||n.getResponseHeader("content-type"));if(i)for(s in a)if(a[s]&&a[s].test(i)){f.unshift(s);break}if(f[0]in r)o=f[0];else{for(s in r){if(!f[0]||e.converters[s+" "+f[0]]){o=s;break}u||(u=s)}o=o||u}if(o)return o!==f[0]&&f.unshift(o),r[o]}function L(e,t){var n,r,i,s,o=e.dataTypes.slice(),u=o[0],a={},f=0;e.dataFilter&&(t=e.dataFilter(t,e.dataType));if(o[1])for(n in e.converters)a[n.toLowerCase()]=e.converters[n];for(;i=o[++f];)if(i!=="*"){if(u!=="*"&&u!==i){n=a[u+" "+i]||a["* "+i];if(!n)for(r in a){s=r.split(" ");if(s[1]===i){n=a[u+" "+s[0]]||a["* "+s[0]];if(n){n===!0?n=a[r]:a[r]!==!0&&(i=s[0],o.splice(f--,0,i));break}}}if(n!==!0)if(n&&e["throws"])t=n(t);else try{t=n(t)}catch(l){return{state:"parsererror",error:n?l:"No conversion from "+u+" to "+i}}}u=i}return{state:"success",data:t}}function A(){try{return new e.XMLHttpRequest}catch(t){}}function O(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}function M(){return setTimeout(function(){Jn=t},0),Jn=Y.now()}function _(e,t){Y.each(t,function(t,n){var r=(er[t]||[]).concat(er["*"]),i=0,s=r.length;for(;i<s;i++)if(r[i].call(e,t,n))return})}function D(e,t,n){var r,i=0,s=0,o=Zn.length,u=Y.Deferred().always(function(){delete a.elem}),a=function(){var t=Jn||M(),n=Math.max(0,f.startTime+f.duration-t),r=1-(n/f.duration||0),i=0,s=f.tweens.length;for(;i<s;i++)f.tweens[i].run(r);return u.notifyWith(e,[f,r,n]),r<1&&s?n:(u.resolveWith(e,[f]),!1)},f=u.promise({elem:e,props:Y.extend({},t),opts:Y.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:Jn||M(),duration:n.duration,tweens:[],createTween:function(t,n,r){var i=Y.Tween(e,f.opts,t,n,f.opts.specialEasing[t]||f.opts.easing);return f.tweens.push(i),i},stop:function(t){var n=0,r=t?f.tweens.length:0;for(;n<r;n++)f.tweens[n].run(1);return t?u.resolveWith(e,[f,t]):u.rejectWith(e,[f,t]),this}}),l=f.props;P(l,f.opts.specialEasing);for(;i<o;i++){r=Zn[i].call(f,e,l,f.opts);if(r)return r}return _(f,l),Y.isFunction(f.opts.start)&&f.opts.start.call(e,f),Y.fx.timer(Y.extend(a,{anim:f,queue:f.opts.queue,elem:e})),f.progress(f.opts.progress).done(f.opts.done,f.opts.complete).fail(f.opts.fail).always(f.opts.always)}function P(e,t){var n,r,i,s,o;for(n in e){r=Y.camelCase(n),i=t[r],s=e[n],Y.isArray(s)&&(i=s[1],s=e[n]=s[0]),n!==r&&(e[r]=s,delete e[n]),o=Y.cssHooks[r];if(o&&"expand"in o){s=o.expand(s),delete e[r];for(n in s)n in e||(e[n]=s[n],t[n]=i)}else t[r]=i}}function H(e,t,n){var r,i,s,o,u,a,f,l,c=this,h=e.style,p={},d=[],v=e.nodeType&&g(e);n.queue||(f=Y._queueHooks(e,"fx"),f.unqueued==null&&(f.unqueued=0,l=f.empty.fire,f.empty.fire=function(){f.unqueued||l()}),f.unqueued++,c.always(function(){c.always(function(){f.unqueued--,Y.queue(e,"fx").length||f.empty.fire()})})),e.nodeType===1&&("height"in t||"width"in t)&&(n.overflow=[h.overflow,h.overflowX,h.overflowY],Y.css(e,"display")==="inline"&&Y.css(e,"float")==="none"&&(!Y.support.inlineBlockNeedsLayout||S(e.nodeName)==="inline"?h.display="inline-block":h.zoom=1)),n.overflow&&(h.overflow="hidden",Y.support.shrinkWrapBlocks||c.done(function(){h.overflow=n.overflow[0],h.overflowX=n.overflow[1],h.overflowY=n.overflow[2]}));for(r in t){s=t[r];if(Qn.exec(s)){delete t[r];if(s===(v?"hide":"show"))continue;d.push(r)}}o=d.length;if(o){u=Y._data(e,"fxshow")||Y._data(e,"fxshow",{}),v?Y(e).show():c.done(function(){Y(e).hide()}),c.done(function(){var t;Y.removeData(e,"fxshow",!0);for(t in p)Y.style(e,t,p[t])});for(r=0;r<o;r++)i=d[r],a=c.createTween(i,v?u[i]:0),p[i]=u[i]||Y.style(e,i),i in u||(u[i]=a.start,v&&(a.end=a.start,a.start=i==="width"||i==="height"?1:0))}}function B(e,t,n,r,i){return new B.prototype.init(e,t,n,r,i)}function j(e,t){var n,r={height:e},i=0;t=t?1:0;for(;i<4;i+=2-t)n=gn[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}function F(e){return Y.isWindow(e)?e:e.nodeType===9?e.defaultView||e.parentWindow:!1}var I,q,R=e.document,U=e.location,z=e.navigator,W=e.jQuery,X=e.$,V=Array.prototype.push,$=Array.prototype.slice,J=Array.prototype.indexOf,K=Object.prototype.toString,Q=Object.prototype.hasOwnProperty,G=String.prototype.trim,Y=function(e,t){return new Y.fn.init(e,t,I)},Z=/[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,et=/\S/,tt=/\s+/,nt=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,rt=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,it=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,st=/^[\],:{}\s]*$/,ot=/(?:^|:|,)(?:\s*\[)+/g,ut=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,at=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,ft=/^-ms-/,lt=/-([\da-z])/gi,ct=function(e,t){return(t+"").toUpperCase()},ht=function(){R.addEventListener?(R.removeEventListener("DOMContentLoaded",ht,!1),Y.ready()):R.readyState==="complete"&&(R.detachEvent("onreadystatechange",ht),Y.ready())},pt={};Y.fn=Y.prototype={constructor:Y,init:function(e,n,r){var i,s,o,u;if(!e)return this;if(e.nodeType)return this.context=this[0]=e,this.length=1,this;if(typeof e=="string"){e.charAt(0)==="<"&&e.charAt(e.length-1)===">"&&e.length>=3?i=[null,e,null]:i=rt.exec(e);if(i&&(i[1]||!n)){if(i[1])return n=n instanceof Y?n[0]:n,u=n&&n.nodeType?n.ownerDocument||n:R,e=Y.parseHTML(i[1],u,!0),it.test(i[1])&&Y.isPlainObject(n)&&this.attr.call(e,n,!0),Y.merge(this,e);s=R.getElementById(i[2]);if(s&&s.parentNode){if(s.id!==i[2])return r.find(e);this.length=1,this[0]=s}return this.context=R,this.selector=e,this}return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e)}return Y.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),Y.makeArray(e,this))},selector:"",jquery:"1.8.1",length:0,size:function(){return this.length},toArray:function(){return $.call(this)},get:function(e){return e==null?this.toArray():e<0?this[this.length+e]:this[e]},pushStack:function(e,t,n){var r=Y.merge(this.constructor(),e);return r.prevObject=this,r.context=this.context,t==="find"?r.selector=this.selector+(this.selector?" ":"")+n:t&&(r.selector=this.selector+"."+t+"("+n+")"),r},each:function(e,t){return Y.each(this,e,t)},ready:function(e){return Y.ready.promise().done(e),this},eq:function(e){return e=+e,e===-1?this.slice(e):this.slice(e,e+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack($.apply(this,arguments),"slice",$.call(arguments).join(","))},map:function(e){return this.pushStack(Y.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:V,sort:[].sort,splice:[].splice},Y.fn.init.prototype=Y.fn,Y.extend=Y.fn.extend=function(){var e,n,r,i,s,o,u=arguments[0]||{},a=1,f=arguments.length,l=!1;typeof u=="boolean"&&(l=u,u=arguments[1]||{},a=2),typeof u!="object"&&!Y.isFunction(u)&&(u={}),f===a&&(u=this,--a);for(;a<f;a++)if((e=arguments[a])!=null)for(n in e){r=u[n],i=e[n];if(u===i)continue;l&&i&&(Y.isPlainObject(i)||(s=Y.isArray(i)))?(s?(s=!1,o=r&&Y.isArray(r)?r:[]):o=r&&Y.isPlainObject(r)?r:{},u[n]=Y.extend(l,o,i)):i!==t&&(u[n]=i)}return u},Y.extend({noConflict:function(t){return e.$===Y&&(e.$=X),t&&e.jQuery===Y&&(e.jQuery=W),Y},isReady:!1,readyWait:1,holdReady:function(e){e?Y.readyWait++:Y.ready(!0)},ready:function(e){if(e===!0?--Y.readyWait:Y.isReady)return;if(!R.body)return setTimeout(Y.ready,1);Y.isReady=!0;if(e!==!0&&--Y.readyWait>0)return;q.resolveWith(R,[Y]),Y.fn.trigger&&Y(R).trigger("ready").off("ready")},isFunction:function(e){return Y.type(e)==="function"},isArray:Array.isArray||function(e){return Y.type(e)==="array"},isWindow:function(e){return e!=null&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return e==null?String(e):pt[K.call(e)]||"object"},isPlainObject:function(e){if(!e||Y.type(e)!=="object"||e.nodeType||Y.isWindow(e))return!1;try{if(e.constructor&&!Q.call(e,"constructor")&&!Q.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||Q.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw new Error(e)},parseHTML:function(e,t,n){var r;return!e||typeof e!="string"?null:(typeof t=="boolean"&&(n=t,t=0),t=t||R,(r=it.exec(e))?[t.createElement(r[1])]:(r=Y.buildFragment([e],t,n?null:[]),Y.merge([],(r.cacheable?Y.clone(r.fragment):r.fragment).childNodes)))},parseJSON:function(t){if(!t||typeof t!="string")return null;t=Y.trim(t);if(e.JSON&&e.JSON.parse)return e.JSON.parse(t);if(st.test(t.replace(ut,"@").replace(at,"]").replace(ot,"")))return(new Function("return "+t))();Y.error("Invalid JSON: "+t)},parseXML:function(n){var r,i;if(!n||typeof n!="string")return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(s){r=t}return(!r||!r.documentElement||r.getElementsByTagName("parsererror").length)&&Y.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&et.test(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(ft,"ms-").replace(lt,ct)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toUpperCase()===t.toUpperCase()},each:function(e,n,r){var i,s=0,o=e.length,u=o===t||Y.isFunction(e);if(r){if(u){for(i in e)if(n.apply(e[i],r)===!1)break}else for(;s<o;)if(n.apply(e[s++],r)===!1)break}else if(u){for(i in e)if(n.call(e[i],i,e[i])===!1)break}else for(;s<o;)if(n.call(e[s],s,e[s++])===!1)break;return e},trim:G&&!G.call(" ")?function(e){return e==null?"":G.call(e)}:function(e){return e==null?"":e.toString().replace(nt,"")},makeArray:function(e,t){var n,r=t||[];return e!=null&&(n=Y.type(e),e.length==null||n==="string"||n==="function"||n==="regexp"||Y.isWindow(e)?V.call(r,e):Y.merge(r,e)),r},inArray:function(e,t,n){var r;if(t){if(J)return J.call(t,e,n);r=t.length,n=n?n<0?Math.max(0,r+n):n:0;for(;n<r;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,s=0;if(typeof r=="number")for(;s<r;s++)e[i++]=n[s];else while(n[s]!==t)e[i++]=n[s++];return e.length=i,e},grep:function(e,t,n){var r,i=[],s=0,o=e.length;n=!!n;for(;s<o;s++)r=!!t(e[s],s),n!==r&&i.push(e[s]);return i},map:function(e,n,r){var i,s,o=[],u=0,a=e.length,f=e instanceof Y||a!==t&&typeof a=="number"&&(a>0&&e[0]&&e[a-1]||a===0||Y.isArray(e));if(f)for(;u<a;u++)i=n(e[u],u,r),i!=null&&(o[o.length]=i);else for(s in e)i=n(e[s],s,r),i!=null&&(o[o.length]=i);return o.concat.apply([],o)},guid:1,proxy:function(e,n){var r,i,s;return typeof n=="string"&&(r=e[n],n=e,e=r),Y.isFunction(e)?(i=$.call(arguments,2),s=function(){return e.apply(n,i.concat($.call(arguments)))},s.guid=e.guid=e.guid||s.guid||Y.guid++,s):t},access:function(e,n,r,i,s,o,u){var a,f=r==null,l=0,c=e.length;if(r&&typeof r=="object"){for(l in r)Y.access(e,n,l,r[l],1,o,i);s=1}else if(i!==t){a=u===t&&Y.isFunction(i),f&&(a?(a=n,n=function(e,t,n){return a.call(Y(e),n)}):(n.call(e,i),n=null));if(n)for(;l<c;l++)n(e[l],r,a?i.call(e[l],l,n(e[l],r)):i,u);s=1}return s?e:f?n.call(e):c?n(e[0],r):o},now:function(){return(new Date).getTime()}}),Y.ready.promise=function(t){if(!q){q=Y.Deferred();if(R.readyState==="complete")setTimeout(Y.ready,1);else if(R.addEventListener)R.addEventListener("DOMContentLoaded",ht,!1),e.addEventListener("load",Y.ready,!1);else{R.attachEvent("onreadystatechange",ht),e.attachEvent("onload",Y.ready);var n=!1;try{n=e.frameElement==null&&R.documentElement}catch(r){}n&&n.doScroll&&function i(){if(!Y.isReady){try{n.doScroll("left")}catch(e){return setTimeout(i,50)}Y.ready()}}()}}return q.promise(t)},Y.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(e,t){pt["[object "+t+"]"]=t.toLowerCase()}),I=Y(R);var dt={};Y.Callbacks=function(e){e=typeof e=="string"?dt[e]||n(e):Y.extend({},e);var r,i,s,o,u,a,f=[],l=!e.once&&[],c=function(t){r=e.memory&&t,i=!0,a=o||0,o=0,u=f.length,s=!0;for(;f&&a<u;a++)if(f[a].apply(t[0],t[1])===!1&&e.stopOnFalse){r=!1;break}s=!1,f&&(l?l.length&&c(l.shift()):r?f=[]:h.disable())},h={add:function(){if(f){var t=f.length;(function n(t){Y.each(t,function(t,r){var i=Y.type(r);i==="function"&&(!e.unique||!h.has(r))?f.push(r):r&&r.length&&i!=="string"&&n(r)})})(arguments),s?u=f.length:r&&(o=t,c(r))}return this},remove:function(){return f&&Y.each(arguments,function(e,t){var n;while((n=Y.inArray(t,f,n))>-1)f.splice(n,1),s&&(n<=u&&u--,n<=a&&a--)}),this},has:function(e){return Y.inArray(e,f)>-1},empty:function(){return f=[],this},disable:function(){return f=l=r=t,this},disabled:function(){return!f},lock:function(){return l=t,r||h.disable(),this},locked:function(){return!l},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],f&&(!i||l)&&(s?l.push(t):c(t)),this},fire:function(){return h.fireWith(this,arguments),this},fired:function(){return!!i}};return h},Y.extend({Deferred:function(e){var t=[["resolve","done",Y.Callbacks("once memory"),"resolved"],["reject","fail",Y.Callbacks("once memory"),"rejected"],["notify","progress",Y.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return Y.Deferred(function(n){Y.each(t,function(t,r){var s=r[0],o=e[t];i[r[1]](Y.isFunction(o)?function(){var e=o.apply(this,arguments);e&&Y.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[s+"With"](this===i?n:this,[e])}:n[s])}),e=null}).promise()},promise:function(e){return typeof e=="object"?Y.extend(e,r):r}},i={};return r.pipe=r.then,Y.each(t,function(e,s){var o=s[2],u=s[3];r[s[1]]=o.add,u&&o.add(function(){n=u},t[e^1][2].disable,t[2][2].lock),i[s[0]]=o.fire,i[s[0]+"With"]=o.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=$.call(arguments),r=n.length,i=r!==1||e&&Y.isFunction(e.promise)?r:0,s=i===1?e:Y.Deferred(),o=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?$.call(arguments):r,n===u?s.notifyWith(t,n):--i||s.resolveWith(t,n)}},u,a,f;if(r>1){u=new Array(r),a=new Array(r),f=new Array(r);for(;t<r;t++)n[t]&&Y.isFunction(n[t].promise)?n[t].promise().done(o(t,f,n)).fail(s.reject).progress(o(t,a,u)):--i}return i||s.resolveWith(f,n),s.promise()}}),Y.support=function(){var t,n,r,i,s,o,u,a,f,l,c,h=R.createElement("div");h.setAttribute("className","t"),h.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=h.getElementsByTagName("*"),r=h.getElementsByTagName("a")[0],r.style.cssText="top:1px;float:left;opacity:.5";if(!n||!n.length||!r)return{};i=R.createElement("select"),s=i.appendChild(R.createElement("option")),o=h.getElementsByTagName("input")[0],t={leadingWhitespace:h.firstChild.nodeType===3,tbody:!h.getElementsByTagName("tbody").length,htmlSerialize:!!h.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:r.getAttribute("href")==="/a",opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:o.value==="on",optSelected:s.selected,getSetAttribute:h.className!=="t",enctype:!!R.createElement("form").enctype,html5Clone:R.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",boxModel:R.compatMode==="CSS1Compat",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},o.checked=!0,t.noCloneChecked=o.cloneNode(!0).checked,i.disabled=!0,t.optDisabled=!s.disabled;try{delete h.test}catch(p){t.deleteExpando=!1}!h.addEventListener&&h.attachEvent&&h.fireEvent&&(h.attachEvent("onclick",c=function(){t.noCloneEvent=!1}),h.cloneNode(!0).fireEvent("onclick"),h.detachEvent("onclick",c)),o=R.createElement("input"),o.value="t",o.setAttribute("type","radio"),t.radioValue=o.value==="t",o.setAttribute("checked","checked"),o.setAttribute("name","t"),h.appendChild(o),u=R.createDocumentFragment(),u.appendChild(h.lastChild),t.checkClone=u.cloneNode(!0).cloneNode(!0).lastChild.checked,t.appendChecked=o.checked,u.removeChild(o),u.appendChild(h);if(h.attachEvent)for(f in{submit:!0,change:!0,focusin:!0})a="on"+f,l=a in h,l||(h.setAttribute(a,"return;"),l=typeof h[a]=="function"),t[f+"Bubbles"]=l;return Y(function(){var n,r,i,s,o="padding:0;margin:0;border:0;display:block;overflow:hidden;",u=R.getElementsByTagName("body")[0];if(!u)return;n=R.createElement("div"),n.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",u.insertBefore(n,u.firstChild),r=R.createElement("div"),n.appendChild(r),r.innerHTML="<table><tr><td></td><td>t</td></tr></table>",i=r.getElementsByTagName("td"),i[0].style.cssText="padding:0;margin:0;border:0;display:none",l=i[0].offsetHeight===0,i[0].style.display="",i[1].style.display="none",t.reliableHiddenOffsets=l&&i[0].offsetHeight===0,r.innerHTML="",r.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%;",t.boxSizing=r.offsetWidth===4,t.doesNotIncludeMarginInBodyOffset=u.offsetTop!==1,e.getComputedStyle&&(t.pixelPosition=(e.getComputedStyle(r,null)||{}).top!=="1%",t.boxSizingReliable=(e.getComputedStyle(r,null)||{width:"4px"}).width==="4px",s=R.createElement("div"),s.style.cssText=r.style.cssText=o,s.style.marginRight=s.style.width="0",r.style.width="1px",r.appendChild(s),t.reliableMarginRight=!parseFloat((e.getComputedStyle(s,null)||{}).marginRight)),typeof r.style.zoom!="undefined"&&(r.innerHTML="",r.style.cssText=o+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=r.offsetWidth===3,r.style.display="block",r.style.overflow="visible",r.innerHTML="<div></div>",r.firstChild.style.width="5px",t.shrinkWrapBlocks=r.offsetWidth!==3,n.style.zoom=1),u.removeChild(n),n=r=i=s=null}),u.removeChild(h),n=r=i=s=o=u=h=null,t}();var vt=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,mt=/([A-Z])/g;Y.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(Y.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?Y.cache[e[Y.expando]]:e[Y.expando],!!e&&!i(e)},data:function(e,n,r,i){if(!Y.acceptData(e))return;var s,o,u=Y.expando,a=typeof n=="string",f=e.nodeType,l=f?Y.cache:e,c=f?e[u]:e[u]&&u;if((!c||!l[c]||!i&&!l[c].data)&&a&&r===t)return;c||(f?e[u]=c=Y.deletedIds.pop()||++Y.uuid:c=u),l[c]||(l[c]={},f||(l[c].toJSON=Y.noop));if(typeof n=="object"||typeof n=="function")i?l[c]=Y.extend(l[c],n):l[c].data=Y.extend(l[c].data,n);return s=l[c],i||(s.data||(s.data={}),s=s.data),r!==t&&(s[Y.camelCase(n)]=r),a?(o=s[n],o==null&&(o=s[Y.camelCase(n)])):o=s,o},removeData:function(e,t,n){if(!Y.acceptData(e))return;var r,s,o,u=e.nodeType,a=u?Y.cache:e,f=u?e[Y.expando]:Y.expando;if(!a[f])return;if(t){r=n?a[f]:a[f].data;if(r){Y.isArray(t)||(t in r?t=[t]:(t=Y.camelCase(t),t in r?t=[t]:t=t.split(" ")));for(s=0,o=t.length;s<o;s++)delete r[t[s]];if(!(n?i:Y.isEmptyObject)(r))return}}if(!n){delete a[f].data;if(!i(a[f]))return}u?Y.cleanData([e],!0):Y.support.deleteExpando||a!=a.window?delete a[f]:a[f]=null},_data:function(e,t,n){return Y.data(e,t,n,!0)},acceptData:function(e){var t=e.nodeName&&Y.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),Y.fn.extend({data:function(e,n){var i,s,o,u,a,f=this[0],l=0,c=null;if(e===t){if(this.length){c=Y.data(f);if(f.nodeType===1&&!Y._data(f,"parsedAttrs")){o=f.attributes;for(a=o.length;l<a;l++)u=o[l].name,u.indexOf("data-")===0&&(u=Y.camelCase(u.substring(5)),r(f,u,c[u]));Y._data(f,"parsedAttrs",!0)}}return c}return typeof e=="object"?this.each(function(){Y.data(this,e)}):(i=e.split(".",2),i[1]=i[1]?"."+i[1]:"",s=i[1]+"!",Y.access(this,function(n){if(n===t)return c=this.triggerHandler("getData"+s,[i[0]]),c===t&&f&&(c=Y.data(f,e),c=r(f,e,c)),c===t&&i[1]?this.data(i[0]):c;i[1]=n,this.each(function(){var t=Y(this);t.triggerHandler("setData"+s,i),Y.data(this,e,n),t.triggerHandler("changeData"+s,i)})},null,n,arguments.length>1,null,!1))},removeData:function(e){return this.each(function(){Y.removeData(this,e)})}}),Y.extend({queue:function(e,t,n){var r;if(e)return t=(t||"fx")+"queue",r=Y._data(e,t),n&&(!r||Y.isArray(n)?r=Y._data(e,t,Y.makeArray(n)):r.push(n)),r||[]},dequeue:function(e,t){t=t||"fx";var n=Y.queue(e,t),r=n.length,i=n.shift(),s=Y._queueHooks(e,t),o=function(){Y.dequeue(e,t)};i==="inprogress"&&(i=n.shift(),r--),i&&(t==="fx"&&n.unshift("inprogress"),delete s.stop,i.call(e,o,s)),!r&&s&&s.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return Y._data(e,n)||Y._data(e,n,{empty:Y.Callbacks("once memory").add(function(){Y.removeData(e,t+"queue",!0),Y.removeData(e,n,!0)})})}}),Y.fn.extend({queue:function(e,n){var r=2;return typeof e!="string"&&(n=e,e="fx",r--),arguments.length<r?Y.queue(this[0],e):n===t?this:this.each(function(){var t=Y.queue(this,e,n);Y._queueHooks(this,e),e==="fx"&&t[0]!=="inprogress"&&Y.dequeue(this,e)})},dequeue:function(e){return this.each(function(){Y.dequeue(this,e)})},delay:function(e,t){return e=Y.fx?Y.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,n){var r,i=1,s=Y.Deferred(),o=this,u=this.length,a=function(){--i||s.resolveWith(o,[o])};typeof e!="string"&&(n=e,e=t),e=e||"fx";while(u--)r=Y._data(o[u],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(a));return a(),s.promise(n)}});var gt,yt,bt,wt=/[\t\r\n]/g,Et=/\r/g,St=/^(?:button|input)$/i,xt=/^(?:button|input|object|select|textarea)$/i,Tt=/^a(?:rea|)$/i,Nt=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,Ct=Y.support.getSetAttribute;Y.fn.extend({attr:function(e,t){return Y.access(this,Y.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){Y.removeAttr(this,e)})},prop:function(e,t){return Y.access(this,Y.prop,e,t,arguments.length>1)},removeProp:function(e){return e=Y.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,s,o,u;if(Y.isFunction(e))return this.each(function(t){Y(this).addClass(e.call(this,t,this.className))});if(e&&typeof e=="string"){t=e.split(tt);for(n=0,r=this.length;n<r;n++){i=this[n];if(i.nodeType===1)if(!i.className&&t.length===1)i.className=e;else{s=" "+i.className+" ";for(o=0,u=t.length;o<u;o++)~s.indexOf(" "+t[o]+" ")||(s+=t[o]+" ");i.className=Y.trim(s)}}}return this},removeClass:function(e){var n,r,i,s,o,u,a;if(Y.isFunction(e))return this.each(function(t){Y(this).removeClass(e.call(this,t,this.className))});if(e&&typeof e=="string"||e===t){n=(e||"").split(tt);for(u=0,a=this.length;u<a;u++){i=this[u];if(i.nodeType===1&&i.className){r=(" "+i.className+" ").replace(wt," ");for(s=0,o=n.length;s<o;s++)while(r.indexOf(" "+n[s]+" ")>-1)r=r.replace(" "+n[s]+" "," ");i.className=e?Y.trim(r):""}}}return this},toggleClass:function(e,t){var n=typeof e,r=typeof t=="boolean";return Y.isFunction(e)?this.each(function(n){Y(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if(n==="string"){var i,s=0,o=Y(this),u=t,a=e.split(tt);while(i=a[s++])u=r?u:!o.hasClass(i),o[u?"addClass":"removeClass"](i)}else if(n==="undefined"||n==="boolean")this.className&&Y._data(this,"__className__",this.className),this.className=this.className||e===!1?"":Y._data(this,"__className__")||""})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;n<r;n++)if(this[n].nodeType===1&&(" "+this[n].className+" ").replace(wt," ").indexOf(t)>-1)return!0;return!1},val:function(e){var n,r,i,s=this[0];if(!arguments.length){if(s)return n=Y.valHooks[s.type]||Y.valHooks[s.nodeName.toLowerCase()],n&&"get"in n&&(r=n.get(s,"value"))!==t?r:(r=s.value,typeof r=="string"?r.replace(Et,""):r==null?"":r);return}return i=Y.isFunction(e),this.each(function(r){var s,o=Y(this);if(this.nodeType!==1)return;i?s=e.call(this,r,o.val()):s=e,s==null?s="":typeof s=="number"?s+="":Y.isArray(s)&&(s=Y.map(s,function(e){return e==null?"":e+""})),n=Y.valHooks[this.type]||Y.valHooks[this.nodeName.toLowerCase()];if(!n||!("set"in n)||n.set(this,s,"value")===t)this.value=s})}}),Y.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r,i,s=e.selectedIndex,o=[],u=e.options,a=e.type==="select-one";if(s<0)return null;n=a?s:0,r=a?s+1:u.length;for(;n<r;n++){i=u[n];if(i.selected&&(Y.support.optDisabled?!i.disabled:i.getAttribute("disabled")===null)&&(!i.parentNode.disabled||!Y.nodeName(i.parentNode,"optgroup"))){t=Y(i).val();if(a)return t;o.push(t)}}return a&&!o.length&&u.length?Y(u[s]).val():o},set:function(e,t){var n=Y.makeArray(t);return Y(e).find("option").each(function(){this.selected=Y.inArray(Y(this).val(),n)>=0}),n.length||(e.selectedIndex=-1),n}}},attrFn:{},attr:function(e,n,r,i){var s,o,u,a=e.nodeType;if(!e||a===3||a===8||a===2)return;if(i&&Y.isFunction(Y.fn[n]))return Y(e)[n](r);if(typeof e.getAttribute=="undefined")return Y.prop(e,n,r);u=a!==1||!Y.isXMLDoc(e),u&&(n=n.toLowerCase(),o=Y.attrHooks[n]||(Nt.test(n)?yt:gt));if(r!==t){if(r===null){Y.removeAttr(e,n);return}return o&&"set"in o&&u&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,""+r),r)}return o&&"get"in o&&u&&(s=o.get(e,n))!==null?s:(s=e.getAttribute(n),s===null?t:s)},removeAttr:function(e,t){var n,r,i,s,o=0;if(t&&e.nodeType===1){r=t.split(tt);for(;o<r.length;o++)i=r[o],i&&(n=Y.propFix[i]||i,s=Nt.test(i),s||Y.attr(e,i,""),e.removeAttribute(Ct?i:n),s&&n in e&&(e[n]=!1))}},attrHooks:{type:{set:function(e,t){if(St.test(e.nodeName)&&e.parentNode)Y.error("type property can't be changed");else if(!Y.support.radioValue&&t==="radio"&&Y.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}},value:{get:function(e,t){return gt&&Y.nodeName(e,"button")?gt.get(e,t):t in e?e.value:null},set:function(e,t,n){if(gt&&Y.nodeName(e,"button"))return gt.set(e,t,n);e.value=t}}},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(e,n,r){var i,s,o,u=e.nodeType;if(!e||u===3||u===8||u===2)return;return o=u!==1||!Y.isXMLDoc(e),o&&(n=Y.propFix[n]||n,s=Y.propHooks[n]),r!==t?s&&"set"in s&&(i=s.set(e,r,n))!==t?i:e[n]=r:s&&"get"in s&&(i=s.get(e,n))!==null?i:e[n]},propHooks:{tabIndex:{get:function(e){var n=e.getAttributeNode("tabindex");return n&&n.specified?parseInt(n.value,10):xt.test(e.nodeName)||Tt.test(e.nodeName)&&e.href?0:t}}}}),yt={get:function(e,n){var r,i=Y.prop(e,n);return i===!0||typeof i!="boolean"&&(r=e.getAttributeNode(n))&&r.nodeValue!==!1?n.toLowerCase():t},set:function(e,t,n){var r;return t===!1?Y.removeAttr(e,n):(r=Y.propFix[n]||n,r in e&&(e[r]=!0),e.setAttribute(n,n.toLowerCase())),n}},Ct||(bt={name:!0,id:!0,coords:!0},gt=Y.valHooks.button={get:function(e,n){var r;return r=e.getAttributeNode(n),r&&(bt[n]?r.value!=="":r.specified)?r.value:t},set:function(e,t,n){var r=e.getAttributeNode(n);return r||(r=R.createAttribute(n),e.setAttributeNode(r)),r.value=t+""}},Y.each(["width","height"],function(e,t){Y.attrHooks[t]=Y.extend(Y.attrHooks[t],{set:function(e,n){if(n==="")return e.setAttribute(t,"auto"),n}})}),Y.attrHooks.contenteditable={get:gt.get,set:function(e,t,n){t===""&&(t="false"),gt.set(e,t,n)}}),Y.support.hrefNormalized||Y.each(["href","src","width","height"],function(e,n){Y.attrHooks[n]=Y.extend(Y.attrHooks[n],{get:function(e){var r=e.getAttribute(n,2);return r===null?t:r}})}),Y.support.style||(Y.attrHooks.style={get:function(e){return e.style.cssText.toLowerCase()||t},set:function(e,t){return e.style.cssText=""+t}}),Y.support.optSelected||(Y.propHooks.selected=Y.extend(Y.propHooks.selected,{get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}})),Y.support.enctype||(Y.propFix.enctype="encoding"),Y.support.checkOn||Y.each(["radio","checkbox"],function(){Y.valHooks[this]={get:function(e){return e.getAttribute("value")===null?"on":e.value}}}),Y.each(["radio","checkbox"],function(){Y.valHooks[this]=Y.extend(Y.valHooks[this],{set:function(e,t){if(Y.isArray(t))return e.checked=Y.inArray(Y(e).val(),t)>=0}})});var kt=/^(?:textarea|input|select)$/i,Lt=/^([^\.]*|)(?:\.(.+)|)$/,At=/(?:^|\s)hover(\.\S+|)\b/,Ot=/^key/,Mt=/^(?:mouse|contextmenu)|click/,_t=/^(?:focusinfocus|focusoutblur)$/,Dt=function(e){return Y.event.special.hover?e:e.replace(At,"mouseenter$1 mouseleave$1")};Y.event={add:function(e,n,r,i,s){var o,u,a,f,l,c,h,p,d,v,m;if(e.nodeType===3||e.nodeType===8||!n||!r||!(o=Y._data(e)))return;r.handler&&(d=r,r=d.handler,s=d.selector),r.guid||(r.guid=Y.guid++),a=o.events,a||(o.events=a={}),u=o.handle,u||(o.handle=u=function(e){return typeof Y=="undefined"||!!e&&Y.event.triggered===e.type?t:Y.event.dispatch.apply(u.elem,arguments)},u.elem=e),n=Y.trim(Dt(n)).split(" ");for(f=0;f<n.length;f++){l=Lt.exec(n[f])||[],c=l[1],h=(l[2]||"").split(".").sort(),m=Y.event.special[c]||{},c=(s?m.delegateType:m.bindType)||c,m=Y.event.special[c]||{},p=Y.extend({type:c,origType:l[1],data:i,handler:r,guid:r.guid,selector:s,namespace:h.join(".")},d),v=a[c];if(!v){v=a[c]=[],v.delegateCount=0;if(!m.setup||m.setup.call(e,i,h,u)===!1)e.addEventListener?e.addEventListener(c,u,!1):e.attachEvent&&e.attachEvent("on"+c,u)}m.add&&(m.add.call(e,p),p.handler.guid||(p.handler.guid=r.guid)),s?v.splice(v.delegateCount++,0,p):v.push(p),Y.event.global[c]=!0}e=null},global:{},remove:function(e,t,n,r,i){var s,o,u,a,f,l,c,h,p,d,v,m=Y.hasData(e)&&Y._data(e);if(!m||!(h=m.events))return;t=Y.trim(Dt(t||"")).split(" ");for(s=0;s<t.length;s++){o=Lt.exec(t[s])||[],u=a=o[1],f=o[2];if(!u){for(u in h)Y.event.remove(e,u+t[s],n,r,!0);continue}p=Y.event.special[u]||{},u=(r?p.delegateType:p.bindType)||u,d=h[u]||[],l=d.length,f=f?new RegExp("(^|\\.)"+f.split(".").sort().join("\\.(?:.*\\.|)")+"(\\.|$)"):null;for(c=0;c<d.length;c++)v=d[c],(i||a===v.origType)&&(!n||n.guid===v.guid)&&(!f||f.test(v.namespace))&&(!r||r===v.selector||r==="**"&&v.selector)&&(d.splice(c--,1),v.selector&&d.delegateCount--,p.remove&&p.remove.call(e,v));d.length===0&&l!==d.length&&((!p.teardown||p.teardown.call(e,f,m.handle)===!1)&&Y.removeEvent(e,u,m.handle),delete h[u])}Y.isEmptyObject(h)&&(delete m.handle,Y.removeData(e,"events",!0))},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(n,r,i,s){if(!i||i.nodeType!==3&&i.nodeType!==8){var o,u,a,f,l,c,h,p,d,v,m=n.type||n,g=[];if(_t.test(m+Y.event.triggered))return;m.indexOf("!")>=0&&(m=m.slice(0,-1),u=!0),m.indexOf(".")>=0&&(g=m.split("."),m=g.shift(),g.sort());if((!i||Y.event.customEvent[m])&&!Y.event.global[m])return;n=typeof n=="object"?n[Y.expando]?n:new Y.Event(m,n):new Y.Event(m),n.type=m,n.isTrigger=!0,n.exclusive=u,n.namespace=g.join("."),n.namespace_re=n.namespace?new RegExp("(^|\\.)"+g.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,c=m.indexOf(":")<0?"on"+m:"";if(!i){o=Y.cache;for(a in o)o[a].events&&o[a].events[m]&&Y.event.trigger(n,r,o[a].handle.elem,!0);return}n.result=t,n.target||(n.target=i),r=r!=null?Y.makeArray(r):[],r.unshift(n),h=Y.event.special[m]||{};if(h.trigger&&h.trigger.apply(i,r)===!1)return;d=[[i,h.bindType||m]];if(!s&&!h.noBubble&&!Y.isWindow(i)){v=h.delegateType||m,f=_t.test(v+m)?i:i.parentNode;for(l=i;f;f=f.parentNode)d.push([f,v]),l=f;l===(i.ownerDocument||R)&&d.push([l.defaultView||l.parentWindow||e,v])}for(a=0;a<d.length&&!n.isPropagationStopped();a++)f=d[a][0],n.type=d[a][1],p=(Y._data(f,"events")||{})[n.type]&&Y._data(f,"handle"),p&&p.apply(f,r),p=c&&f[c],p&&Y.acceptData(f)&&p.apply(f,r)===!1&&n.preventDefault();return n.type=m,!s&&!n.isDefaultPrevented()&&(!h._default||h._default.apply(i.ownerDocument,r)===!1)&&(m!=="click"||!Y.nodeName(i,"a"))&&Y.acceptData(i)&&c&&i[m]&&(m!=="focus"&&m!=="blur"||n.target.offsetWidth!==0)&&!Y.isWindow(i)&&(l=i[c],l&&(i[c]=null),Y.event.triggered=m,i[m](),Y.event.triggered=t,l&&(i[c]=l)),n.result}return},dispatch:function(n){n=Y.event.fix(n||e.event);var r,i,s,o,u,a,f,l,c,h,p=(Y._data(this,"events")||{})[n.type]||[],d=p.delegateCount,v=[].slice.call(arguments),m=!n.exclusive&&!n.namespace,g=Y.event.special[n.type]||{},y=[];v[0]=n,n.delegateTarget=this;if(g.preDispatch&&g.preDispatch.call(this,n)===!1)return;if(d&&(!n.button||n.type!=="click"))for(s=n.target;s!=this;s=s.parentNode||this)if(s.disabled!==!0||n.type!=="click"){u={},f=[];for(r=0;r<d;r++)l=p[r],c=l.selector,u[c]===t&&(u[c]=Y(c,this).index(s)>=0),u[c]&&f.push(l);f.length&&y.push({elem:s,matches:f})}p.length>d&&y.push({elem:this,matches:p.slice(d)});for(r=0;r<y.length&&!n.isPropagationStopped();r++){a=y[r],n.currentTarget=a.elem;for(i=0;i<a.matches.length&&!n.isImmediatePropagationStopped();i++){l=a.matches[i];if(m||!n.namespace&&!l.namespace||n.namespace_re&&n.namespace_re.test(l.namespace))n.data=l.data,n.handleObj=l,o=((Y.event.special[l.origType]||{}).handle||l.handler).apply(a.elem,v),o!==t&&(n.result=o,o===!1&&(n.preventDefault(),n.stopPropagation()))}}return g.postDispatch&&g.postDispatch.call(this,n),n.result},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(e,t){return e.which==null&&(e.which=t.charCode!=null?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,n){var r,i,s,o=n.button,u=n.fromElement;return e.pageX==null&&n.clientX!=null&&(r=e.target.ownerDocument||R,i=r.documentElement,s=r.body,e.pageX=n.clientX+(i&&i.scrollLeft||s&&s.scrollLeft||0)-(i&&i.clientLeft||s&&s.clientLeft||0),e.pageY=n.clientY+(i&&i.scrollTop||s&&s.scrollTop||0)-(i&&i.clientTop||s&&s.clientTop||0)),!e.relatedTarget&&u&&(e.relatedTarget=u===e.target?n.toElement:u),!e.which&&o!==t&&(e.which=o&1?1:o&2?3:o&4?2:0),e}},fix:function(e){if(e[Y.expando])return e;var t,n,r=e,i=Y.event.fixHooks[e.type]||{},s=i.props?this.props.concat(i.props):this.props;e=Y.Event(r);for(t=s.length;t;)n=s[--t],e[n]=r[n];return e.target||(e.target=r.srcElement||R),e.target.nodeType===3&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,i.filter?i.filter(e,r):e},special:{load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(e,t,n){Y.isWindow(this)&&(this.onbeforeunload=n)},teardown:function(e,t){this.onbeforeunload===t&&(this.onbeforeunload=null)}}},simulate:function(e,t,n,r){var i=Y.extend(new Y.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?Y.event.trigger(i,null,t):Y.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},Y.event.handle=Y.event.dispatch,Y.removeEvent=R.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]=="undefined"&&(e[r]=null),e.detachEvent(r,n))},Y.Event=function(e,t){if(!(this instanceof Y.Event))return new Y.Event(e,t);e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?o:s):this.type=e,t&&Y.extend(this,t),this.timeStamp=e&&e.timeStamp||Y.now(),this[Y.expando]=!0},Y.Event.prototype={preventDefault:function(){this.isDefaultPrevented=o;var e=this.originalEvent;if(!e)return;e.preventDefault?e.preventDefault():e.returnValue=!1},stopPropagation:function(){this.isPropagationStopped=o;var e=this.originalEvent;if(!e)return;e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=o,this.stopPropagation()},isDefaultPrevented:s,isPropagationStopped:s,isImmediatePropagationStopped:s},Y.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){Y.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,s=e.handleObj,o=s.selector;if(!i||i!==r&&!Y.contains(r,i))e.type=s.origType,n=s.handler.apply(this,arguments),e.type=t;return n}}}),Y.support.submitBubbles||(Y.event.special.submit={setup:function(){if(Y.nodeName(this,"form"))return!1;Y.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=Y.nodeName(n,"input")||Y.nodeName(n,"button")?n.form:t;r&&!Y._data(r,"_submit_attached")&&(Y.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),Y._data(r,"_submit_attached",!0))})},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&Y.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){if(Y.nodeName(this,"form"))return!1;Y.event.remove(this,"._submit")}}),Y.support.changeBubbles||(Y.event.special.change={setup:function(){if(kt.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")Y.event.add(this,"propertychange._change",function(e){e.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),Y.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),Y.event.simulate("change",this,e,!0)});return!1}Y.event.add(this,"beforeactivate._change",function(e){var t=e.target;kt.test(t.nodeName)&&!Y._data(t,"_change_attached")&&(Y.event.add(t,"change._change",function(e){this.parentNode&&!e.isSimulated&&!e.isTrigger&&Y.event.simulate("change",this.parentNode,e,!0)}),Y._data(t,"_change_attached",!0))})},handle:function(e){var t=e.target;if(this!==t||e.isSimulated||e.isTrigger||t.type!=="radio"&&t.type!=="checkbox")return e.handleObj.handler.apply(this,arguments)},teardown:function(){return Y.event.remove(this,"._change"),!kt.test(this.nodeName)}}),Y.support.focusinBubbles||Y.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){Y.event.simulate(t,e.target,Y.event.fix(e),!0)};Y.event.special[t]={setup:function(){n++===0&&R.addEventListener(e,r,!0)},teardown:function(){--n===0&&R.removeEventListener(e,r,!0)}}}),Y.fn.extend({on:function(e,n,r,i,o){var u,a;if(typeof e=="object"){typeof n!="string"&&(r=r||n,n=t);for(a in e)this.on(a,n,r,e[a],o);return this}r==null&&i==null?(i=n,r=n=t):i==null&&(typeof n=="string"?(i=r,r=t):(i=r,r=n,n=t));if(i===!1)i=s;else if(!i)return this;return o===1&&(u=i,i=function(e){return Y().off(e),u.apply(this,arguments)},i.guid=u.guid||(u.guid=Y.guid++)),this.each(function(){Y.event.add(this,e,i,r,n)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,n,r){var i,o;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,Y(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if(typeof e=="object"){for(o in e)this.off(o,n,e[o]);return this}if(n===!1||typeof n=="function")r=n,n=t;return r===!1&&(r=s),this.each(function(){Y.event.remove(this,e,r,n)})},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},live:function(e,t,n){return Y(this.context).on(e,this.selector,t,n),this},die:function(e,t){return Y(this.context).off(e,this.selector||"**",t),this},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return arguments.length==1?this.off(e,"**"):this.off(t,e||"**",n)},trigger:function(e,t){return this.each(function(){Y.event.trigger(e,t,this)})},triggerHandler:function(e,t){if(this[0])return Y.event.trigger(e,t,this[0],!0)},toggle:function(e){var t=arguments,n=e.guid||Y.guid++,r=0,i=function(n){var i=(Y._data(this,"lastToggle"+e.guid)||0)%r;return Y._data(this,"lastToggle"+e.guid,i+1),n.preventDefault(),t[i].apply(this,arguments)||!1};i.guid=n;while(r<t.length)t[r++].guid=n;return this.click(i)},hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}}),Y.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(e,t){Y.fn[t]=function(e,n){return n==null&&(n=e,e=null),arguments.length>0?this.on(t,null,e,n):this.trigger(t)},Ot.test(t)&&(Y.event.fixHooks[t]=Y.event.keyHooks),Mt.test(t)&&(Y.event.fixHooks[t]=Y.event.mouseHooks)}),function(e,t){function n(e,t,n,r){n=n||[],t=t||L;var i,s,o,u,a=t.nodeType;if(a!==1&&a!==9)return[];if(!e||typeof e!="string")return n;o=w(t);if(!o&&!r)if(i=K.exec(e))if(u=i[1]){if(a===9){s=t.getElementById(u);if(!s||!s.parentNode)return n;if(s.id===u)return n.push(s),n}else if(t.ownerDocument&&(s=t.ownerDocument.getElementById(u))&&E(t,s)&&s.id===u)return n.push(s),n}else{if(i[2])return _.apply(n,M.call(t.getElementsByTagName(e),0)),n;if((u=i[3])&&at&&t.getElementsByClassName)return _.apply(n,M.call(t.getElementsByClassName(u),0)),n}return d(e,t,n,r,o)}function r(e){return function(t){var n=t.nodeName.toLowerCase();return n==="input"&&t.type===e}}function i(e){return function(t){var n=t.nodeName.toLowerCase();return(n==="input"||n==="button")&&t.type===e}}function s(e,t,n){if(e===t)return n;var r=e.nextSibling;while(r){if(r===t)return-1;r=r.nextSibling}return 1}function o(e,t,r,i){var s,o,u,a,f,l,c,h,p,d,v=!r&&t!==L,m=(v?"<s>":"")+e.replace(X,"$1<s>"),g=B[k][m];if(g)return i?0:M.call(g,0);f=e,l=[],h=0,p=y.preFilter,d=y.filter;while(f){if(!s||(o=V.exec(f)))o&&(f=f.slice(o[0].length),u.selector=c),l.push(u=[]),c="",v&&(f=" "+f);s=!1;if(o=$.exec(f))c+=o[0],f=f.slice(o[0].length),s=u.push({part:o.pop().replace(X," "),string:o[0],captures:o});for(a in d)(o=rt[a].exec(f))&&(!p[a]||(o=p[a](o,t,r)))&&(c+=o[0],f=f.slice(o[0].length),s=u.push({part:a,string:o.shift(),captures:o}));if(!s)break}return c&&(u.selector=c),i?f.length:f?n.error(e):M.call(B(m,l),0)}function u(e,t,n,r){var i=t.dir,s=O++;return e||(e=function(e){return e===n}),t.first?function(t){while(t=t[i])if(t.nodeType===1)return e(t)&&t}:r?function(t){while(t=t[i])if(t.nodeType===1&&e(t))return t}:function(t){var n,r=s+"."+v,o=r+"."+m;while(t=t[i])if(t.nodeType===1){if((n=t[k])===o)return t.sizset;if(typeof n=="string"&&n.indexOf(r)===0){if(t.sizset)return t}else{t[k]=o;if(e(t))return t.sizset=!0,t;t.sizset=!1}}}}function a(e,t){return e?function(n){var r=t(n);return r&&e(r===!0?n:r)}:t}function f(e,t,n){var r,i,s=0;for(;r=e[s];s++)y.relative[r.part]?i=u(i,y.relative[r.part],t,n):i=a(i,y.filter[r.part].apply(null,r.captures.concat(t,n)));return i}function l(e){return function(t){var n,r=0;for(;n=e[r];r++)if(n(t))return!0;return!1}}function c(e,t,r,i){var s=0,o=t.length;for(;s<o;s++)n(e,t[s],r,i)}function h(e,t,r,i,s,o){var u,a=y.setFilters[t.toLowerCase()];return a||n.error(t),(e||!(u=s))&&c(e||"*",i,u=[],s),u.length>0?a(u,r,o):[]}function p(e,r,i,s){var o,u,a,f,l,p,d,v,m,g,y,b,w,E=0,S=e.length,x=rt.POS,T=new RegExp("^"+x.source+"(?!"+F+")","i"),N=function(){var e=1,n=arguments.length-2;for(;e<n;e++)arguments[e]===t&&(m[e]=t)};for(;E<S;E++){o=e[E],u="",v=s;for(a=0,f=o.length;a<f;a++){l=o[a],p=l.string;if(l.part==="PSEUDO"){x.exec(""),d=0;while(m=x.exec(p)){g=!0,y=x.lastIndex=m.index+m[0].length;if(y>d){u+=p.slice(d,m.index),d=y,b=[r],$.test(u)&&(v&&(b=v),v=s);if(w=Z.test(u))u=u.slice(0,-5).replace($,"$&*"),d++;m.length>1&&m[0].replace(T,N),v=h(u,m[1],m[2],b,v,w)}u=""}}g||(u+=p),g=!1}u?$.test(u)?c(u,v||[r],i,s):n(u,r,i,s?s.concat(v):v):_.apply(i,v)}return S===1?i:n.uniqueSort(i)}function d(e,t,n,r,i){e=e.replace(X,"$1");var s,u,a,f,l,c,h,d,g,b,w=o(e,t,i),E=t.nodeType;if(rt.POS.test(e))return p(w,t,n,r);if(r)s=M.call(r,0);else if(w.length===1){if((c=M.call(w[0],0)).length>2&&(h=c[0]).part==="ID"&&E===9&&!i&&y.relative[c[1].part]){t=y.find.ID(h.captures[0].replace(nt,""),t,i)[0];if(!t)return n;e=e.slice(c.shift().string.length)}g=(w=G.exec(c[0].string))&&!w.index&&t.parentNode||t,d="";for(l=c.length-1;l>=0;l--){h=c[l],b=h.part,d=h.string+d;if(y.relative[b])break;if(y.order.test(b)){s=y.find[b](h.captures[0].replace(nt,""),g,i);if(s==null)continue;e=e.slice(0,e.length-d.length)+d.replace(rt[b],""),e||_.apply(n,M.call(s,0));break}}}if(e){u=S(e,t,i),v=u.dirruns++,s==null&&(s=y.find.TAG("*",G.test(e)&&t.parentNode||t));for(l=0;f=s[l];l++)m=u.runs++,u(f)&&n.push(f)}return n}var v,m,g,y,b,w,E,S,x,T,N=!0,C="undefined",k=("sizcache"+Math.random()).replace(".",""),L=e.document,A=L.documentElement,O=0,M=[].slice,_=[].push,D=function(e,t){return e[k]=t||!0,e},P=function(){var e={},t=[];return D(function(n,r){return t.push(n)>y.cacheLength&&delete e[t.shift()],e[n]=r},e)},H=P(),B=P(),j=P(),F="[\\x20\\t\\r\\n\\f]",I="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",q=I.replace("w","w#"),R="([*^$|!~]?=)",U="\\["+F+"*("+I+")"+F+"*(?:"+R+F+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+q+")|)|)"+F+"*\\]",z=":("+I+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:"+U+")|[^:]|\\\\.)*|.*))\\)|)",W=":(nth|eq|gt|lt|first|last|even|odd)(?:\\(((?:-\\d)?\\d*)\\)|)(?=[^-]|$)",X=new RegExp("^"+F+"+|((?:^|[^\\\\])(?:\\\\.)*)"+F+"+$","g"),V=new RegExp("^"+F+"*,"+F+"*"),$=new RegExp("^"+F+"*([\\x20\\t\\r\\n\\f>+~])"+F+"*"),J=new RegExp(z),K=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,Q=/^:not/,G=/[\x20\t\r\n\f]*[+~]/,Z=/:not\($/,et=/h\d/i,tt=/input|select|textarea|button/i,nt=/\\(?!\\)/g,rt={ID:new RegExp("^#("+I+")"),CLASS:new RegExp("^\\.("+I+")"),NAME:new RegExp("^\\[name=['\"]?("+I+")['\"]?\\]"),TAG:new RegExp("^("+I.replace("w","w*")+")"),ATTR:new RegExp("^"+U),PSEUDO:new RegExp("^"+z),CHILD:new RegExp("^:(only|nth|last|first)-child(?:\\("+F+"*(even|odd|(([+-]|)(\\d*)n|)"+F+"*(?:([+-]|)"+F+"*(\\d+)|))"+F+"*\\)|)","i"),POS:new RegExp(W,"ig"),needsContext:new RegExp("^"+F+"*[>+~]|"+W,"i")},it=function(e){var t=L.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}},st=it(function(e){return e.appendChild(L.createComment("")),!e.getElementsByTagName("*").length}),ot=it(function(e){return e.innerHTML="<a href='#'></a>",e.firstChild&&typeof e.firstChild.getAttribute!==C&&e.firstChild.getAttribute("href")==="#"}),ut=it(function(e){e.innerHTML="<select></select>";var t=typeof e.lastChild.getAttribute("multiple");return t!=="boolean"&&t!=="string"}),at=it(function(e){return e.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",!e.getElementsByClassName||!e.getElementsByClassName("e").length?!1:(e.lastChild.className="e",e.getElementsByClassName("e").length===2)}),ft=it(function(e){e.id=k+0,e.innerHTML="<a name='"+k+"'></a><div name='"+k+"'></div>",A.insertBefore(e,A.firstChild);var t=L.getElementsByName&&L.getElementsByName(k).length===2+L.getElementsByName(k+0).length;return g=!L.getElementById(k),A.removeChild(e),t});try{M.call(A.childNodes,0)[0].nodeType}catch(lt){M=function(e){var t,n=[];for(;t=this[e];e++)n.push(t);return n}}n.matches=function(e,t){return n(e,null,null,t)},n.matchesSelector=function(e,t){return n(t,null,null,[e]).length>0},b=n.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(i===1||i===9||i===11){if(typeof e.textContent=="string")return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=b(e)}else if(i===3||i===4)return e.nodeValue}else for(;t=e[r];r++)n+=b(t);return n},w=n.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?t.nodeName!=="HTML":!1},E=n.contains=A.contains?function(e,t){var n=e.nodeType===9?e.documentElement:e,r=t&&t.parentNode;return e===r||!!(r&&r.nodeType===1&&n.contains&&n.contains(r))}:A.compareDocumentPosition?function(e,t){return t&&!!(e.compareDocumentPosition(t)&16)}:function(e,t){while(t=t.parentNode)if(t===e)return!0;return!1},n.attr=function(e,t){var n,r=w(e);return r||(t=t.toLowerCase()),y.attrHandle[t]?y.attrHandle[t](e):ut||r?e.getAttribute(t):(n=e.getAttributeNode(t),n?typeof e[t]=="boolean"?e[t]?t:null:n.specified?n.value:null:null)},y=n.selectors={cacheLength:50,createPseudo:D,match:rt,order:new RegExp("ID|TAG"+(ft?"|NAME":"")+(at?"|CLASS":"")),attrHandle:ot?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},find:{ID:g?function(e,t,n){if(typeof t.getElementById!==C&&!n){var r=t.getElementById(e);return r&&r.parentNode?[r]:[]}}:function(e,n,r){if(typeof n.getElementById!==C&&!r){var i=n.getElementById(e);return i?i.id===e||typeof i.getAttributeNode!==C&&i.getAttributeNode("id").value===e?[i]:t:[]}},TAG:st?function(e,t){if(typeof t.getElementsByTagName!==C)return t.getElementsByTagName(e)}:function(e,t){var n=t.getElementsByTagName(e);if(e==="*"){var r,i=[],s=0;for(;r=n[s];s++)r.nodeType===1&&i.push(r);return i}return n},NAME:function(e,t){if(typeof t.getElementsByName!==C)return t.getElementsByName(name)},CLASS:function(e,t,n){if(typeof t.getElementsByClassName!==C&&!n)return t.getElementsByClassName(e)}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(nt,""),e[3]=(e[4]||e[5]||"").replace(nt,""),e[2]==="~="&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),e[1]==="nth"?(e[2]||n.error(e[0]),e[3]=+(e[3]?e[4]+(e[5]||1):2*(e[2]==="even"||e[2]==="odd")),e[4]=+(e[6]+e[7]||e[2]==="odd")):e[2]&&n.error(e[0]),e},PSEUDO:function(e,t,n){var r,i;if(rt.CHILD.test(e[0]))return null;if(e[3])e[2]=e[3];else if(r=e[4])J.test(r)&&(i=o(r,t,n,!0))&&(i=r.indexOf(")",r.length-i)-r.length)&&(r=r.slice(0,i),e[0]=e[0].slice(0,i)),e[2]=r;return e.slice(0,3)}},filter:{ID:g?function(e){return e=e.replace(nt,""),function(t){return t.getAttribute("id")===e}}:function(e){return e=e.replace(nt,""),function(t){var n=typeof t.getAttributeNode!==C&&t.getAttributeNode("id");return n&&n.value===e}},TAG:function(e){return e==="*"?function(){return!0}:(e=e.replace(nt,"").toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=H[k][e];return t||(t=H(e,new RegExp("(^|"+F+")"+e+"("+F+"|$)"))),function(e){return t.test(e.className||typeof e.getAttribute!==C&&e.getAttribute("class")||"")}},ATTR:function(e,t,r){return t?function(i){var s=n.attr(i,e),o=s+"";if(s==null)return t==="!=";switch(t){case"=":return o===r;case"!=":return o!==r;case"^=":return r&&o.indexOf(r)===0;case"*=":return r&&o.indexOf(r)>-1;case"$=":return r&&o.substr(o.length-r.length)===r;case"~=":return(" "+o+" ").indexOf(r)>-1;case"|=":return o===r||o.substr(0,r.length+1)===r+"-"}}:function(t){return n.attr(t,e)!=null}},CHILD:function(e,t,n,r){if(e==="nth"){var i=O++;return function(e){var t,s,o=0,u=e;if(n===1&&r===0)return!0;t=e.parentNode;if(t&&(t[k]!==i||!e.sizset)){for(u=t.firstChild;u;u=u.nextSibling)if(u.nodeType===1){u.sizset=++o;if(u===e)break}t[k]=i}return s=e.sizset-r,n===0?s===0:s%n===0&&s/n>=0}}return function(t){var n=t;switch(e){case"only":case"first":while(n=n.previousSibling)if(n.nodeType===1)return!1;if(e==="first")return!0;n=t;case"last":while(n=n.nextSibling)if(n.nodeType===1)return!1;return!0}}},PSEUDO:function(e,t,r,i){var s,o=y.pseudos[e]||y.pseudos[e.toLowerCase()];return o||n.error("unsupported pseudo: "+e),o[k]?o(t,r,i):o.length>1?(s=[e,e,"",t],function(e){return o(e,0,s)}):o}},pseudos:{not:D(function(e,t,n){var r=S(e.replace(X,"$1"),t,n);return function(e){return!r(e)}}),enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&!!e.checked||t==="option"&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},parent:function(e){return!y.pseudos.empty(e)},empty:function(e){var t;e=e.firstChild;while(e){if(e.nodeName>"@"||(t=e.nodeType)===3||t===4)return!1;e=e.nextSibling}return!0},contains:D(function(e){return function(t){return(t.textContent||t.innerText||b(t)).indexOf(e)>-1}}),has:D(function(e){return function(t){return n(e,t).length>0}}),header:function(e){return et.test(e.nodeName)},text:function(e){var t,n;return e.nodeName.toLowerCase()==="input"&&(t=e.type)==="text"&&((n=e.getAttribute("type"))==null||n.toLowerCase()===t)},radio:r("radio"),checkbox:r("checkbox"),file:r("file"),password:r("password"),image:r("image"),submit:i("submit"),reset:i("reset"),button:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&e.type==="button"||t==="button"},input:function(e){return tt.test(e.nodeName)},focus:function(e){var t=e.ownerDocument;return e===t.activeElement&&(!t.hasFocus||t.hasFocus())&&(!!e.type||!!e.href)},active:function(e){return e===e.ownerDocument.activeElement}},setFilters:{first:function(e,t,n){return n?e.slice(1):[e[0]]},last:function(e,t,n){var r=e.pop();return n?e:[r]},even:function(e,t,n){var r=[],i=n?1:0,s=e.length;for(;i<s;i+=2)r.push(e[i]);return r},odd:function(e,t,n){var r=[],i=n?0:1,s=e.length;for(;i<s;i+=2)r.push(e[i]);return r},lt:function(e,t,n){return n?e.slice(+t):e.slice(0,+t)},gt:function(e,t,n){return n?e.slice(0,+t+1):e.slice(+t+1)},eq:function(e,t,n){var r=e.splice(+t,1);return n?e:r}}},x=A.compareDocumentPosition?function(e,t){return e===t?(T=!0,0):(!e.compareDocumentPosition||!t.compareDocumentPosition?e.compareDocumentPosition:e.compareDocumentPosition(t)&4)?-1:1}:function(e,t){if(e===t)return T=!0,0;if(e.sourceIndex&&t.sourceIndex)return e.sourceIndex-t.sourceIndex;var n,r,i=[],o=[],u=e.parentNode,a=t.parentNode,f=u;if(u===a)return s(e,t);if(!u)return-1;if(!a)return 1;while(f)i.unshift(f),f=f.parentNode;f=a;while(f)o.unshift(f),f=f.parentNode;n=i.length,r=o.length;for(var l=0;l<n&&l<r;l++)if(i[l]!==o[l])return s(i[l],o[l]);return l===n?s(e,o[l],-1):s(i[l],t,1)},[0,0].sort(x),N=!T,n.uniqueSort=function(e){var t,n=1;T=N,e.sort(x);if(T)for(;t=e[n];n++)t===e[n-1]&&e.splice(n--,1);return e},n.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},S=n.compile=function(e,t,n){var r,i,s,u=j[k][e];if(u&&u.context===t)return u;r=o(e,t,n);for(i=0,s=r.length;i<s;i++)r[i]=f(r[i],t,n);return u=j(e,l(r)),u.context=t,u.runs=u.dirruns=0,u},L.querySelectorAll&&function(){var e,t=d,r=/'|\\/g,i=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,s=[],u=[":active"],a=A.matchesSelector||A.mozMatchesSelector||A.webkitMatchesSelector||A.oMatchesSelector||A.msMatchesSelector;it(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||s.push("\\["+F+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||s.push(":checked")}),it(function(e){e.innerHTML="<p test=''></p>",e.querySelectorAll("[test^='']").length&&s.push("[*^$]="+F+"*(?:\"\"|'')"),e.innerHTML="<input type='hidden'/>",e.querySelectorAll(":enabled").length||s.push(":enabled",":disabled")}),s=s.length&&new RegExp(s.join("|")),d=function(e,n,i,u,a){if(!u&&!a&&(!s||!s.test(e)))if(n.nodeType===9)try{return _.apply(i,M.call(n.querySelectorAll(e),0)),i}catch(f){}else if(n.nodeType===1&&n.nodeName.toLowerCase()!=="object"){var l,c,h,p=n.getAttribute("id"),d=p||k,v=G.test(e)&&n.parentNode||n;p?d=d.replace(r,"\\$&"):n.setAttribute("id",d),l=o(e,n,a),d="[id='"+d+"']";for(c=0,h=l.length;c<h;c++)l[c]=d+l[c].selector;try{return _.apply(i,M.call(v.querySelectorAll(l.join(",")),0)),i}catch(f){}finally{p||n.removeAttribute("id")}}return t(e,n,i,u,a)},a&&(it(function(t){e=a.call(t,"div");try{a.call(t,"[test!='']:sizzle"),u.push(rt.PSEUDO.source,rt.POS.source,"!=")}catch(n){}}),u=new RegExp(u.join("|")),n.matchesSelector=function(t,r){r=r.replace(i,"='$1']");if(!w(t)&&!u.test(r)&&(!s||!s.test(r)))try{var o=a.call(t,r);if(o||e||t.document&&t.document.nodeType!==11)return o}catch(f){}return n(r,null,null,[t]).length>0})}(),y.setFilters.nth=y.setFilters.eq,y.filters=y.pseudos,n.attr=Y.attr,Y.find=n,Y.expr=n.selectors,Y.expr[":"]=Y.expr.pseudos,Y.unique=n.uniqueSort,Y.text=n.getText,Y.isXMLDoc=n.isXML,Y.contains=n.contains}(e);var Pt=/Until$/,Ht=/^(?:parents|prev(?:Until|All))/,Bt=/^.[^:#\[\.,]*$/,jt=Y.expr.match.needsContext,Ft={children:!0,contents:!0,next:!0,prev:!0};Y.fn.extend({find:function(e){var t,n,r,i,s,o,u=this;if(typeof e!="string")return Y(e).filter(function(){for(t=0,n=u.length;t<n;t++)if(Y.contains(u[t],this))return!0});o=this.pushStack("","find",e);for(t=0,n=this.length;t<n;t++){r=o.length,Y.find(e,this[t],o);if(t>0)for(i=r;i<o.length;i++)for(s=0;s<r;s++)if(o[s]===o[i]){o.splice(i--,1);break}}return o},has:function(e){var t,n=Y(e,this),r=n.length;return this.filter(function(){for(t=0;t<r;t++)if(Y.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(f(this,e,!1),"not",e)},filter:function(e){return this.pushStack(f(this,e,!0),"filter",e)},is:function(e){return!!e&&(typeof e=="string"?jt.test(e)?Y(e,this.context).index(this[0])>=0:Y.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,s=[],o=jt.test(e)||typeof e!="string"?Y(e,t||this.context):0;for(;r<i;r++){n=this[r];while(n&&n.ownerDocument&&n!==t&&n.nodeType!==11){if(o?o.index(n)>-1:Y.find.matchesSelector(n,e)){s.push(n);break}n=n.parentNode}}return s=s.length>1?Y.unique(s):s,this.pushStack(s,"closest",e)},index:function(e){return e?typeof e=="string"?Y.inArray(this[0],Y(e)):Y.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(e,t){var n=typeof e=="string"?Y(e,t):Y.makeArray(e&&e.nodeType?[e]:e),r=Y.merge(this.get(),n);return this.pushStack(u(n[0])||u(r[0])?r:Y.unique(r))},addBack:function(e){return this.add(e==null?this.prevObject:this.prevObject.filter(e))}}),Y.fn.andSelf=Y.fn.addBack,Y.each({parent:function(e){var t=e.parentNode;return t&&t.nodeType!==11?t:null},parents:function(e){return Y.dir(e,"parentNode")},parentsUntil:function(e,t,n){return Y.dir(e,"parentNode",n)},next:function(e){return a(e,"nextSibling")},prev:function(e){return a(e,"previousSibling")},nextAll:function(e){return Y.dir(e,"nextSibling")},prevAll:function(e){return Y.dir(e,"previousSibling")},nextUntil:function(e,t,n){return Y.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return Y.dir(e,"previousSibling",n)},siblings:function(e){return Y.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return Y.sibling(e.firstChild)},contents:function(e){return Y.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:Y.merge([],e.childNodes)}},function(e,t){Y.fn[e]=function(n,r){var i=Y.map(this,t,n);return Pt.test(e)||(r=n),r&&typeof r=="string"&&(i=Y.filter(r,i)),i=this.length>1&&!Ft[e]?Y.unique(i):i,this.length>1&&Ht.test(e)&&(i=i.reverse()),this.pushStack(i,e,$.call(arguments).join(","))}}),Y.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),t.length===1?Y.find.matchesSelector(t[0],e)?[t[0]]:[]:Y.find.matches(e,t)},dir:function(e,n,r){var i=[],s=e[n];while(s&&s.nodeType!==9&&(r===t||s.nodeType!==1||!Y(s).is(r)))s.nodeType===1&&i.push(s),s=s[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)e.nodeType===1&&e!==t&&n.push(e);return n}});var It="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",qt=/ jQuery\d+="(?:null|\d+)"/g,Rt=/^\s+/,Ut=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,zt=/<([\w:]+)/,Wt=/<tbody/i,Xt=/<|&#?\w+;/,Vt=/<(?:script|style|link)/i,$t=/<(?:script|object|embed|option|style)/i,Jt=new RegExp("<(?:"+It+")[\\s/>]","i"),Kt=/^(?:checkbox|radio)$/,Qt=/checked\s*(?:[^=]|=\s*.checked.)/i,Gt=/\/(java|ecma)script/i,Yt=/^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,Zt={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,"",""]},en=l(R),tn=en.appendChild(R.createElement("div"));Zt.optgroup=Zt.option,Zt.tbody=Zt.tfoot=Zt.colgroup=Zt.caption=Zt.thead,Zt.th=Zt.td,Y.support.htmlSerialize||(Zt._default=[1,"X<div>","</div>"]),Y.fn.extend({text:function(e){return Y.access(this,function(e){return e===t?Y.text(this):this.empty().append((this[0]&&this[0].ownerDocument||R).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(Y.isFunction(e))return this.each(function(t){Y(this).wrapAll(e.call(this,t))});if(this[0]){var t=Y(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&e.firstChild.nodeType===1)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return Y.isFunction(e)?this.each(function(t){Y(this).wrapInner(e.call(this,t))}):this.each(function(){var t=Y(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=Y.isFunction(e);return this.each(function(n){Y(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){Y.nodeName(this,"body")||Y(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(e,this.firstChild)})},before:function(){if(!u(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this)});if(arguments.length){var e=Y.clean(arguments);return this.pushStack(Y.merge(e,this),"before",this.selector)}},after:function(){if(!u(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this.nextSibling)});if(arguments.length){var e=Y.clean(arguments);return this.pushStack(Y.merge(this,e),"after",this.selector)}},remove:function(e,t){var n,r=0;for(;(n=this[r])!=null;r++)if(!e||Y.filter(e,[n]).length)!t&&n.nodeType===1&&(Y.cleanData(n.getElementsByTagName("*")),Y.cleanData([n])),n.parentNode&&n.parentNode.removeChild(n);return this},empty:function(){var e,t=0;for(;(e=this[t])!=null;t++){e.nodeType===1&&Y.cleanData(e.getElementsByTagName("*"));while(e.firstChild)e.removeChild(e.firstChild)}return this},clone:function(e,t){return e=e==null?!1:e,t=t==null?e:t,this.map(function(){return Y.clone(this,e,t)})},html:function(e){return Y.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return n.nodeType===1?n.innerHTML.replace(qt,""):t;if(typeof e=="string"&&!Vt.test(e)&&(Y.support.htmlSerialize||!Jt.test(e))&&(Y.support.leadingWhitespace||!Rt.test(e))&&!Zt[(zt.exec(e)||["",""])[1].toLowerCase()]){e=e.replace(Ut,"<$1></$2>");try{for(;r<i;r++)n=this[r]||{},n.nodeType===1&&(Y.cleanData(n.getElementsByTagName("*")),n.innerHTML=e);n=0}catch(s){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(e){return u(this[0])?this.length?this.pushStack(Y(Y.isFunction(e)?e():e),"replaceWith",e):this:Y.isFunction(e)?this.each(function(t){var n=Y(this),r=n.html();n.replaceWith(e.call(this,t,r))}):(typeof e!="string"&&(e=Y(e).detach()),this.each(function(){var t=this.nextSibling,n=this.parentNode;Y(this).remove(),t?Y(t).before(e):Y(n).append(e)}))},detach:function(e){return this.remove(e,!0)},domManip:function(e,n,r){e=[].concat.apply([],e);var i,s,o,u,a=0,f=e[0],l=[],h=this.length;if(!Y.support.checkClone&&h>1&&typeof f=="string"&&Qt.test(f))return this.each(function(){Y(this).domManip(e,n,r)});if(Y.isFunction(f))return this.each(function(i){var s=Y(this);e[0]=f.call(this,i,n?s.html():t),s.domManip(e,n,r)});if(this[0]){i=Y.buildFragment(e,this,l),o=i.fragment,s=o.firstChild,o.childNodes.length===1&&(o=s);if(s){n=n&&Y.nodeName(s,"tr");for(u=i.cacheable||h-1;a<h;a++)r.call(n&&Y.nodeName(this[a],"table")?c(this[a],"tbody"):this[a],a===u?o:Y.clone(o,!0,!0))}o=s=null,l.length&&Y.each(l,function(e,t){t.src?Y.ajax?Y.ajax({url:t.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):Y.error("no ajax"):Y.globalEval((t.text||t.textContent||t.innerHTML||"").replace(Yt,"")),t.parentNode&&t.parentNode.removeChild(t)})}return this}}),Y.buildFragment=function(e,n,r){var i,s,o,u=e[0];return n=n||R,n=!n.nodeType&&n[0]||n,n=n.ownerDocument||n,e.length===1&&typeof u=="string"&&u.length<512&&n===R&&u.charAt(0)==="<"&&!$t.test(u)&&(Y.support.checkClone||!Qt.test(u))&&(Y.support.html5Clone||!Jt.test(u))&&(s=!0,i=Y.fragments[u],o=i!==t),i||(i=n.createDocumentFragment(),Y.clean(e,n,i,r),s&&(Y.fragments[u]=o&&i)),{fragment:i,cacheable:s}},Y.fragments={},Y.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){Y.fn[e]=function(n){var r,i=0,s=[],o=Y(n),u=o.length,a=this.length===1&&this[0].parentNode;if((a==null||a&&a.nodeType===11&&a.childNodes.length===1)&&u===1)return o[t](this[0]),this;for(;i<u;i++)r=(i>0?this.clone(!0):this).get(),Y(o[i])[t](r),s=s.concat(r);return this.pushStack(s,e,o.selector)}}),Y.extend({clone:function(e,t,n){var r,i,s,o;Y.support.html5Clone||Y.isXMLDoc(e)||!Jt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(tn.innerHTML=e.outerHTML,tn.removeChild(o=tn.firstChild));if((!Y.support.noCloneEvent||!Y.support.noCloneChecked)&&(e.nodeType===1||e.nodeType===11)&&!Y.isXMLDoc(e)){p(e,o),r=d(e),i=d(o);for(s=0;r[s];++s)i[s]&&p(r[s],i[s])}if(t){h(e,o);if(n){r=d(e),i=d(o);for(s=0;r[s];++s)h(r[s],i[s])}}return r=i=null,o},clean:function(e,t,n,r){var i,s,o,u,a,f,c,h,p,d,m,g,y=t===R&&en,b=[];if(!t||typeof t.createDocumentFragment=="undefined")t=R;for(i=0;(o=e[i])!=null;i++){typeof o=="number"&&(o+="");if(!o)continue;if(typeof o=="string")if(!Xt.test(o))o=t.createTextNode(o);else{y=y||l(t),c=t.createElement("div"),y.appendChild(c),o=o.replace(Ut,"<$1></$2>"),u=(zt.exec(o)||["",""])[1].toLowerCase(),a=Zt[u]||Zt._default,f=a[0],c.innerHTML=a[1]+o+a[2];while(f--)c=c.lastChild;if(!Y.support.tbody){h=Wt.test(o),p=u==="table"&&!h?c.firstChild&&c.firstChild.childNodes:a[1]==="<table>"&&!h?c.childNodes:[];for(s=p.length-1;s>=0;--s)Y.nodeName(p[s],"tbody")&&!p[s].childNodes.length&&p[s].parentNode.removeChild(p[s])}!Y.support.leadingWhitespace&&Rt.test(o)&&c.insertBefore(t.createTextNode(Rt.exec(o)[0]),c.firstChild),o=c.childNodes,c.parentNode.removeChild(c)}o.nodeType?b.push(o):Y.merge(b,o)}c&&(o=c=y=null);if(!Y.support.appendChecked)for(i=0;(o=b[i])!=null;i++)Y.nodeName(o,"input")?v(o):typeof o.getElementsByTagName!="undefined"&&Y.grep(o.getElementsByTagName("input"),v);if(n){m=function(e){if(!e.type||Gt.test(e.type))return r?r.push(e.parentNode?e.parentNode.removeChild(e):e):n.appendChild(e)};for(i=0;(o=b[i])!=null;i++)if(!Y.nodeName(o,"script")||!m(o))n.appendChild(o),typeof o.getElementsByTagName!="undefined"&&(g=Y.grep(Y.merge([],o.getElementsByTagName("script")),m),b.splice.apply(b,[i+1,0].concat(g)),i+=g.length)}return b},cleanData:function(e,t){var n,r,i,s,o=0,u=Y.expando,a=Y.cache,f=Y.support.deleteExpando,l=Y.event.special;for(;(i=e[o])!=null;o++)if(t||Y.acceptData(i)){r=i[u],n=r&&a[r];if(n){if(n.events)for(s in n.events)l[s]?Y.event.remove(i,s):Y.removeEvent(i,s,n.handle);a[r]&&(delete a[r],f?delete i[u]:i.removeAttribute?i.removeAttribute(u):i[u]=null,Y.deletedIds.push(r))}}}}),function(){var e,t;Y.uaMatch=function(e){e=e.toLowerCase();var t=/(chrome)[ \/]([\w.]+)/.exec(e)||/(webkit)[ \/]([\w.]+)/.exec(e)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(e)||/(msie) ([\w.]+)/.exec(e)||e.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(e)||[];return{browser:t[1]||"",version:t[2]||"0"}},e=Y.uaMatch(z.userAgent),t={},e.browser&&(t[e.browser]=!0,t.version=e.version),t.chrome?t.webkit=!0:t.webkit&&(t.safari=!0),Y.browser=t,Y.sub=function(){function e(t,n){return new e.fn.init(t,n)}Y.extend(!0,e,this),e.superclass=this,e.fn=e.prototype=this(),e.fn.constructor=e,e.sub=this.sub,e.fn.init=function n(n,r){return r&&r instanceof Y&&!(r instanceof e)&&(r=e(r)),Y.fn.init.call(this,n,r,t)},e.fn.init.prototype=e.fn;var t=e(R);return e}}();var nn,rn,sn,on=/alpha\([^)]*\)/i,un=/opacity=([^)]*)/,an=/^(top|right|bottom|left)$/,fn=/^(none|table(?!-c[ea]).+)/,ln=/^margin/,cn=new RegExp("^("+Z+")(.*)$","i"),hn=new RegExp("^("+Z+")(?!px)[a-z%]+$","i"),pn=new RegExp("^([-+])=("+Z+")","i"),dn={},vn={position:"absolute",visibility:"hidden",display:"block"},mn={letterSpacing:0,fontWeight:400},gn=["Top","Right","Bottom","Left"],yn=["Webkit","O","Moz","ms"],bn=Y.fn.toggle;Y.fn.extend({css:function(e,n){return Y.access(this,function(e,n,r){return r!==t?Y.style(e,n,r):Y.css(e,n)},e,n,arguments.length>1)},show:function(){return y(this,!0)},hide:function(){return y(this)},toggle:function(e,t){var n=typeof e=="boolean";return Y.isFunction(e)&&Y.isFunction(t)?bn.apply(this,arguments):this.each(function(){(n?e:g(this))?Y(this).show():Y(this).hide()})}}),Y.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=nn(e,"opacity");return n===""?"1":n}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":Y.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(!e||e.nodeType===3||e.nodeType===8||!e.style)return;var s,o,u,a=Y.camelCase(n),f=e.style;n=Y.cssProps[a]||(Y.cssProps[a]=m(f,a)),u=Y.cssHooks[n]||Y.cssHooks[a];if(r===t)return u&&"get"in u&&(s=u.get(e,!1,i))!==t?s:f[n];o=typeof r,o==="string"&&(s=pn.exec(r))&&(r=(s[1]+1)*s[2]+parseFloat(Y.css(e,n)),o="number");if(r==null||o==="number"&&isNaN(r))return;o==="number"&&!Y.cssNumber[a]&&(r+="px");if(!u||!("set"in u)||(r=u.set(e,r,i))!==t)try{f[n]=r}catch(l){}},css:function(e,n,r,i){var s,o,u,a=Y.camelCase(n);return n=Y.cssProps[a]||(Y.cssProps[a]=m(e.style,a)),u=Y.cssHooks[n]||Y.cssHooks[a],u&&"get"in u&&(s=u.get(e,!0,i)),s===t&&(s=nn(e,n)),s==="normal"&&n in mn&&(s=mn[n]),r||i!==t?(o=parseFloat(s),r||Y.isNumeric(o)?o||0:s):s},swap:function(e,t,n){var r,i,s={};for(i in t)s[i]=e.style[i],e.style[i]=t[i];r=n.call(e);for(i in t)e.style[i]=s[i];return r}}),e.getComputedStyle?nn=function(t,n){var r,i,s,o,u=e.getComputedStyle(t,null),a=t.style;return u&&(r=u[n],r===""&&!Y.contains(t.ownerDocument,t)&&(r=Y.style(t,n)),hn.test(r)&&ln.test(n)&&(i=a.width,s=a.minWidth,o=a.maxWidth,a.minWidth=a.maxWidth=a.width=r,r=u.width,a.width=i,a.minWidth=s,a.maxWidth=o)),r}:R.documentElement.currentStyle&&(nn=function(e,t){var n,r,i=e.currentStyle&&e.currentStyle[t],s=e.style;return i==null&&s&&s[t]&&(i=s[t]),hn.test(i)&&!an.test(t)&&(n=s.left,r=e.runtimeStyle&&e.runtimeStyle.left,r&&(e.runtimeStyle.left=e.currentStyle.left),s.left=t==="fontSize"?"1em":i,i=s.pixelLeft+"px",s.left=n,r&&(e.runtimeStyle.left=r)),i===""?"auto":i}),Y.each(["height","width"],function(e,t){Y.cssHooks[t]={get:function(e,n,r){if(n)return e.offsetWidth===0&&fn.test(nn(e,"display"))?Y.swap(e,vn,function(){return E(e,t,r)}):E(e,t,r)},set:function(e,n,r){return b(e,n,r?w(e,t,r,Y.support.boxSizing&&Y.css(e,"boxSizing")==="border-box"):0)}}}),Y.support.opacity||(Y.cssHooks.opacity={get:function(e,t){return un.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=Y.isNumeric(t)?"alpha(opacity="+t*100+")":"",s=r&&r.filter||n.filter||"";n.zoom=1;if(t>=1&&Y.trim(s.replace(on,""))===""&&n.removeAttribute){n.removeAttribute("filter");if(r&&!r.filter)return}n.filter=on.test(s)?s.replace(on,i):s+" "+i}}),Y(function(){Y.support.reliableMarginRight||(Y.cssHooks.marginRight={get:function(e,t){return Y.swap(e,{display:"inline-block"},function(){if(t)return nn(e,"marginRight")})}}),!Y.support.pixelPosition&&Y.fn.position&&Y.each(["top","left"],function(e,t){Y.cssHooks[t]={get:function(e,n){if(n){var r=nn(e,t);return hn.test(r)?Y(e).position()[t]+"px":r}}}})}),Y.expr&&Y.expr.filters&&(Y.expr.filters.hidden=function(e){return e.offsetWidth===0&&e.offsetHeight===0||!Y.support.reliableHiddenOffsets&&(e.style&&e.style.display||nn(e,"display"))==="none"},Y.expr.filters.visible=function(e){return!Y.expr.filters.hidden(e)}),Y.each({margin:"",padding:"",border:"Width"},function(e,t){Y.cssHooks[e+t]={expand:function(n){var r,i=typeof n=="string"?n.split(" "):[n],s={};for(r=0;r<4;r++)s[e+gn[r]+t]=i[r]||i[r-2]||i[0];return s}},ln.test(e)||(Y.cssHooks[e+t].set=b)});var wn=/%20/g,En=/\[\]$/,Sn=/\r?\n/g,xn=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,Tn=/^(?:select|textarea)/i;Y.fn.extend({serialize:function(){return Y.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?Y.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||Tn.test(this.nodeName)||xn.test(this.type))}).map(function(e,t){var n=Y(this).val();return n==null?null:Y.isArray(n)?Y.map(n,function(e,n){return{name:t.name,value:e.replace(Sn,"\r\n")}}):{name:t.name,value:n.replace(Sn,"\r\n")}}).get()}}),Y.param=function(e,n){var r,i=[],s=function(e,t){t=Y.isFunction(t)?t():t==null?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};n===t&&(n=Y.ajaxSettings&&Y.ajaxSettings.traditional);if(Y.isArray(e)||e.jquery&&!Y.isPlainObject(e))Y.each(e,function(){s(this.name,this.value)});else for(r in e)x(r,e[r],n,s);return i.join("&").replace(wn,"+")};var Nn,Cn,kn=/#.*$/,Ln=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,An=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,On=/^(?:GET|HEAD)$/,Mn=/^\/\//,_n=/\?/,Dn=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,Pn=/([?&])_=[^&]*/,Hn=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,Bn=Y.fn.load,jn={},Fn={},In=["*/"]+["*"];try{Nn=U.href}catch(qn){Nn=R.createElement("a"),Nn.href="",Nn=Nn.href}Cn=Hn.exec(Nn.toLowerCase())||[],Y.fn.load=function(e,n,r){if(typeof e!="string"&&Bn)return Bn.apply(this,arguments);if(!this.length)return this;var i,s,o,u=this,a=e.indexOf(" ");return a>=0&&(i=e.slice(a,e.length),e=e.slice(0,a)),Y.isFunction(n)?(r=n,n=t):n&&typeof n=="object"&&(s="POST"),Y.ajax({url:e,type:s,dataType:"html",data:n,complete:function(e,t){r&&u.each(r,o||[e.responseText,t,e])}}).done(function(e){o=arguments,u.html(i?Y("<div>").append(e.replace(Dn,"")).find(i):e)}),this},Y.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(e,t){Y.fn[t]=function(e){return this.on(t,e)}}),Y.each(["get","post"],function(e,n){Y[n]=function(e,r,i,s){return Y.isFunction(r)&&(s=s||i,i=r,r=t),Y.ajax({type:n,url:e,data:r,success:i,dataType:s})}}),Y.extend({getScript:function(e,n){return Y.get(e,t,n,"script")},getJSON:function(e,t,n){return Y.get(e,t,n,"json")},ajaxSetup:function(e,t){return t?C(e,Y.ajaxSettings):(t=e,e=Y.ajaxSettings),C(e,t),e},ajaxSettings:{url:Nn,isLocal:An.test(Cn[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":In},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":e.String,"text html":!0,"text json":Y.parseJSON,"text xml":Y.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:T(jn),ajaxTransport:T(Fn),ajax:function(e,n){function r(e,n,r,o){var f,c,y,b,E,x=n;if(w===2)return;w=2,a&&clearTimeout(a),u=t,s=o||"",S.readyState=e>0?4:0,r&&(b=k(h,S,r));if(e>=200&&e<300||e===304)h.ifModified&&(E=S.getResponseHeader("Last-Modified"),E&&(Y.lastModified[i]=E),E=S.getResponseHeader("Etag"),E&&(Y.etag[i]=E)),e===304?(x="notmodified",f=!0):(f=L(h,b),x=f.state,c=f.data,y=f.error,f=!y);else{y=x;if(!x||e)x="error",e<0&&(e=0)}S.status=e,S.statusText=""+(n||x),f?v.resolveWith(p,[c,x,S]):v.rejectWith(p,[S,x,y]),S.statusCode(g),g=t,l&&d.trigger("ajax"+(f?"Success":"Error"),[S,h,f?c:y]),m.fireWith(p,[S,x]),l&&(d.trigger("ajaxComplete",[S,h]),--Y.active||Y.event.trigger("ajaxStop"))}typeof e=="object"&&(n=e,e=t),n=n||{};var i,s,o,u,a,f,l,c,h=Y.ajaxSetup({},n),p=h.context||h,d=p!==h&&(p.nodeType||p instanceof Y)?Y(p):Y.event,v=Y.Deferred(),m=Y.Callbacks("once memory"),g=h.statusCode||{},y={},b={},w=0,E="canceled",S={readyState:0,setRequestHeader:function(e,t){if(!w){var n=e.toLowerCase();e=b[n]=b[n]||e,y[e]=t}return this},getAllResponseHeaders:function(){return w===2?s:null},getResponseHeader:function(e){var n;if(w===2){if(!o){o={};while(n=Ln.exec(s))o[n[1].toLowerCase()]=n[2]}n=o[e.toLowerCase()]}return n===t?null:n},overrideMimeType:function(e){return w||(h.mimeType=e),this},abort:function(e){return e=e||E,u&&u.abort(e),r(0,e),this}};v.promise(S),S.success=S.done,S.error=S.fail,S.complete=m.add,S.statusCode=function(e){if(e){var t;if(w<2)for(t in e)g[t]=[g[t],e[t]];else t=e[S.status],S.always(t)}return this},h.url=((e||h.url)+"").replace(kn,"").replace(Mn,Cn[1]+"//"),h.dataTypes=Y.trim(h.dataType||"*").toLowerCase().split(tt),h.crossDomain==null&&(f=Hn.exec(h.url.toLowerCase()),h.crossDomain=!(!f||f[1]==Cn[1]&&f[2]==Cn[2]&&(f[3]||(f[1]==="http:"?80:443))==(Cn[3]||(Cn[1]==="http:"?80:443)))),h.data&&h.processData&&typeof h.data!="string"&&(h.data=Y.param(h.data,h.traditional)),N(jn,h,n,S);if(w===2)return S;l=h.global,h.type=h.type.toUpperCase(),h.hasContent=!On.test(h.type),l&&Y.active++===0&&Y.event.trigger("ajaxStart");if(!h.hasContent){h.data&&(h.url+=(_n.test(h.url)?"&":"?")+h.data,delete h.data),i=h.url;if(h.cache===!1){var x=Y.now(),T=h.url.replace(Pn,"$1_="+x);h.url=T+(T===h.url?(_n.test(h.url)?"&":"?")+"_="+x:"")}}(h.data&&h.hasContent&&h.contentType!==!1||n.contentType)&&S.setRequestHeader("Content-Type",h.contentType),h.ifModified&&(i=i||h.url,Y.lastModified[i]&&S.setRequestHeader("If-Modified-Since",Y.lastModified[i]),Y.etag[i]&&S.setRequestHeader("If-None-Match",Y.etag[i])),S.setRequestHeader("Accept",h.dataTypes[0]&&h.accepts[h.dataTypes[0]]?h.accepts[h.dataTypes[0]]+(h.dataTypes[0]!=="*"?", "+In+"; q=0.01":""):h.accepts["*"]);for(c in h.headers)S.setRequestHeader(c,h.headers[c]);if(!h.beforeSend||h.beforeSend.call(p,S,h)!==!1&&w!==2){E="abort";for(c in{success:1,error:1,complete:1})S[c](h[c]);u=N(Fn,h,n,S);if(!u)r(-1,"No Transport");else{S.readyState=1,l&&d.trigger("ajaxSend",[S,h]),h.async&&h.timeout>0&&(a=setTimeout(function(){S.abort("timeout")},h.timeout));try{w=1,u.send(y,r)}catch(C){if(!(w<2))throw C;r(-1,C)}}return S}return S.abort()},active:0,lastModified:{},etag:{}});var Rn=[],Un=/\?/,zn=/(=)\?(?=&|$)|\?\?/,Wn=Y.now();Y.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Rn.pop()||Y.expando+"_"+Wn++;return this[e]=!0,e}}),Y.ajaxPrefilter("json jsonp",function(n,r,i){var s,o,u,a=n.data,f=n.url,l=n.jsonp!==!1,c=l&&zn.test(f),h=l&&!c&&typeof a=="string"&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&zn.test(a);if(n.dataTypes[0]==="jsonp"||c||h)return s=n.jsonpCallback=Y.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,o=e[s],c?n.url=f.replace(zn,"$1"+s):h?n.data=a.replace(zn,"$1"+s):l&&(n.url+=(Un.test(f)?"&":"?")+n.jsonp+"="+s),n.converters["script json"]=function(){return u||Y.error(s+" was not called"),u[0]},n.dataTypes[0]="json",e[s]=function(){u=arguments},i.always(function(){e[s]=o,n[s]&&(n.jsonpCallback=r.jsonpCallback,Rn.push(s)),u&&Y.isFunction(o)&&o(u[0]),u=o=t}),"script"}),Y.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(e){return Y.globalEval(e),e}}}),Y.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),Y.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=R.head||R.getElementsByTagName("head")[0]||R.documentElement;return{send:function(i,s){n=R.createElement("script"),n.async="async",e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,i){if(i||!n.readyState||/loaded|complete/.test(n.readyState))n.onload=n.onreadystatechange=null,r&&n.parentNode&&r.removeChild(n),n=t,i||s(200,"success")},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(0,1)}}}});var Xn,Vn=e.ActiveXObject?function(){for(var e in Xn)Xn[e](0,1)}:!1,$n=0;Y.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&A()||O()}:A,function(e){Y.extend(Y.support,{ajax:!!e,cors:!!e&&"withCredentials"in e})}(Y.ajaxSettings.xhr()),Y.support.ajax&&Y.ajaxTransport(function(n){if(!n.crossDomain||Y.support.cors){var r;return{send:function(i,s){var o,u,a=n.xhr();n.username?a.open(n.type,n.url,n.async,n.username,n.password):a.open(n.type,n.url,n.async);if(n.xhrFields)for(u in n.xhrFields)a[u]=n.xhrFields[u];n.mimeType&&a.overrideMimeType&&a.overrideMimeType(n.mimeType),!n.crossDomain&&!i["X-Requested-With"]&&(i["X-Requested-With"]="XMLHttpRequest");try{for(u in i)a.setRequestHeader(u,i[u])}catch(f){}a.send(n.hasContent&&n.data||null),r=function(e,i){var u,f,l,c,h;try{if(r&&(i||a.readyState===4)){r=t,o&&(a.onreadystatechange=Y.noop,Vn&&delete Xn[o]);if(i)a.readyState!==4&&a.abort();else{u=a.status,l=a.getAllResponseHeaders(),c={},h=a.responseXML,h&&h.documentElement&&(c.xml=h);try{c.text=a.responseText}catch(e){}try{f=a.statusText}catch(p){f=""}!u&&n.isLocal&&!n.crossDomain?u=c.text?200:404:u===1223&&(u=204)}}}catch(d){i||s(-1,d)}c&&s(u,f,c,l)},n.async?a.readyState===4?setTimeout(r,0):(o=++$n,Vn&&(Xn||(Xn={},Y(e).unload(Vn)),Xn[o]=r),a.onreadystatechange=r):r()},abort:function(){r&&r(0,1)}}}});var Jn,Kn,Qn=/^(?:toggle|show|hide)$/,Gn=new RegExp("^(?:([-+])=|)("+Z+")([a-z%]*)$","i"),Yn=/queueHooks$/,Zn=[H],er={"*":[function(e,t){var n,r,i,s=this.createTween(e,t),o=Gn.exec(t),u=s.cur(),a=+u||0,f=1;if(o){n=+o[2],r=o[3]||(Y.cssNumber[e]?"":"px");if(r!=="px"&&a){a=Y.css(s.elem,e,!0)||n||1;do i=f=f||".5",a/=f,Y.style(s.elem,e,a+r),f=s.cur()/u;while(f!==1&&f!==i)}s.unit=r,s.start=a,s.end=o[1]?a+(o[1]+1)*n:n}return s}]};Y.Animation=Y.extend(D,{tweener:function(e,t){Y.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;r<i;r++)n=e[r],er[n]=er[n]||[],er[n].unshift(t)},prefilter:function(e,t){t?Zn.unshift(e):Zn.push(e)}}),Y.Tween=B,B.prototype={constructor:B,init:function(e,t,n,r,i,s){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=s||(Y.cssNumber[n]?"":"px")},cur:function(){var e=B.propHooks[this.prop];return e&&e.get?e.get(this):B.propHooks._default.get(this)},run:function(e){var t,n=B.propHooks[this.prop];return this.options.duration?this.pos=t=Y.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):this.pos=t=e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):B.propHooks._default.set(this),this}},B.prototype.init.prototype=B.prototype,B.propHooks={_default:{get:function(e){var t;return e.elem[e.prop]==null||!!e.elem.style&&e.elem.style[e.prop]!=null?(t=Y.css(e.elem,e.prop,!1,""),!t||t==="auto"?0:t):e.elem[e.prop]},set:function(e){Y.fx.step[e.prop]?Y.fx.step[e.prop](e):e.elem.style&&(e.elem.style[Y.cssProps[e.prop]]!=null||Y.cssHooks[e.prop])?Y.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},B.propHooks.scrollTop=B.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},Y.each(["toggle","show","hide"],function(e,t){var n=Y.fn[t];Y.fn[t]=function(r,i,s){return r==null||typeof r=="boolean"||!e&&Y.isFunction(r)&&Y.isFunction(i)?n.apply(this,arguments):this.animate(j(t,!0),r,i,s)}}),Y.fn.extend({fadeTo:function(e,t,n,r){return this.filter(g).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=Y.isEmptyObject(e),s=Y.speed(t,n,r),o=function(){var t=D(this,Y.extend({},e),s);i&&t.stop(!0)};return i||s.queue===!1?this.each(o):this.queue(s.queue,o)},stop:function(e,n,r){var i=function(e){var t=e.stop;delete e.stop,t(r)};return typeof e!="string"&&(r=n,n=e,e=t),n&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,n=e!=null&&e+"queueHooks",s=Y.timers,o=Y._data(this);if(n)o[n]&&o[n].stop&&i(o[n]);else for(n in o)o[n]&&o[n].stop&&Yn.test(n)&&i(o[n]);for(n=s.length;n--;)s[n].elem===this&&(e==null||s[n].queue===e)&&(s[n].anim.stop(r),t=!1,s.splice(n,1));(t||!r)&&Y.dequeue(this,e)})}}),Y.each({slideDown:j("show"),slideUp:j("hide"),slideToggle:j("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){Y.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),Y.speed=function(e,t,n){var r=e&&typeof e=="object"?Y.extend({},e):{complete:n||!n&&t||Y.isFunction(e)&&e,duration:e,easing:n&&t||t&&!Y.isFunction(t)&&t};r.duration=Y.fx.off?0:typeof r.duration=="number"?r.duration:r.duration in Y.fx.speeds?Y.fx.speeds[r.duration]:Y.fx.speeds._default;if(r.queue==null||r.queue===!0)r.queue="fx";return r.old=r.complete,r.complete=function(){Y.isFunction(r.old)&&r.old.call(this),r.queue&&Y.dequeue(this,r.queue)},r},Y.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},Y.timers=[],Y.fx=B.prototype.init,Y.fx.tick=function(){var e,t=Y.timers,n=0;for(;n<t.length;n++)e=t[n],!e()&&t[n]===e&&t.splice(n--,1);t.length||Y.fx.stop()},Y.fx.timer=function(e){e()&&Y.timers.push(e)&&!Kn&&(Kn=setInterval(Y.fx.tick,Y.fx.interval))},Y.fx.interval=13,Y.fx.stop=function(){clearInterval(Kn),Kn=null},Y.fx.speeds={slow:600,fast:200,_default:400},Y.fx.step={},Y.expr&&Y.expr.filters&&(Y.expr.filters.animated=function(e){return Y.grep(Y.timers,function(t){return e===t.elem}).length});var tr=/^(?:body|html)$/i;Y.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){Y.offset.setOffset(this,e,t)});var n,r,i,s,o,u,a,f,l,c,h=this[0],p=h&&h.ownerDocument;if(!p)return;return(i=p.body)===h?Y.offset.bodyOffset(h):(r=p.documentElement,Y.contains(r,h)?(n=h.getBoundingClientRect(),s=F(p),o=r.clientTop||i.clientTop||0,u=r.clientLeft||i.clientLeft||0,a=s.pageYOffset||r.scrollTop,f=s.pageXOffset||r.scrollLeft,l=n.top+a-o,c=n.left+f-u,{top:l,left:c}):{top:0,left:0})},Y.offset={bodyOffset:function(e){var t=e.offsetTop,n=e.offsetLeft;return Y.support.doesNotIncludeMarginInBodyOffset&&(t+=parseFloat(Y.css(e,"marginTop"))||0,n+=parseFloat(Y.css(e,"marginLeft"))||0),{top:t,left:n}},setOffset:function(e,t,n){var r=Y.css(e,"position");r==="static"&&(e.style.position="relative");var i=Y(e),s=i.offset(),o=Y.css(e,"top"),u=Y.css(e,"left"),a=(r==="absolute"||r==="fixed")&&Y.inArray("auto",[o,u])>-1,f={},l={},c,h;a?(l=i.position(),c=l.top,h=l.left):(c=parseFloat(o)||0,h=parseFloat(u)||0),Y.isFunction(t)&&(t=t.call(e,n,s)),t.top!=null&&(f.top=t.top-s.top+c),t.left!=null&&(f.left=t.left-s.left+h),"using"in t?t.using.call(e,f):i.css(f)}},Y.fn.extend({position:function(){if(!this[0])return;var e=this[0],t=this.offsetParent(),n=this.offset(),r=tr.test(t[0].nodeName)?{top:0,left:0}:t.offset();return n.top-=parseFloat(Y.css(e,"marginTop"))||0,n.left-=parseFloat(Y.css(e,"marginLeft"))||0,r.top+=parseFloat(Y.css(t[0],"borderTopWidth"))||0,r.left+=parseFloat(Y.css(t[0],"borderLeftWidth"))||0,{top:n.top-r.top,left:n.left-r.left}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||R.body;while(e&&!tr.test(e.nodeName)&&Y.css(e,"position")==="static")e=e.offsetParent;return e||R.body})}}),Y.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);Y.fn[e]=function(i){return Y.access(this,function(e,i,s){var o=F(e);if(s===t)return o?n in o?o[n]:o.document.documentElement[i]:e[i];o?o.scrollTo(r?Y(o).scrollLeft():s,r?s:Y(o).scrollTop()):e[i]=s},e,i,arguments.length,null)}}),Y.each({Height:"height",Width:"width"},function(e,n){Y.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){Y.fn[i]=function(i,s){var o=arguments.length&&(r||typeof i!="boolean"),u=r||(i===!0||s===!0?"margin":"border");return Y.access(this,function(n,r,i){var s;return Y.isWindow(n)?n.document.documentElement["client"+e]:n.nodeType===9?(s=n.documentElement,Math.max(n.body["scroll"+e],s["scroll"+e],n.body["offset"+e],s["offset"+e],s["client"+e])):i===t?Y.css(n,r,i,u):Y.style(n,r,i,u)},n,o?i:t,o,null)}})}),e.jQuery=e.$=Y,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return Y})})(window),typeof document!="undefined"&&!("classList"in document.createElement("a"))&&function(e){var t="classList",n="prototype",r=(e.HTMLElement||e.Element)[n],i=Object,s=String[n].trim||function(){return this.replace(/^\s+|\s+$/g,"")},o=Array[n].indexOf||function(e){var t=0,n=this.length;for(;t<n;t++)if(t in this&&this[t]===e)return t;return-1},u=function(e,t){this.name=e,this.code=DOMException[e],this.message=t},a=function(e,t){if(t==="")throw new u("SYNTAX_ERR","An invalid or illegal string was specified");if(/\s/.test(t))throw new u("INVALID_CHARACTER_ERR","String contains an invalid character");return o.call(e,t)},f=function(e){var t=s.call(e.className),n=t?t.split(/\s+/):[],r=0,i=n.length;for(;r<i;r++)this.push(n[r]);this._updateClassName=function(){e.className=this.toString()}},l=f[n]=[],c=function(){return new f(this)};u[n]=Error[n],l.item=function(e){return this[e]||null},l.contains=function(e){return e+="",a(this,e)!==-1},l.add=function(e){e+="",a(this,e)===-1&&(this.push(e),this._updateClassName())},l.remove=function(e){e+="";var t=a(this,e);t!==-1&&(this.splice(t,1),this._updateClassName())},l.toggle=function(e){e+="",a(this,e)===-1?this.add(e):this.remove(e)},l.toString=function(){return this.join(" ")};if(i.defineProperty){var h={get:c,enumerable:!0,configurable:!0};try{i.defineProperty(r,t,h)}catch(p){p.number===-2146823252&&(h.enumerable=!1,i.defineProperty(r,t,h))}}else i[n].__defineGetter__&&r.__defineGetter__(t,c)}(self),define("classList",function(){});var Reveal=function(){function T(e){N();if(!v&&!d){document.body.setAttribute("class","no-transforms");return}window.addEventListener("load",Y,!1),H(i,e),U(),C()}function N(){d="WebkitPerspective"in document.body.style||"MozPerspective"in document.body.style||"msPerspective"in document.body.style||"OPerspective"in document.body.style||"perspective"in document.body.style,v="WebkitTransform"in document.body.style||"MozTransform"in document.body.style||"msTransform"in document.body.style||"OTransform"in document.body.style||"transform"in document.body.style,m=navigator.userAgent.match(/(iphone|ipod|android)/gi)}function C(){function o(){t.length&&head.js.apply(null,t),k()}var e=[],t=[];for(var n=0,r=i.dependencies.length;n<r;n++){var s=i.dependencies[n];if(!s.condition||s.condition())s.async?t.push(s.src):e.push(s.src),typeof s.callback=="function"&&head.ready(s.src.match(/([\w\d_\-]*)\.?js$|[^\\\/]*$/i)[0],s.callback)}e.length?(head.ready(o),head.js.apply(null,e)):o()}function k(){A(),L(),_(),xt(),setTimeout(function(){p.slides.classList.remove("no-transition"),s=!0,W("ready",{indexh:u,indexv:a,currentSlide:l})},1)}function L(){var e=B(document.querySelectorAll(t));e.forEach(function(e){var t=B(e.querySelectorAll("section"));t.forEach(function(e,t){t>0&&e.classList.add("future")})})}function A(){p.theme=document.querySelector("#theme"),p.wrapper=document.querySelector(".reveal"),p.slides=document.querySelector(".reveal .slides"),p.slides.classList.add("no-transition"),p.background=O(p.wrapper,"div","backgrounds",null),p.progress=O(p.wrapper,"div","progress","<span></span>"),p.progressbar=p.progress.querySelector("span"),O(p.wrapper,"aside","controls",'<div class="navigate-left"></div><div class="navigate-right"></div><div class="navigate-up"></div><div class="navigate-down"></div>'),O(p.wrapper,"div","state-background",null),O(p.wrapper,"div","pause-overlay",null),p.controls=document.querySelector(".reveal .controls"),p.controlsLeft=B(document.querySelectorAll(".navigate-left")),p.controlsRight=B(document.querySelectorAll(".navigate-right")),p.controlsUp=B(document.querySelectorAll(".navigate-up")),p.controlsDown=B(document.querySelectorAll(".navigate-down")),p.controlsPrev=B(document.querySelectorAll(".navigate-prev")),p.controlsNext=B(document.querySelectorAll(".navigate-next"))}function O(e,t,n,r){var i=e.querySelector("."+n);return i||(i=document.createElement(t),i.classList.add(n),r!==null&&(i.innerHTML=r),e.appendChild(i)),i}function M(){function e(e,t){var n={background:e.getAttribute("data-background"),backgroundSize:e.getAttribute("data-background-size"),backgroundImage:e.getAttribute("data-background-image"),backgroundColor:e.getAttribute("data-background-color"),backgroundRepeat:e.getAttribute("data-background-repeat"),backgroundPosition:e.getAttribute("data-background-position"),backgroundTransition:e.getAttribute("data-background-transition")},r=document.createElement("div");return r.className="slide-background",n.background&&(/^(http|file|\/\/)/gi.test(n.background)||/\.(png|jpg|jpeg|gif|bmp)$/gi.test(n.background)?r.style.backgroundImage="url("+n.background+")":r.style.background=n.background),n.backgroundSize&&(r.style.backgroundSize=n.backgroundSize),n.backgroundImage&&(r.style.backgroundImage='url("'+n.backgroundImage+'")'),n.backgroundColor&&(r.style.backgroundColor=n.backgroundColor),n.backgroundRepeat&&(r.style.backgroundRepeat=n.backgroundRepeat),n.backgroundPosition&&(r.style.backgroundPosition=n.backgroundPosition),n.backgroundTransition&&r.setAttribute("data-background-transition",n.backgroundTransition),t.appendChild(r),r}R()&&document.body.classList.add("print-pdf"),p.background.innerHTML="",p.background.classList.add("no-transition"),B(document.querySelectorAll(t)).forEach(function(t){var n;R()?n=e(t,t):n=e(t,p.background),B(t.querySelectorAll("section")).forEach(function(t){R()?e(t,t):e(t,n)})})}function _(e){p.wrapper.classList.remove(i.transition),typeof e=="object"&&H(i,e),d===!1&&(i.transition="linear"),p.wrapper.classList.add(i.transition),p.wrapper.setAttribute("data-transition-speed",i.transitionSpeed),p.wrapper.setAttribute("data-background-transition",i.backgroundTransition),p.controls.style.display=i.controls?"block":"none",p.progress.style.display=i.progress?"block":"none",i.rtl?p.wrapper.classList.add("rtl"):p.wrapper.classList.remove("rtl"),i.center?p.wrapper.classList.add("center"):p.wrapper.classList.remove("center"),i.mouseWheel?(document.addEventListener("DOMMouseScroll",zt,!1),document.addEventListener("mousewheel",zt,!1)):(document.removeEventListener("DOMMouseScroll",zt,!1),document.removeEventListener("mousewheel",zt,!1)),i.rollingLinks?X():V(),i.previewLinks?$():(J(),$("[data-preview-link]"));if(i.theme&&p.theme){var t=p.theme.getAttribute("href"),n=/[^\/]*?(?=\.css)/,r=t.match(n)[0];i.theme!==r&&(t=t.replace(n,i.theme),p.theme.setAttribute("href",t))}pt()}function D(){S=!0,window.addEventListener("hashchange",Gt,!1),window.addEventListener("resize",Yt,!1),i.touch&&(p.wrapper.addEventListener("touchstart",jt,!1),p.wrapper.addEventListener("touchmove",Ft,!1),p.wrapper.addEventListener("touchend",It,!1),window.navigator.msPointerEnabled&&(p.wrapper.addEventListener("MSPointerDown",qt,!1),p.wrapper.addEventListener("MSPointerMove",Rt,!1),p.wrapper.addEventListener("MSPointerUp",Ut,!1))),i.keyboard&&document.addEventListener("keydown",Bt,!1),i.progress&&p.progress&&p.progress.addEventListener("click",Wt,!1),["touchstart","click"].forEach(function(e){p.controlsLeft.forEach(function(t){t.addEventListener(e,Xt,!1)}),p.controlsRight.forEach(function(t){t.addEventListener(e,Vt,!1)}),p.controlsUp.forEach(function(t){t.addEventListener(e,$t,!1)}),p.controlsDown.forEach(function(t){t.addEventListener(e,Jt,!1)}),p.controlsPrev.forEach(function(t){t.addEventListener(e,Kt,!1)}),p.controlsNext.forEach(function(t){t.addEventListener(e,Qt,!1)})})}function P(){S=!1,document.removeEventListener("keydown",Bt,!1),window.removeEventListener("hashchange",Gt,!1),window.removeEventListener("resize",Yt,!1),p.wrapper.removeEventListener("touchstart",jt,!1),p.wrapper.removeEventListener("touchmove",Ft,!1),p.wrapper.removeEventListener("touchend",It,!1),window.navigator.msPointerEnabled&&(p.wrapper.removeEventListener("MSPointerDown",qt,!1),p.wrapper.removeEventListener("MSPointerMove",Rt,!1),p.wrapper.removeEventListener("MSPointerUp",Ut,!1)),i.progress&&p.progress&&p.progress.removeEventListener("click",Wt,!1),["touchstart","click"].forEach(function(e){p.controlsLeft.forEach(function(t){t.removeEventListener(e,Xt,!1)}),p.controlsRight.forEach(function(t){t.removeEventListener(e,Vt,!1)}),p.controlsUp.forEach(function(t){t.removeEventListener(e,$t,!1)}),p.controlsDown.forEach(function(t){t.removeEventListener(e,Jt,!1)}),p.controlsPrev.forEach(function(t){t.removeEventListener(e,Kt,!1)}),p.controlsNext.forEach(function(t){t.removeEventListener(e,Qt,!1)})})}function H(e,t){for(var n in t)e[n]=t[n]}function B(e){return Array.prototype.slice.call(e)}function j(e,t){var n=e.x-t.x,r=e.y-t.y;return Math.sqrt(n*n+r*r)}function F(e,t){e.style.WebkitTransform=t,e.style.MozTransform=t,e.style.msTransform=t,e.style.OTransform=t,e.style.transform=t}function I(e){var t=0;if(e){var n=0;B(e.childNodes).forEach(function(e){typeof e.offsetTop=="number"&&e.style&&(e.style.position==="absolute"&&(n+=1),t=Math.max(t,e.offsetTop+e.offsetHeight))}),n===0&&(t=e.offsetHeight)}return t}function q(e,t){t=t||0;if(e){var n=e.parentNode,r=n.childNodes;B(r).forEach(function(n){if(typeof n.offsetHeight=="number"&&n!==e){var r=window.getComputedStyle(n),i=parseInt(r.marginTop,10),s=parseInt(r.marginBottom,10);t-=n.offsetHeight+i+s}});var i=window.getComputedStyle(e);t-=parseInt(i.marginTop,10)+parseInt(i.marginBottom,10)}return t}function R(){return/print-pdf/gi.test(window.location.search)}function U(){i.hideAddressBar&&m&&(window.addEventListener("load",z,!1),window.addEventListener("orientationchange",z,!1))}function z(){window.orientation===0&&!/crios/gi.test(navigator.userAgent)?(document.documentElement.style.overflow="scroll",document.body.style.height="120%"):(document.documentElement.style.overflow="",document.body.style.height="100%"),setTimeout(function(){window.scrollTo(0,1)},10)}function W(e,t){var n=document.createEvent("HTMLEvents",1,2);n.initEvent(e,!0,!0),H(n,t),p.wrapper.dispatchEvent(n)}function X(){if(d&&!("msPerspective"in document.body.style)){var t=document.querySelectorAll(e+" a:not(.image)");for(var n=0,r=t.length;n<r;n++){var i=t[n];if(i.textContent&&!i.querySelector("*")&&(!i.className||!i.classList.contains(i,"roll"))){var s=document.createElement("span");s.setAttribute("data-title",i.text),s.innerHTML=i.innerHTML,i.classList.add("roll"),i.innerHTML="",i.appendChild(s)}}}}function V(){var t=document.querySelectorAll(e+" a.roll");for(var n=0,r=t.length;n<r;n++){var i=t[n],s=i.querySelector("span");s&&(i.classList.remove("roll"),i.innerHTML=s.innerHTML)}}function $(e){var t=B(document.querySelectorAll(e?e:"a"));t.forEach(function(e){/^(http|www)/gi.test(e.getAttribute("href"))&&e.addEventListener("click",en,!1)})}function J(){var e=B(document.querySelectorAll("a"));e.forEach(function(e){/^(http|www)/gi.test(e.getAttribute("href"))&&e.removeEventListener("click",en,!1)})}function K(e){Q(),p.preview=document.createElement("div"),p.preview.classList.add("preview-link-overlay"),p.wrapper.appendChild(p.preview),p.preview.innerHTML=["<header>",'<a class="close" href="#"><span class="icon"></span></a>','<a class="external" href="'+e+'" target="_blank"><span class="icon"></span></a>',"</header>",'<div class="spinner"></div>','<div class="viewport">','<iframe src="'+e+'"></iframe>',"</div>"].join(""),p.preview.querySelector("iframe").addEventListener("load",function(e){p.preview.classList.add("loaded")},!1),p.preview.querySelector(".close").addEventListener("click",function(e){Q(),e.preventDefault()},!1),p.preview.querySelector(".external").addEventListener("click",function(e){Q()},!1),setTimeout(function(){p.preview.classList.add("visible")},1)}function Q(){p.preview&&(p.preview.setAttribute("src",""),p.preview.parentNode.removeChild(p.preview),p.preview=null)}function G(e){var t=B(e);return t.forEach(function(e,t){e.hasAttribute("data-fragment-index")||e.setAttribute("data-fragment-index",t)}),t.sort(function(e,t){return e.getAttribute("data-fragment-index")-t.getAttribute("data-fragment-index")}),t}function Y(){if(p.wrapper&&!R()){var t=p.wrapper.offsetWidth,n=p.wrapper.offsetHeight;t-=n*i.margin,n-=n*i.margin;var r=i.width,s=i.height,o=20;Z(i.width,i.height,o),typeof r=="string"&&/%$/.test(r)&&(r=parseInt(r,10)/100*t),typeof s=="string"&&/%$/.test(s)&&(s=parseInt(s,10)/100*n),p.slides.style.width=r+"px",p.slides.style.height=s+"px",h=Math.min(t/r,n/s),h=Math.max(h,i.minScale),h=Math.min(h,i.maxScale),typeof p.slides.style.zoom!="undefined"&&!navigator.userAgent.match(/(iphone|ipod|ipad|android)/gi)?p.slides.style.zoom=h:F(p.slides,"translate(-50%, -50%) scale("+h+") translate(50%, 50%)");var u=B(document.querySelectorAll(e));for(var a=0,f=u.length;a<f;a++){var l=u[a];if(l.style.display==="none")continue;i.center?l.classList.contains("stack")?l.style.top=0:l.style.top=Math.max(-(I(l)/2)-o,-s/2)+"px":l.style.top=""}mt()}}function Z(e,t,n){B(p.slides.querySelectorAll("section > .stretch")).forEach(function(r){var i=q(r,t-n*2);if(/(img|video)/gi.test(r.nodeName)){var s=r.naturalWidth||r.videoWidth,o=r.naturalHeight||r.videoHeight,u=Math.min(e/s,i/o);r.style.width=s*u+"px",r.style.height=o*u+"px"}else r.style.width=e+"px",r.style.height=i+"px"})}function et(e,t){typeof e=="object"&&typeof e.setAttribute=="function"&&e.setAttribute("data-previous-indexv",t||0)}function tt(e){if(typeof e=="object"&&typeof e.setAttribute=="function"&&e.classList.contains("stack")){var t=e.hasAttribute("data-start-indexv")?"data-start-indexv":"data-previous-indexv";return parseInt(e.getAttribute(t)||0,10)}return 0}function nt(){if(i.overview){At();var e=p.wrapper.classList.contains("overview"),n=window.innerWidth<400?1e3:2500;p.wrapper.classList.add("overview"),p.wrapper.classList.remove("overview-deactivating"),clearTimeout(w),clearTimeout(E),w=setTimeout(function(){var r=document.querySelectorAll(t);for(var s=0,o=r.length;s<o;s++){var f=r[s],c=i.rtl?-105:105;f.setAttribute("data-index-h",s),F(f,"translateZ(-"+n+"px) translate("+(s-u)*c+"%, 0%)");if(f.classList.contains("stack")){var h=f.querySelectorAll("section");for(var p=0,d=h.length;p<d;p++){var v=s===u?a:tt(f),m=h[p];m.setAttribute("data-index-h",s),m.setAttribute("data-index-v",p),F(m,"translate(0%, "+(p-v)*105+"%)"),m.addEventListener("click",Zt,!0)}}else f.addEventListener("click",Zt,!0)}vt(),Y(),e||W("overviewshown",{indexh:u,indexv:a,currentSlide:l})},10)}}function rt(){i.overview&&(clearTimeout(w),clearTimeout(E),p.wrapper.classList.remove("overview"),p.wrapper.classList.add("overview-deactivating"),E=setTimeout(function(){p.wrapper.classList.remove("overview-deactivating")},1),B(document.querySelectorAll(e)).forEach(function(e){F(e,""),e.removeEventListener("click",Zt,!0)}),ht(u,a),Lt(),W("overviewhidden",{indexh:u,indexv:a,currentSlide:l}))}function it(e){typeof e=="boolean"?e?nt():rt():st()?rt():nt()}function st(){return p.wrapper.classList.contains("overview")}function ot(e){return e=e?e:l,e&&e.parentNode&&!!e.parentNode.nodeName.match(/section/i)}function ut(){var e=document.body,t=e.requestFullScreen||e.webkitRequestFullscreen||e.webkitRequestFullScreen||e.mozRequestFullScreen||e.msRequestFullScreen;t&&t.apply(e)}function at(){var e=p.wrapper.classList.contains("paused");At(),p.wrapper.classList.add("paused"),e===!1&&W("paused")}function ft(){var e=p.wrapper.classList.contains("paused");p.wrapper.classList.remove("paused"),Lt(),e&&W("resumed")}function lt(){ct()?ft():at()}function ct(){return p.wrapper.classList.contains("paused")}function ht(e,i,s,o){f=l;var h=document.querySelectorAll(t);i===undefined&&(i=tt(h[e])),f&&f.parentNode&&f.parentNode.classList.contains("stack")&&et(f.parentNode,a);var p=c.concat();c.length=0;var d=u||0,v=a||0;u=dt(t,e===undefined?u:e),a=dt(n,i===undefined?a:i),vt(),Y();e:for(var m=0,g=c.length;m<g;m++){for(var y=0;y<p.length;y++)if(p[y]===c[m]){p.splice(y,1);continue e}document.documentElement.classList.add(c[m]),W(c[m])}while(p.length)document.documentElement.classList.remove(p.pop());st()&&nt();var b=h[u],w=b.querySelectorAll("section");l=w[a]||b;if(typeof s!="undefined"){var E=G(l.querySelectorAll(".fragment"));B(E).forEach(function(e,t){t<s?e.classList.add("visible"):e.classList.remove("visible")})}var S=u!==d||a!==v;S?W("slidechanged",{indexh:u,indexv:a,previousSlide:f,currentSlide:l,origin:o}):f=null,f&&(f.classList.remove("present"),document.querySelector(r).classList.contains("present")&&setTimeout(function(){var e=B(document.querySelectorAll(t+".stack")),n;for(n in e)e[n]&&et(e[n],0)},0)),S&&(St(f),Et(l)),gt(),mt(),yt(),Tt()}function pt(){P(),D(),Y(),o=i.autoSlide,Lt(),M(),gt(),mt(),yt()}function dt(e,t){var n=B(document.querySelectorAll(e)),r=n.length;if(r){i.loop&&(t%=r,t<0&&(t=r+t)),t=Math.max(Math.min(t,r-1),0);for(var s=0;s<r;s++){var u=n[s],a=i.rtl&&!ot(u);u.classList.remove("past"),u.classList.remove("present"),u.classList.remove("future"),u.setAttribute("hidden","");if(s<t)u.classList.add(a?"future":"past");else if(s>t){u.classList.add(a?"past":"future");var f=B(u.querySelectorAll(".fragment.visible"));while(f.length)f.pop().classList.remove("visible")}u.querySelector("section")&&u.classList.add("stack")}n[t].classList.add("present"),n[t].removeAttribute("hidden");var l=n[t].getAttribute("data-state");l&&(c=c.concat(l.split(" ")));var h=n[t].getAttribute("data-autoslide");h?o=parseInt(h,10):o=i.autoSlide,Lt()}else t=0;return t}function vt(){var e=B(document.querySelectorAll(t)),n=e.length,r,s;if(n){var o=st()?10:i.viewDistance;m&&(o=st()?6:1);for(var f=0;f<n;f++){var l=e[f],c=B(l.querySelectorAll("section")),h=c.length;r=Math.abs((u-f)%(n-o))||0,l.style.display=r>o?"none":"block";if(h){var p=tt(l);for(var d=0;d<h;d++){var v=c[d];s=f===u?Math.abs(a-d):Math.abs(d-p),v.style.display=r+s>o?"none":"block"}}}}}function mt(){if(i.progress&&p.progress){var n=B(document.querySelectorAll(t)),r=document.querySelectorAll(e+":not(.stack)").length,s=0;e:for(var o=0;o<n.length;o++){var u=n[o],a=B(u.querySelectorAll("section"));for(var f=0;f<a.length;f++){if(a[f].classList.contains("present"))break e;s++}if(u.classList.contains("present"))break;u.classList.contains("stack")===!1&&s++}p.progressbar.style.width=s/(r-1)*window.innerWidth+"px"}}function gt(){var e=bt(),t=wt();p.controlsLeft.concat(p.controlsRight).concat(p.controlsUp).concat(p.controlsDown).concat(p.controlsPrev).concat(p.controlsNext).forEach(function(e){e.classList.remove("enabled"),e.classList.remove("fragmented")}),e.left&&p.controlsLeft.forEach(function(e){e.classList.add("enabled")}),e.right&&p.controlsRight.forEach(function(e){e.classList.add("enabled")}),e.up&&p.controlsUp.forEach(function(e){e.classList.add("enabled")}),e.down&&p.controlsDown.forEach(function(e){e.classList.add("enabled")}),(e.left||e.up)&&p.controlsPrev.forEach(function(e){e.classList.add("enabled")}),(e.right||e.down)&&p.controlsNext.forEach(function(e){e.classList.add("enabled")}),l&&(t.prev&&p.controlsPrev.forEach(function(e){e.classList.add("fragmented","enabled")}),t.next&&p.controlsNext.forEach(function(e){e.classList.add("fragmented","enabled")}),ot(l)?(t.prev&&p.controlsUp.forEach(function(e){e.classList.add("fragmented","enabled")}),t.next&&p.controlsDown.forEach(function(e){e.classList.add("fragmented","enabled")})):(t.prev&&p.controlsLeft.forEach(function(e){e.classList.add("fragmented","enabled")}),t.next&&p.controlsRight.forEach(function(e){e.classList.add("fragmented","enabled")})))}function yt(){B(p.background.childNodes).forEach(function(e,t){var n=i.rtl?"future":"past",r=i.rtl?"past":"future";e.className="slide-background "+(t<u?n:t>u?r:"present"),B(e.childNodes).forEach(function(e,t){e.className="slide-background "+(t<a?"past":t>a?"future":"present")})}),setTimeout(function(){p.background.classList.remove("no-transition")},1)}function bt(){var e=document.querySelectorAll(t),r=document.querySelectorAll(n),s={left:u>0||i.loop,right:u<e.length-1||i.loop,up:a>0,down:a<r.length-1};if(i.rtl){var o=s.left;s.left=s.right,s.right=o}return s}function wt(){if(l&&i.fragments){var e=l.querySelectorAll(".fragment"),t=l.querySelectorAll(".fragment:not(.visible)");return{prev:e.length-t.length>0,next:!!t.length}}return{prev:!1,next:!1}}function Et(e){e&&(B(e.querySelectorAll("video, audio")).forEach(function(e){e.hasAttribute("data-autoplay")&&e.play()}),B(e.querySelectorAll('iframe[src*="youtube.com/embed/"]')).forEach(function(e){e.hasAttribute("data-autoplay")&&e.contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}',"*")}))}function St(e){e&&(B(e.querySelectorAll("video, audio")).forEach(function(e){e.hasAttribute("data-ignore")||e.pause()}),B(e.querySelectorAll('iframe[src*="youtube.com/embed/"]')).forEach(function(e){!e.hasAttribute("data-ignore")&&typeof e.contentWindow.postMessage=="function"&&e.contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}',"*")}))}function xt(){var e=window.location.hash,t=e.slice(2).split("/"),n=e.replace(/#|\//gi,"");if(isNaN(parseInt(t[0],10))&&n.length){var r=document.querySelector("#"+n);if(r){var i=Reveal.getIndices(r);ht(i.h,i.v)}else ht(u||0,a||0)}else{var s=parseInt(t[0],10)||0,o=parseInt(t[1],10)||0;(s!==u||o!==a)&&ht(s,o)}}function Tt(e){if(i.history){clearTimeout(b);if(typeof e=="number")b=setTimeout(Tt,e);else{var t="/";if(l&&typeof l.getAttribute("id")=="string")t="/"+l.getAttribute("id");else{if(u>0||a>0)t+=u;a>0&&(t+="/"+a)}window.location.hash=t}}}function Nt(e){var n=u,r=a,i;if(e){var s=ot(e),o=s?e.parentNode:e,f=B(document.querySelectorAll(t));n=Math.max(f.indexOf(o),0),s&&(r=Math.max(B(e.parentNode.querySelectorAll("section")).indexOf(e),0))}if(!e&&l){var c=l.querySelectorAll(".fragment").length>0;if(c){var h=l.querySelectorAll(".fragment.visible");i=h.length}}return{h:n,v:r,f:i}}function Ct(){if(l&&i.fragments){var e=G(l.querySelectorAll(".fragment:not(.visible)"));if(e.length){var t=e[0].getAttribute("data-fragment-index");return e=l.querySelectorAll('.fragment[data-fragment-index="'+t+'"]'),B(e).forEach(function(e){e.classList.add("visible")}),W("fragmentshown",{fragment:e[0],fragments:e}),gt(),!0}}return!1}function kt(){if(l&&i.fragments){var e=G(l.querySelectorAll(".fragment.visible"));if(e.length){var t=e[e.length-1].getAttribute("data-fragment-index");return e=l.querySelectorAll('.fragment[data-fragment-index="'+t+'"]'),B(e).forEach(function(e){e.classList.remove("visible")}),W("fragmenthidden",{fragment:e[0],fragments:e}),gt(),!0}}return!1}function Lt(){clearTimeout(y),o&&!ct()&&!st()&&(y=setTimeout(Ht,o))}function At(){clearTimeout(y)}function Ot(){i.rtl?(st()||Ct()===!1)&&bt().left&&ht(u+1):(st()||kt()===!1)&&bt().left&&ht(u-1)}function Mt(){i.rtl?(st()||kt()===!1)&&bt().right&&ht(u-1):(st()||Ct()===!1)&&bt().right&&ht(u+1)}function _t(){(st()||kt()===!1)&&bt().up&&ht(u,a-1)}function Dt(){(st()||Ct()===!1)&&bt().down&&ht(u,a+1)}function Pt(){if(kt()===!1)if(bt().up)_t();else{var e=document.querySelector(t+".past:nth-child("+u+")");if(e){var n=e.querySelectorAll("section").length-1||undefined,r=u-1;ht(r,n)}}}function Ht(){Ct()===!1&&(bt().down?Dt():Mt()),Lt()}function Bt(e){var t=document.activeElement,n=!(!document.activeElement||!document.activeElement.type&&!document.activeElement.href&&document.activeElement.contentEditable==="inherit");if(n||e.shiftKey&&e.keyCode!==32||e.altKey||e.ctrlKey||e.metaKey)return;if(ct()&&[66,190,191].indexOf(e.keyCode)===-1)return!1;var r=!1;if(typeof i.keyboard=="object")for(var s in i.keyboard)if(parseInt(s,10)===e.keyCode){var o=i.keyboard[s];typeof o=="function"?o.apply(null,[e]):typeof o=="string"&&typeof Reveal[o]=="function"&&Reveal[o].call(),r=!0}if(r===!1){r=!0;switch(e.keyCode){case 80:case 33:Pt();break;case 78:case 34:Ht();break;case 72:case 37:Ot();break;case 76:case 39:Mt();break;case 75:case 38:_t();break;case 74:case 40:Dt();break;case 36:ht(0);break;case 35:ht(Number.MAX_VALUE);break;case 32:st()?rt():e.shiftKey?Pt():Ht();break;case 13:st()?rt():r=!1;break;case 66:case 190:case 191:lt();break;case 70:ut();break;default:r=!1}}r?e.preventDefault():(e.keyCode===27||e.keyCode===79)&&d&&(it(),e.preventDefault()),Lt()}function jt(e){x.startX=e.touches[0].clientX,x.startY=e.touches[0].clientY,x.startCount=e.touches.length,e.touches.length===2&&i.overview&&(x.startSpan=j({x:e.touches[1].clientX,y:e.touches[1].clientY},{x:x.startX,y:x.startY}))}function Ft(e){if(!x.captured){var t=e.touches[0].clientX,n=e.touches[0].clientY;if(e.touches.length===2&&x.startCount===2&&i.overview){var r=j({x:e.touches[1].clientX,y:e.touches[1].clientY},{x:x.startX,y:x.startY});Math.abs(x.startSpan-r)>x.threshold&&(x.captured=!0,r<x.startSpan?nt():rt()),e.preventDefault()}else if(e.touches.length===1&&x.startCount!==2){var s=t-x.startX,o=n-x.startY;s>x.threshold&&Math.abs(s)>Math.abs(o)?(x.captured=!0,Ot()):s<-x.threshold&&Math.abs(s)>Math.abs(o)?(x.captured=!0,Mt()):o>x.threshold?(x.captured=!0,_t()):o<-x.threshold&&(x.captured=!0,Dt()),i.embedded?(x.captured||ot(l))&&e.preventDefault():e.preventDefault()}}else navigator.userAgent.match(/android/gi)&&e.preventDefault()}function It(e){x.captured=!1}function qt(e){e.pointerType===e.MSPOINTER_TYPE_TOUCH&&(e.touches=[{clientX:e.clientX,clientY:e.clientY}],jt(e))}function Rt(e){e.pointerType===e.MSPOINTER_TYPE_TOUCH&&(e.touches=[{clientX:e.clientX,clientY:e.clientY}],Ft(e))}function Ut(e){e.pointerType===e.MSPOINTER_TYPE_TOUCH&&(e.touches=[{clientX:e.clientX,clientY:e.clientY}],It(e))}function zt(e){if(Date.now()-g>600){g=Date.now();var t=e.detail||-e.wheelDelta;t>0?Ht():Pt()}}function Wt(e){e.preventDefault();var n=B(document.querySelectorAll(t)).length,r=Math.floor(e.clientX/p.wrapper.offsetWidth*n);ht(r)}function Xt(e){e.preventDefault(),Ot()}function Vt(e){e.preventDefault(),Mt()}function $t(e){e.preventDefault(),_t()}function Jt(e){e.preventDefault(),Dt()}function Kt(e){e.preventDefault(),Pt()}function Qt(e){e.preventDefault(),Ht()}function Gt(e){xt()}function Yt(e){Y()}function Zt(e){if(S&&st()){e.preventDefault(),e.stopPropagation();var t=e.target;while(t&&!t.nodeName.match(/section/gi))t=t.parentNode;if(t&&!t.classList.contains("disabled")){rt();if(t.nodeName.match(/section/gi)){var n=parseInt(t.getAttribute("data-index-h"),10),r=parseInt(t.getAttribute("data-index-v"),10);ht(n,r)}}}}function en(e){var t=e.target.getAttribute("href");t&&(K(t),e.preventDefault())}var e=".reveal .slides section",t=".reveal .slides>section",n=".reveal .slides>section.present>section",r=".reveal .slides>section:first-child",i={width:960,height:700,margin:.1,minScale:.2,maxScale:1,controls:!0,progress:!0,history:!1,keyboard:!0,overview:!0,center:!0,touch:!0,loop:!1,rtl:!1,fragments:!0,embedded:!1,autoSlide:0,mouseWheel:!1,rollingLinks:!1,hideAddressBar:!0,previewLinks:!1,theme:null,transition:"default",transitionSpeed:"default",backgroundTransition:"default",viewDistance:3,dependencies:[]},s=!1,o=0,u,a,f,l,c=[],h=1,p={},d,v,m,g=0,y=0,b=0,w=0,E=0,S=!1,x={startX:0,startY:0,startSpan:0,startCount:0,captured:!1,threshold:40};return{initialize:T,configure:_,sync:pt,slide:ht,left:Ot,right:Mt,up:_t,down:Dt,prev:Pt,next:Ht,prevFragment:kt,nextFragment:Ct,navigateTo:ht,navigateLeft:Ot,navigateRight:Mt,navigateUp:_t,navigateDown:Dt,navigatePrev:Pt,navigateNext:Ht,layout:Y,availableRoutes:bt,availableFragments:wt,toggleOverview:it,togglePause:lt,isOverview:st,isPaused:ct,addEventListeners:D,removeEventListeners:P,getIndices:Nt,getSlide:function(e,n){var r=document.querySelectorAll(t)[e],i=r&&r.querySelectorAll("section");return typeof n!="undefined"?i?i[n]:undefined:r},getPreviousSlide:function(){return f},getCurrentSlide:function(){return l},getScale:function(){return h},getConfig:function(){return i},getQueryHash:function(){var e={};return location.search.replace(/[A-Z0-9]+?=(\w*)/gi,function(t){e[t.split("=").shift()]=t.split("=").pop()}),e},isFirstSlide:function(){return document.querySelector(e+".past")==null?!0:!1},isLastSlide:function(){return l?l.nextElementSibling?!1:ot(l)&&l.parentNode.nextElementSibling?!1:!0:!1},isReady:function(){return s},addEventListener:function(e,t,n){"addEventListener"in window&&(p.wrapper||document.querySelector(".reveal")).addEventListener(e,t,n)},removeEventListener:function(e,t,n){"addEventListener"in window&&(p.wrapper||document.querySelector(".reveal")).removeEventListener(e,t,n)}}}();define("revealJS",["jquery","classList"],function(){}),!function(e){e(function(){e.support.transition=function(){var e=function(){var e=document.createElement("bootstrap"),t={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"},n;for(n in t)if(e.style[n]!==undefined)return t[n]}();return e&&{end:e}}()})}(window.jQuery),!function(e){var t=function(t,n){this.options=n,this.$element=e(t).delegate('[data-dismiss="modal"]',"click.dismiss.modal",e.proxy(this.hide,this)),this.options.remote&&this.$element.find(".modal-body").load(this.options.remote)};t.prototype={constructor:t,toggle:function(){return this[this.isShown?"hide":"show"]()},show:function(){var t=this,n=e.Event("show");this.$element.trigger(n);if(this.isShown||n.isDefaultPrevented())return;e("body").addClass("modal-open"),this.isShown=!0,this.escape(),this.backdrop(function(){var n=e.support.transition&&t.$element.hasClass("fade");t.$element.parent().length||t.$element.appendTo(document.body),t.$element.show(),n&&t.$element[0].offsetWidth,t.$element.addClass("in").attr("aria-hidden",!1).focus(),t.enforceFocus(),n?t.$element.one(e.support.transition.end,function(){t.$element.trigger("shown")}):t.$element.trigger("shown")})},hide:function(t){t&&t.preventDefault();var n=this;t=e.Event("hide"),this.$element.trigger(t);if(!this.isShown||t.isDefaultPrevented())return;this.isShown=!1,e("body").removeClass("modal-open"),this.escape(),e(document).off("focusin.modal"),this.$element.removeClass("in").attr("aria-hidden",!0),e.support.transition&&this.$element.hasClass("fade")?this.hideWithTransition():this.hideModal()},enforceFocus:function(){var t=this;e(document).on("focusin.modal",function(e){t.$element[0]!==e.target&&!t.$element.has(e.target).length&&t.$element.focus()})},escape:function(){var e=this;this.isShown&&this.options.keyboard?this.$element.on("keyup.dismiss.modal",function(t){t.which==27&&e.hide()}):this.isShown||this.$element.off("keyup.dismiss.modal")},hideWithTransition:function(){var t=this,n=setTimeout(function(){t.$element.off(e.support.transition.end),t.hideModal()},500);this.$element.one(e.support.transition.end,function(){clearTimeout(n),t.hideModal()})},hideModal:function(e){this.$element.hide().trigger("hidden"),this.backdrop()},removeBackdrop:function(){this.$backdrop.remove(),this.$backdrop=null},backdrop:function(t){var n=this,r=this.$element.hasClass("fade")?"fade":"";if(this.isShown&&this.options.backdrop){var i=e.support.transition&&r;this.$backdrop=e('<div class="modal-backdrop '+r+'" />').appendTo(document.body),this.options.backdrop!="static"&&this.$backdrop.click(e.proxy(this.hide,this)),i&&this.$backdrop[0].offsetWidth,this.$backdrop.addClass("in"),i?this.$backdrop.one(e.support.transition.end,t):t()}else!this.isShown&&this.$backdrop?(this.$backdrop.removeClass("in"),e.support.transition&&this.$element.hasClass("fade")?this.$backdrop.one(e.support.transition.end,e.proxy(this.removeBackdrop,this)):this.removeBackdrop()):t&&t()}},e.fn.modal=function(n){return this.each(function(){var r=e(this),i=r.data("modal"),s=e.extend({},e.fn.modal.defaults,r.data(),typeof n=="object"&&n);i||r.data("modal",i=new t(this,s)),typeof n=="string"?i[n]():s.show&&i.show()})},e.fn.modal.defaults={backdrop:!0,keyboard:!0,show:!0},e.fn.modal.Constructor=t,e(function(){e("body").on("click.modal.data-api",'[data-toggle="modal"]',function(t){var n=e(this),r=n.attr("href"),i=e(n.attr("data-target")||r&&r.replace(/.*(?=#[^\s]+$)/,"")),s=i.data("modal")?"toggle":e.extend({remote:!/#/.test(r)&&r},i.data(),n.data());t.preventDefault(),i.modal(s).one("hide",function(){n.focus()})})})}(window.jQuery),!function(e){function t(){n(e(r)).removeClass("open")}function n(t){var n=t.attr("data-target"),r;return n||(n=t.attr("href"),n=n&&n.replace(/.*(?=#[^\s]*$)/,"")),r=e(n),r.length||(r=t.parent()),r}var r="[data-toggle=dropdown]",i=function(t){var n=e(t).on("click.dropdown.data-api",this.toggle);e("html").on("click.dropdown.data-api",function(){n.parent().removeClass("open")})};i.prototype={constructor:i,toggle:function(r){var i=e(this),s,o;if(i.is(".disabled, :disabled"))return;return s=n(i),o=s.hasClass("open"),t(),o||(s.toggleClass("open"),i.focus()),!1},keydown:function(t){var r,i,s,o,u,f;if(!/(38|40|27)/.test(t.keyCode))return;r=e(this),t.preventDefault(),t.stopPropagation();if(r.is(".disabled, :disabled"))return;o=n(r),u=o.hasClass("open");if(!u||u&&t.keyCode==27)return r.click();i=e("[role=menu] li:not(.divider) a",o);if(!i.length)return;f=i.index(i.filter(":focus")),t.keyCode==38&&f>0&&f--,t.keyCode==40&&f<i.length-1&&f++,~f||(f=0),i.eq(f).focus()}},e.fn.dropdown=function(t){return this.each(function(){var n=e(this),r=n.data("dropdown");r||n.data("dropdown",r=new i(this)),typeof t=="string"&&r[t].call(n)})},e.fn.dropdown.Constructor=i,e(function(){e("html").on("click.dropdown.data-api touchstart.dropdown.data-api",t),e("body").on("click.dropdown touchstart.dropdown.data-api",".dropdown",function(e){e.stopPropagation()}).on("click.dropdown.data-api touchstart.dropdown.data-api",r,i.prototype.toggle).on("keydown.dropdown.data-api touchstart.dropdown.data-api",r+", [role=menu]",i.prototype.keydown)})}(window.jQuery),!function(e){function t(t,n){var r=e.proxy(this.process,this),i=e(t).is("body")?e(window):e(t),s;this.options=e.extend({},e.fn.scrollspy.defaults,n),this.$scrollElement=i.on("scroll.scroll-spy.data-api",r),this.selector=(this.options.target||(s=e(t).attr("href"))&&s.replace(/.*(?=#[^\s]+$)/,"")||"")+" .nav li > a",this.$body=e("body"),this.refresh(),this.process()}t.prototype={constructor:t,refresh:function(){var t=this,n;this.offsets=e([]),this.targets=e([]),n=this.$body.find(this.selector).map(function(){var t=e(this),n=t.data("target")||t.attr("href"),r=/^#\w/.test(n)&&e(n);return r&&r.length&&[[r.position().top,n]]||null}).sort(function(e,t){return e[0]-t[0]}).each(function(){t.offsets.push(this[0]),t.targets.push(this[1])})},process:function(){var e=this.$scrollElement.scrollTop()+this.options.offset,t=this.$scrollElement[0].scrollHeight||this.$body[0].scrollHeight,n=t-this.$scrollElement.height(),r=this.offsets,i=this.targets,s=this.activeTarget,o;if(e>=n)return s!=(o=i.last()[0])&&this.activate(o);for(o=r.length;o--;)s!=i[o]&&e>=r[o]&&(!r[o+1]||e<=r[o+1])&&this.activate(i[o])},activate:function(t){var n,r;this.activeTarget=t,e(this.selector).parent(".active").removeClass("active"),r=this.selector+'[data-target="'+t+'"],'+this.selector+'[href="'+t+'"]',n=e(r).parent("li").addClass("active"),n.parent(".dropdown-menu").length&&(n=n.closest("li.dropdown").addClass("active")),n.trigger("activate")}},e.fn.scrollspy=function(n){return this.each(function(){var r=e(this),i=r.data("scrollspy"),s=typeof n=="object"&&n;i||r.data("scrollspy",i=new t(this,s)),typeof n=="string"&&i[n]()})},e.fn.scrollspy.Constructor=t,e.fn.scrollspy.defaults={offset:10},e(window).on("load",function(){e('[data-spy="scroll"]').each(function(){var t=e(this);t.scrollspy(t.data())})})}(window.jQuery),!function(e){var t=function(t){this.element=e(t)};t.prototype={constructor:t,show:function(){var t=this.element,n=t.closest("ul:not(.dropdown-menu)"),r=t.attr("data-target"),i,s,o;r||(r=t.attr("href"),r=r&&r.replace(/.*(?=#[^\s]*$)/,""));if(t.parent("li").hasClass("active"))return;i=n.find(".active a").last()[0],o=e.Event("show",{relatedTarget:i}),t.trigger(o);if(o.isDefaultPrevented())return;s=e(r),this.activate(t.parent("li"),n),this.activate(s,s.parent(),function(){t.trigger({type:"shown",relatedTarget:i})})},activate:function(t,n,r){function i(){s.removeClass("active").find("> .dropdown-menu > .active").removeClass("active"),t.addClass("active"),o?(t[0].offsetWidth,t.addClass("in")):t.removeClass("fade"),t.parent(".dropdown-menu")&&t.closest("li.dropdown").addClass("active"),r&&r()}var s=n.find("> .active"),o=r&&e.support.transition&&s.hasClass("fade");o?s.one(e.support.transition.end,i):i(),s.removeClass("in")}},e.fn.tab=function(n){return this.each(function(){var r=e(this),i=r.data("tab");i||r.data("tab",i=new t(this)),typeof n=="string"&&i[n]()})},e.fn.tab.Constructor=t,e(function(){e("body").on("click.tab.data-api",'[data-toggle="tab"], [data-toggle="pill"]',function(t){t.preventDefault(),e(this).tab("show")})})}(window.jQuery),!function(e){var t=function(e,t){this.init("tooltip",e,t)};t.prototype={constructor:t,init:function(t,n,r){var i,s;this.type=t,this.$element=e(n),this.options=this.getOptions(r),this.enabled=!0,this.options.trigger=="click"?this.$element.on("click."+this.type,this.options.selector,e.proxy(this.toggle,this)):this.options.trigger!="manual"&&(i=this.options.trigger=="hover"?"mouseenter":"focus",s=this.options.trigger=="hover"?"mouseleave":"blur",this.$element.on(i+"."+this.type,this.options.selector,e.proxy(this.enter,this)),this.$element.on(s+"."+this.type,this.options.selector,e.proxy(this.leave,this))),this.options.selector?this._options=e.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},getOptions:function(t){return t=e.extend({},e.fn[this.type].defaults,t,this.$element.data()),t.delay&&typeof t.delay=="number"&&(t.delay={show:t.delay,hide:t.delay}),t},enter:function(t){var n=e(t.currentTarget)[this.type](this._options).data(this.type);if(!n.options.delay||!n.options.delay.show)return n.show();clearTimeout(this.timeout),n.hoverState="in",this.timeout=setTimeout(function(){n.hoverState=="in"&&n.show()},n.options.delay.show)},leave:function(t){var n=e(t.currentTarget)[this.type](this._options).data(this.type);this.timeout&&clearTimeout(this.timeout);if(!n.options.delay||!n.options.delay.hide)return n.hide();n.hoverState="out",this.timeout=setTimeout(function(){n.hoverState=="out"&&n.hide()},n.options.delay.hide)},show:function(){var e,t,n,r,i,s,o;if(this.hasContent()&&this.enabled){e=this.tip(),this.setContent(),this.options.animation&&e.addClass("fade"),s=typeof this.options.placement=="function"?this.options.placement.call(this,e[0],this.$element[0]):this.options.placement,t=/in/.test(s),e.remove().css({top:0,left:0,display:"block"}).appendTo(t?this.$element:document.body),n=this.getPosition(t),r=e[0].offsetWidth,i=e[0].offsetHeight;switch(t?s.split(" ")[1]:s){case"bottom":o={top:n.top+n.height,left:n.left+n.width/2-r/2};break;case"top":o={top:n.top-i,left:n.left+n.width/2-r/2};break;case"left":o={top:n.top+n.height/2-i/2,left:n.left-r};break;case"right":o={top:n.top+n.height/2-i/2,left:n.left+n.width}}e.css(o).addClass(s).addClass("in")}},setContent:function(){var e=this.tip(),t=this.getTitle();e.find(".tooltip-inner")[this.options.html?"html":"text"](t),e.removeClass("fade in top bottom left right")},hide:function(){function t(){var t=setTimeout(function(){r.off(e.support.transition.end).remove()},500);r.one(e.support.transition.end,function(){clearTimeout(t),r.remove()})}var n=this,r=this.tip();return r.removeClass("in"),e.support.transition&&this.$tip.hasClass("fade")?t():r.remove(),this},fixTitle:function(){var e=this.$element;(e.attr("title")||typeof e.attr("data-original-title")!="string")&&e.attr("data-original-title",e.attr("title")||"").removeAttr("title")},hasContent:function(){return this.getTitle()},getPosition:function(t){return e.extend({},t?{top:0,left:0}:this.$element.offset(),{width:this.$element[0].offsetWidth,height:this.$element[0].offsetHeight})},getTitle:function(){var e,t=this.$element,n=this.options;return e=t.attr("data-original-title")||(typeof n.title=="function"?n.title.call(t[0]):n.title),e},tip:function(){return this.$tip=this.$tip||e(this.options.template)},validate:function(){this.$element[0].parentNode||(this.hide(),this.$element=null,this.options=null)},enable:function(){this.enabled=!0},disable:function(){this.enabled=!1},toggleEnabled:function(){this.enabled=!this.enabled},toggle:function(){this[this.tip().hasClass("in")?"hide":"show"]()},destroy:function(){this.hide().$element.off("."+this.type).removeData(this.type)}},e.fn.tooltip=function(n){return this.each(function(){var r=e(this),i=r.data("tooltip"),s=typeof n=="object"&&n;i||r.data("tooltip",i=new t(this,s)),typeof n=="string"&&i[n]()})},e.fn.tooltip.Constructor=t,e.fn.tooltip.defaults={animation:!0,placement:"top",selector:!1,template:'<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',trigger:"hover",title:"",delay:0,html:!0}}(window.jQuery),!function(e){var t=function(e,t){this.init("popover",e,t)};t.prototype=e.extend({},e.fn.tooltip.Constructor.prototype,{constructor:t,setContent:function(){var e=this.tip(),t=this.getTitle(),n=this.getContent();e.find(".popover-title")[this.options.html?"html":"text"](t),e.find(".popover-content > *")[this.options.html?"html":"text"](n),e.removeClass("fade top bottom left right in")},hasContent:function(){return this.getTitle()||this.getContent()},getContent:function(){var e,t=this.$element,n=this.options;return e=t.attr("data-content")||(typeof n.content=="function"?n.content.call(t[0]):n.content),e},tip:function(){return this.$tip||(this.$tip=e(this.options.template)),this.$tip},destroy:function(){this.hide().$element.off("."+this.type).removeData(this.type)}}),e.fn.popover=function(n){return this.each(function(){var r=e(this),i=r.data("popover"),s=typeof n=="object"&&n;i||r.data("popover",i=new t(this,s)),typeof n=="string"&&i[n]()})},e.fn.popover.Constructor=t,e.fn.popover.defaults=e.extend({},e.fn.tooltip.defaults,{placement:"right",trigger:"click",content:"",template:'<div class="popover"><div class="arrow"></div><div class="popover-inner"><h3 class="popover-title"></h3><div class="popover-content"><p></p></div></div></div>'})}(window.jQuery),!function(e){var t=function(t,n){this.options=e.extend({},e.fn.affix.defaults,n),this.$window=e(window).on("scroll.affix.data-api",e.proxy(this.checkPosition,this)),this.$element=e(t),this.checkPosition()};t.prototype.checkPosition=function(){if(!this.$element.is(":visible"))return;var t=e(document).height(),n=this.$window.scrollTop(),r=this.$element.offset(),i=this.options.offset,s=i.bottom,o=i.top,u="affix affix-top affix-bottom",f;typeof i!="object"&&(s=o=i),typeof o=="function"&&(o=i.top()),typeof s=="function"&&(s=i.bottom()),f=this.unpin!=null&&n+this.unpin<=r.top?!1:s!=null&&r.top+this.$element.height()>=t-s?"bottom":o!=null&&n<=o?"top":!1;if(this.affixed===f)return;this.affixed=f,this.unpin=f=="bottom"?r.top-n:null,this.$element.removeClass(u).addClass("affix"+(f?"-"+f:""))},e.fn.affix=function(n){return this.each(function(){var r=e(this),i=r.data("affix"),s=typeof n=="object"&&n;i||r.data("affix",i=new t(this,s)),typeof n=="string"&&i[n]()})},e.fn.affix.Constructor=t,e.fn.affix.defaults={offset:0},e(window).on("load",function(){e('[data-spy="affix"]').each(function(){var t=e(this),n=t.data();n.offset=n.offset||{},n.offsetBottom&&(n.offset.bottom=n.offsetBottom),n.offsetTop&&(n.offset.top=n.offsetTop),t.affix(n)})})}(window.jQuery),!function(e){var t='[data-dismiss="alert"]',n=function(n){e(n).on("click",t,this.close)};n.prototype.close=function(t){function n(){s.trigger("closed").remove()}var r=e(this),i=r.attr("data-target"),s;i||(i=r.attr("href"),i=i&&i.replace(/.*(?=#[^\s]*$)/,"")),s=e(i),t&&t.preventDefault(),s.length||(s=r.hasClass("alert")?r:r.parent()),s.trigger(t=e.Event("close"));if(t.isDefaultPrevented())return;s.removeClass("in"),e.support.transition&&s.hasClass("fade")?s.on(e.support.transition.end,n):n()},e.fn.alert=function(t){return this.each(function(){var r=e(this),i=r.data("alert");i||r.data("alert",i=new n(this)),typeof t=="string"&&i[t].call(r)})},e.fn.alert.Constructor=n,e(function(){e("body").on("click.alert.data-api",t,n.prototype.close)})}(window.jQuery),!function(e){var t=function(t,n){this.$element=e(t),this.options=e.extend({},e.fn.button.defaults,n)};t.prototype.setState=function(e){var t="disabled",n=this.$element,r=n.data(),i=n.is("input")?"val":"html";e+="Text",r.resetText||n.data("resetText",n[i]()),n[i](r[e]||this.options[e]),setTimeout(function(){e=="loadingText"?n.addClass(t).attr(t,t):n.removeClass(t).removeAttr(t)},0)},t.prototype.toggle=function(){var e=this.$element.parent('[data-toggle="buttons-radio"]');e&&e.find(".active").removeClass("active"),this.$element.toggleClass("active")},e.fn.button=function(n){return this.each(function(){var r=e(this),i=r.data("button"),s=typeof n=="object"&&n;i||r.data("button",i=new t(this,s)),n=="toggle"?i.toggle():n&&i.setState(n)})},e.fn.button.defaults={loadingText:"loading..."},e.fn.button.Constructor=t,e(function(){e("body").on("click.button.data-api","[data-toggle^=button]",function(t){var n=e(t.target);n.hasClass("btn")||(n=n.closest(".btn")),n.button("toggle")})})}(window.jQuery),!function(e){var t=function(t,n){this.$element=e(t),this.options=e.extend({},e.fn.collapse.defaults,n),this.options.parent&&(this.$parent=e(this.options.parent)),this.options.toggle&&this.toggle()};t.prototype={constructor:t,dimension:function(){var e=this.$element.hasClass("width");return e?"width":"height"},show:function(){var t,n,r,i;if(this.transitioning)return;t=this.dimension(),n=e.camelCase(["scroll",t].join("-")),r=this.$parent&&this.$parent.find("> .accordion-group > .in");if(r&&r.length){i=r.data("collapse");if(i&&i.transitioning)return;r.collapse("hide"),i||r.data("collapse",null)}this.$element[t](0),this.transition("addClass",e.Event("show"),"shown"),e.support.transition&&this.$element[t](this.$element[0][n])},hide:function(){var t;if(this.transitioning)return;t=this.dimension(),this.reset(this.$element[t]()),this.transition("removeClass",e.Event("hide"),"hidden"),this.$element[t](0)},reset:function(e){var t=this.dimension();return this.$element.removeClass("collapse")[t](e||"auto")[0].offsetWidth,this.$element[e!==null?"addClass":"removeClass"]("collapse"),this},transition:function(t,n,r){var i=this,s=function(){n.type=="show"&&i.reset(),i.transitioning=0,i.$element.trigger(r)};this.$element.trigger(n);if(n.isDefaultPrevented())return;this.transitioning=1,this.$element[t]("in"),e.support.transition&&this.$element.hasClass("collapse")?this.$element.one(e.support.transition.end,s):s()},toggle:function(){this[this.$element.hasClass("in")?"hide":"show"]()}},e.fn.collapse=function(n){return this.each(function(){var r=e(this),i=r.data("collapse"),s=typeof n=="object"&&n;i||r.data("collapse",i=new t(this,s)),typeof n=="string"&&i[n]()})},e.fn.collapse.defaults={toggle:!0},e.fn.collapse.Constructor=t,e(function(){e("body").on("click.collapse.data-api","[data-toggle=collapse]",function(t){var n=e(this),r,i=n.attr("data-target")||t.preventDefault()||(r=n.attr("href"))&&r.replace(/.*(?=#[^\s]+$)/,""),s=e(i).data("collapse")?"toggle":n.data();n[e(i).hasClass("in")?"addClass":"removeClass"]("collapsed"),e(i).collapse(s)})})}(window.jQuery),!function(e){var t=function(t,n){this.$element=e(t),this.options=n,this.options.slide&&this.slide(this.options.slide),this.options.pause=="hover"&&this.$element.on("mouseenter",e.proxy(this.pause,this)).on("mouseleave",e.proxy(this.cycle,this))};t.prototype={cycle:function(t){return t||(this.paused=!1),this.options.interval&&!this.paused&&(this.interval=setInterval(e.proxy(this.next,this),this.options.interval)),this},to:function(t){var n=this.$element.find(".item.active"),r=n.parent().children(),i=r.index(n),s=this;if(t>r.length-1||t<0)return;return this.sliding?this.$element.one("slid",function(){s.to(t)}):i==t?this.pause().cycle():this.slide(t>i?"next":"prev",e(r[t]))},pause:function(t){return t||(this.paused=!0),this.$element.find(".next, .prev").length&&e.support.transition.end&&(this.$element.trigger(e.support.transition.end),this.cycle()),clearInterval(this.interval),this.interval=null,this},next:function(){if(this.sliding)return;return this.slide("next")},prev:function(){if(this.sliding)return;return this.slide("prev")},slide:function(t,n){var r=this.$element.find(".item.active"),i=n||r[t](),s=this.interval,o=t=="next"?"left":"right",u=t=="next"?"first":"last",f=this,l=e.Event("slide",{relatedTarget:i[0]});this.sliding=!0,s&&this.pause(),i=i.length?i:this.$element.find(".item")[u]();if(i.hasClass("active"))return;if(e.support.transition&&this.$element.hasClass("slide")){this.$element.trigger(l);if(l.isDefaultPrevented())return;i.addClass(t),i[0].offsetWidth,r.addClass(o),i.addClass(o),this.$element.one(e.support.transition.end,function(){i.removeClass([t,o].join(" ")).addClass("active"),r.removeClass(["active",o].join(" ")),f.sliding=!1,setTimeout(function(){f.$element.trigger("slid")},0)})}else{this.$element.trigger(l);if(l.isDefaultPrevented())return;r.removeClass("active"),i.addClass("active"),this.sliding=!1,this.$element.trigger("slid")}return s&&this.cycle(),this}},e.fn.carousel=function(n){return this.each(function(){var r=e(this),i=r.data("carousel"),s=e.extend({},e.fn.carousel.defaults,typeof n=="object"&&n),o=typeof n=="string"?n:s.slide;i||r.data("carousel",i=new t(this,s)),typeof n=="number"?i.to(n):o?i[o]():s.interval&&i.cycle()})},e.fn.carousel.defaults={interval:5e3,pause:"hover"},e.fn.carousel.Constructor=t,e(function(){e("body").on("click.carousel.data-api","[data-slide]",function(t){var n=e(this),r,i=e(n.attr("data-target")||(r=n.attr("href"))&&r.replace(/.*(?=#[^\s]+$)/,"")),s=!i.data("modal")&&e.extend({},i.data(),n.data());i.carousel(s),t.preventDefault()})})}(window.jQuery),!function(e){var t=function(t,n){this.$element=e(t),this.options=e.extend({},e.fn.typeahead.defaults,n),this.matcher=this.options.matcher||this.matcher,this.sorter=this.options.sorter||this.sorter,this.highlighter=this.options.highlighter||this.highlighter,this.updater=this.options.updater||this.updater,this.$menu=e(this.options.menu).appendTo("body"),this.source=this.options.source,this.shown=!1,this.listen()};t.prototype={constructor:t,select:function(){var e=this.$menu.find(".active").attr("data-value");return this.$element.val(this.updater(e)).change(),this.hide()},updater:function(e){return e},show:function(){var t=e.extend({},this.$element.offset(),{height:this.$element[0].offsetHeight});return this.$menu.css({top:t.top+t.height,left:t.left}),this.$menu.show(),this.shown=!0,this},hide:function(){return this.$menu.hide(),this.shown=!1,this},lookup:function(t){var n;return this.query=this.$element.val(),!this.query||this.query.length<this.options.minLength?this.shown?this.hide():this:(n=e.isFunction(this.source)?this.source(this.query,e.proxy(this.process,this)):this.source,n?this.process(n):this)},process:function(t){var n=this;return t=e.grep(t,function(e){return n.matcher(e)}),t=this.sorter(t),t.length?this.render(t.slice(0,this.options.items)).show():this.shown?this.hide():this},matcher:function(e){return~e.toLowerCase().indexOf(this.query.toLowerCase())},sorter:function(e){var t=[],n=[],r=[],i;while(i=e.shift())i.toLowerCase().indexOf(this.query.toLowerCase())?~i.indexOf(this.query)?n.push(i):r.push(i):t.push(i);return t.concat(n,r)},highlighter:function(e){var t=this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&");return e.replace(new RegExp("("+t+")","ig"),function(e,t){return"<strong>"+t+"</strong>"})},render:function(t){var n=this;return t=e(t).map(function(t,r){return t=e(n.options.item).attr("data-value",r),t.find("a").html(n.highlighter(r)),t[0]}),t.first().addClass("active"),this.$menu.html(t),this},next:function(t){var n=this.$menu.find(".active").removeClass("active"),r=n.next();r.length||(r=e(this.$menu.find("li")[0])),r.addClass("active")},prev:function(e){var t=this.$menu.find(".active").removeClass("active"),n=t.prev();n.length||(n=this.$menu.find("li").last()),n.addClass("active")},listen:function(){this.$element.on("blur",e.proxy(this.blur,this)).on("keypress",e.proxy(this.keypress,this)).on("keyup",e.proxy(this.keyup,this)),(e.browser.webkit||e.browser.msie)&&this.$element.on("keydown",e.proxy(this.keydown,this)),this.$menu.on("click",e.proxy(this.click,this)).on("mouseenter","li",e.proxy(this.mouseenter,this))},move:function(e){if(!this.shown)return;switch(e.keyCode){case 9:case 13:case 27:e.preventDefault();break;case 38:e.preventDefault(),this.prev();break;case 40:e.preventDefault(),this.next()}e.stopPropagation()},keydown:function(t){this.suppressKeyPressRepeat=!~e.inArray(t.keyCode,[40,38,9,13,27]),this.move(t)},keypress:function(e){if(this.suppressKeyPressRepeat)return;this.move(e)},keyup:function(e){switch(e.keyCode){case 40:case 38:break;case 9:case 13:if(!this.shown)return;this.select();break;case 27:if(!this.shown)return;this.hide();break;default:this.lookup()}e.stopPropagation(),e.preventDefault()},blur:function(e){var t=this;setTimeout(function(){t.hide()},150)},click:function(e){e.stopPropagation(),e.preventDefault(),this.select()},mouseenter:function(t){this.$menu.find(".active").removeClass("active"),e(t.currentTarget).addClass("active")}},e.fn.typeahead=function(n){return this.each(function(){var r=e(this),i=r.data("typeahead"),s=typeof n=="object"&&n;i||r.data("typeahead",i=new t(this,s)),typeof n=="string"&&i[n]()})},e.fn.typeahead.defaults={source:[],items:8,menu:'<ul class="typeahead dropdown-menu"></ul>',item:'<li><a href="#"></a></li>',minLength:1},e.fn.typeahead.Constructor=t,e(function(){e("body").on("focus.typeahead.data-api",'[data-provide="typeahead"]',function(t){var n=e(this);if(n.data("typeahead"))return;t.preventDefault(),n.typeahead(n.data())})})}(window.jQuery),define("bootstrap",["jquery"],function(){}),window.screenLock=!1,window.screenScale=null,window.bar_height=50;var get_window_size=function(){var e=window,t=document,n=t.documentElement,r=t.getElementsByTagName("body")[0],i=e.innerWidth||n.clientWidth||r.clientWidth,s=e.innerHeight||n.clientHeight||r.clientHeight;return{x:i,y:s-bar_height}},recover_screen=function(){document.querySelectorAll(".reveal")[0].style.zoom=1,document.querySelectorAll(".reveal")[0].style.MozTransform="scale(1)"};window.screenSizeLock=function(){recover_screen(),window.screenLock=!0},window.screenSizeRelease=function(){window.screenLock=!1,adjust_screen()},$.presentate=function(e){return $("body").append("<div class='presentate_area'></div>"),this.can_resize=e==undefined?!1:e,this.render(),this},$.presentate.prototype={render:function(){$(".reveal .progress").remove();if(this.get_user_agent()=="mobile"){window.bar_height=0,this.reder_for_mobile();return}window.bar_height=50,this.share_overlay=$(_.template(this.template.share_overlay,{url:location.href,player:"<iframe width=800 height=600 src='"+location.href+"?embed=1"+"'></iframe>",qrcode:"http://api.qrserver.com/v1/create-qr-code/?size=140x140&data="+escape(location.href)})).appendTo($(".presentate_area")),this.progress=$(_.template(this.template.progress_bar,{})).appendTo($(".presentate_area")),this.control=$(_.template(this.template.controls_bar,{})).appendTo($(".presentate_area")),this.wait=$(_.template(this.template.loading,{})).appendTo($(".presentate_area")),this.site=this.control.find("div#epub360 a").tooltip(),this.actualsize=this.control.find(".actualsize").tooltip(),this.adaptive=this.control.find(".adaptive").tooltip(),this.fullscreen=this.control.find(".fullscreen").tooltip(),this.over=this.control.find(".overview").tooltip(),this.navigation=this.control.find(".navigation").tooltip(),screenfull.enabled||this.fullscreen.remove(),this.total=0,this.state="adaptive",this.click_event_name=this.hasTouch()?"touchstart":"click",this.size_share_overlay(),this.delegate_event()},reder_for_mobile:function(){var e=this;this.over=$(_.template(this.mobile_template.overview,{})).appendTo($(".presentate_area")).tooltip(),this.progress=$(_.template(this.mobile_template.progress_bar,{})).appendTo($(".presentate_area")),this.wait=$(_.template(this.template.loading,{})).appendTo($(".presentate_area")),Reveal.addEventListener("ready",function(){e.wait.hide(),e.get_slides_num(),Reveal.addEventListener("overviewhidden",function(){$(".reveal .controls").addClass("slideoverview")})}),this.over.on("touchstart",function(e){Reveal.toggleOverview(),$(".reveal .controls").addClass("slideoverview")})},size_share_overlay:function(){var e=this.share_overlay.children();$("html").width()>=600&&$("html").height()>=460?(e.width(560),e.height(220),e.find("#small_share").hide(),e.find("#normal_share").show()):(e.width($("html").width()/2),e.height($("html").height()/2),e.find("#small_share").show(),e.find("#normal_share").hide()),e.css("margin-top",-e.height()/2),e.css("margin-left",-e.width()/2)},delegate_event:function(){var e=this;this.share_overlay.on(e.click_event_name,function(t){t.target==$(this)[0]&&e.share_overlay.hide()}),this.share_overlay.find(".btn-close").on(e.click_event_name,function(){e.share_overlay.hide()}),this.share_overlay.find("input").mouseenter(function(){$(this).select()}),Reveal.addEventListener("ready",function(){e.wait.hide(),$("body").height($("html").height()-50),e.get_slides_num();var t=$(".reveal .slides").width(),n=$(".reveal .slides").height();$(".reveal").width()>t&&$(".reveal").height()>n&&(e.actualsize.trigger(e.click_event_name),e.state="actualsize"),Reveal.addEventListener("overviewhidden",function(){e.over.removeClass("active"),e.navigation.hasClass("active")&&$(".reveal .controls").addClass("slideoverview")}),Reveal.addEventListener("overviewshown",function(){e.over.addClass("active"),e.actualsize.parent().children().removeClass("active"),screenSizeRelease()})}),this.can_resize&&$(window).resize(function(){(screenfull.enabled&&!screenfull.isFullscreen||!screenfull.enabled)&&$("body").height($("html").height()-50)}),this.fullscreen.on(e.click_event_name,function(){window.bar_height=0,e.control.hide(),$(".reveal .progress").remove(),e.progress.css("bottom","0px").show(),$("body").css("height","100%"),screenfull.request($("body")[0]),$(document).on(screenfull.raw.fullscreenchange,function(){screenfull.isFullscreen||(window.bar_height=50,e.progress.css("bottom","50px"),e.control.show(),$("body").height($("html").height()-50),adjust_screen&&adjust_screen())})}),this.actualsize.on(e.click_event_name,function(){if($(this).hasClass("active"))return;e.over.hasClass("active")&&Reveal.toggleOverview(!1),e.state="actualsize",$(this).siblings().removeClass("active"),$(this).addClass("active"),screenSizeLock()}),this.adaptive.on(e.click_event_name,function(){if($(this).hasClass("active"))return;e.over.hasClass("active")&&Reveal.toggleOverview(!1),e.state="adaptive",$(this).siblings().removeClass("active"),$(this).addClass("active"),screenSizeRelease()}),this.over.on(e.click_event_name,function(t){$(this).hasClass("active")?e.control.find("."+e.state).trigger(e.click_event_name):(e.adaptive.parent().children().removeClass("active"),Reveal.toggleOverview(!0),e.navigation.addClass("active"))}),this.navigation.on(e.click_event_name,function(e){$(this).toggleClass("active"),$(".reveal .controls").toggleClass("slideoverview")})},hasTouch:function(){try{return document.createEvent("TouchEvent"),!0}catch(e){return!1}},get_user_agent:function(){var e=navigator.userAgent.toLowerCase();return e.match("iphone")=="iphone"||e.match("android")=="android"?"mobile":"computer"},get_slides_num:function(){var e=this;$(".reveal .controls").css({position:"absolute",bottom:"10px"}).addClass("slideoverview"),$(".reveal .slides>*").children()[0].tagName.toLowerCase()=="section"?e.total=$(".reveal .slides>*").children().length:e.total=$(".reveal .slides").children().length,Reveal.addEventListener("slidechanged",function(){var t=0;$(".reveal .slides>*").children()[0].tagName.toLowerCase()=="section"?t=$(".reveal section.group.past").children().length+$(".reveal section.group.present").children(".past").length:t=$(".reveal section.past").length,e.progress.find("span").css("width",100*t/(e.total-1)+"%")})},template:{share_overlay:['<div class="share-overlay">',' <div class="share-overlay-content">',' <button class="btn-close">×</button>',' <div id="normal_share" style="margin:30px;width: 500px;height: 220px;">',' <h5 style="color:#f80;margin-bottom: 10px;">分享给站外好友:</h5>',' <div class="control-group">',' <label for="inc_http" class="control-label" style="color: white; width: auto; padding-left: 30px;float:left;font-family: \'microsoft yahei\', tahoma, arial, sans-serif;font-size: 14px;">地址:</label>',' <div class="controls" style="margin-left: 110px;">',' <input type="text" value="<%=url%>" id="inc_http" style="width:360px;font-family: \'microsoft yahei\', tahoma, arial, sans-serif;font-size: 14px;">'," </div>"," </div>",' <h5 style="color:#f80; margin-top: 30px;margin-bottom: 10px;">把内容贴到Blog或BBS:</h5>',' <div class="control-group">',' <label for="inc_html" class="control-label" style="color: white; width: auto; padding-left: 30px;float:left;font-family: \'microsoft yahei\', tahoma, arial, sans-serif;font-size: 14px;">通用代码:</label>',' <div class="controls" style="margin-left: 110px;">',' <input type="text" value="<%=player%>" id="inc_html" style="width:360px;font-family: \'microsoft yahei\', tahoma, arial, sans-serif;font-size: 14px;">'," </div>"," </div>"," </div>",' <div id="small_share" style="position:absolute; display: none; width:100%; height:100%">',' <table style="width:100%; height:100%">',' <tr style="height:30%"><td style="text-align: center;">'," </td></tr>",' <tr style="height:20px"><td style="text-align: center;">',' <lable for="copylink" style="color: white; width: auto; font-size: 14px;font-family: \'microsoft yahei\', tahoma, arial, sans-serif;">鼠标移入,按下Ctrl+C复制地址:</label>'," </td></tr>",' <tr><td style="text-align: center;">',' <input type="text" value="<%=url%>" id="copylink" style="width: 80%;font-size: 14px;font-family: \'microsoft yahei\', tahoma, arial, sans-serif;"/>'," </td></tr>",' <tr style="height:20%"><td style="text-align: center;">'," </td></tr>"," </table>"," </div>"," </div>","</div>"].join(""),progress_bar:['<div class="progress" style="bottom:50px;">',' <span style=""></span>',"</div>"].join(""),controls_bar:['<div class="controlbar">',' <div style="position:absolute; left: 50px; top: 8px; width:100px; height:30px;" id="epub360" >',' <a href="http://www.epub360.com" target="_blank" rel="tooltip" data-original-title="EPub360--交互内容设计利器"><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFcAAAAaCAYAAADCDsDeAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyRpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMy1jMDExIDY2LjE0NTY2MSwgMjAxMi8wMi8wNi0xNDo1NjoyNyAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNiAoTWFjaW50b3NoKSIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDpBQjY2MTk2OTUwRDgxMUUzOUVEODgyQjY1Qzk0MUVEMyIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDpBQjY2MTk2QTUwRDgxMUUzOUVEODgyQjY1Qzk0MUVEMyI+IDx4bXBNTTpEZXJpdmVkRnJvbSBzdFJlZjppbnN0YW5jZUlEPSJ4bXAuaWlkOkFCNjYxOTY3NTBEODExRTM5RUQ4ODJCNjVDOTQxRUQzIiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOkFCNjYxOTY4NTBEODExRTM5RUQ4ODJCNjVDOTQxRUQzIi8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+usLItgAAClRJREFUeNrsWHlIVPsXv3PnzuLMOKNOmrtmz9R6vpep9dqLomiXoqSFoijbow2C/miDQqigoohWoqKilaKixaANsn1fXdOyLHdtnHFm7vw+Z/peuc7PzKzgwfMLR+/c73a+53vO53zO5TiP1qVLF43L5YqHdIa0g+htNhun1Wq51vZjjW/ivQpihISp1erQzZs3a1rN9ZMtISFBwbzVDxIhimICfifX1dXFFxUV+aanp7caqaVNo9FwsbGxfHR0tCIgIIA7deqUqqysjIycBCMnHD9+3K/VSi1swFw1jBgNiYL4Tp8+3Q0dmZmZAfhNBv5r9+7d+lZLtcy4KhiwA0EB5B9I+5kzZ6rCwsI4PAdBelCiGzdunKLVWk03pfQwb948bsiQIdywYcNEq9VakZGRUdO5c2fqN+O9uqqqqiwvL68OmExea9TpdNUXLlyoq62tbbViU2327NlqJKwQBgfRjx8/Dr548aKAZ5I4SNcXL174wqvJewMhvSBtk5KSmrU+jTt//rz+7Nmzuo4dO/53DHv16lVtaWkp4WtXSDcm9Bw9f/585ZUrV8x4ToTXRtH4tWvX+jJoCIfRmgUNKSkpxEAiKSHm5+f7BQYGNjpu7969HC7WePv27WBIUHZ2tmHChAn1/ZcvX+bv3r1rRl8IJDArK0uTnJzs7mvTpg338OFDAe/9IaGQgEePHgmUlL/V4EBKrKd/8+aNZtGiRQ36zGYz9+DBAy3WMeTk5AhDhw6t7wsKCiI9efTpoaMuMTGR37ZtG4f9vJ49e6bftGnTV0TAgWNYwZBUXV3d7suXL1Q4JJKRP3z44P/582cVKFnoy5cv29L41NRULfoiIGZ4cnONS0kyll1KSFRU1P/N27p1K+lC0ZPA9ifpAvEnA4K18IT/7F2SlFwBYd5Yj3v9+jUVP51k/TQ/DpepFgShwV579uzhampq/J1O519sP5rzR1pampr6r1+/rgRDimJ9JH9TpPbu3Vvh5eXFvXv3zpvt5Z5bUlISCxvFSr+hUzzG+NGuBrZnLW4/v1OnTsL9+/epHCMP0/Xv378E3v2OBtDCr169svr7+7/Fgi0JFJGJy7PDz8+P9DCzPFDFChkqYgJRHVZBN+o3sbkVENJRD+oYqFKpLNCJLp/ygRXyhZ3LAM8NUCgU7zz30uv1waxQsrE92+zYscMGjyzEOYN80ZiuDggZPRx2oARTzfN8BNvfzrxcsiGNdUInbUhISKBUoZEnOcFlOZH+fFXQQoO//uQ43JoS2GyA6/ts2LDB2KtXL8FoNHJQnBs8eLAaYho5cqQ+IiLCvWbPnj31w4cPNwFjdQ6HQ25MZZ8+fYRBgwbx3bp1k5/ZCyLAm+zA5zf37t17yw7uxYxA/3lEV83Jkyez4alFpDNEx4xD/0VEW+mxY8dy6D9bV9fIJdOlqaDXl3Pnzj1D+EvGN3Tv3l1lMpmoXwG4/Ag9nuO5knSDUfUQMiRVq3W5ublv4Gw59EzjkbcKbt68+QrPNe59WfhQGMWCAfCEUatWrRLWrVun3b9/vwrG4iZOnKjCoduzcT0YLsesX7/eiy4YSgazJBe/cOFCd5kM7KFE2BO3/Wffvn15BguE5X9SCBKdQ8UX0KNHD3fMHjp0iBJlV4Tr3/R7wIABWjb2H1ys4caNG6G0/5MnT9pT/+LFi30ZXUyMiYlRI4xpv0Ss44avAwcOkE7JFoulAzy7gWUBMWHUV15e7s4jYEhGdi76plIPL5cuXTJBD7JROOunNX2YHTrCRvyCBQuIunYk3YuLizVxcXE8qxGS5WDEA4i18AwRCrmwsB2Gcc6dO5fbuHFjKG7MzDylhnmS79KlS7mdO3dmw7udSqXSzsKCk4WI9E7CWBfzJG+WGERUfBoYvxD7UigXS6EmiyjXNyCGousT6xc95nyvuTzWdTIoqvV4r2hCD4VMPL/VuN8Jss00M2bMiJJCF0mgCMb9jGJBCQyhMBGfP39eNmbMmMKVK1e2HT9+fBCFF5KDyjNhfOdDUTk7CK3pAwObR48eXQ6Prx44cKADyUmPUDUjgnQs/GzyC4qMjFSfOHHCD7mBDPoeWd6BbK+Ad7a4qLlz507tqFGjsj5+/Chu377d0dxE/SNfxXiGa14ynJMXGq6KiopaYJ0DWGNht01YzBPuNrPRwBoUJR9RlBSyS6XL01AxAmZCxgwB7YkEzQtge1cwL3V7j7e3tw6XEQkoIEdoD3jQhoaGugBNLTYC9hXPnDljg5HtSNSu3/HJ0QrMyH7//n0WjPgKYF76u7g1ChIO1Z/DI7w47O0ADtd++vSplsGDBCMqKSyRNJxQzcp+m1CWByFXKIFxLu5f1gQ5W4iOjq602+0i0THymg4dOijhKb9lY/Dp+mfsSR6pSE9PF5HQCiorK623bt3ShYeHxzB6pZb0BE2snjZtWg6yuBl0Korht/JndPHx8VHizBo4lwimYPvVxv3qularC5sooXgo7ckSTFkjYO5qItH8cEMoOtesWWMG7kbB6DaDwfAYBhQzMjLsDHfrEwr6iGtzK1ascCDROpv44N/sRrQRpXkcS9bZv+psvCzbyTOdxsNj3A0sgm6WAyYqZXMbKALPIxzmEK7fAmIXJUCU1o0VGA6PzM81wQKaywoUzRzb1DjxB9Zp4Lk29l8LbugP4ylY9SEyclx/WBQEPqdPnxYSEhJMzLh2JBQH+G4dqBgN0U6dOtUflV0tCgwtO5y0hlOKwi1bttShiNDLqxopGpDbVNDDNzg4WM0u2S4zPF2aFpWUN0piI4ODOjaX+nnwZgPqfAOKHCL7CiQ6B3F37KlB5SXA4y2AHTeeA6v1+/bt8wYDMUq6gAk5p0yZIoK18PHx8ably5dLhYpLpmezjVsAoVLQOzU1NYxNpveWJUuWVI4YMULs16+f+2ZR0hkhJtn8ooMHD9rz8vJqQMwppPQ4XIAsEkiZElnJSnMNIO1aZhgFK1VrJGSCVxsmTZrUjs2hRPaZsQVaqy3w0SstLe0PWeSUsgugfUwoekxz5swxsPVd4OAlgBIeDIOgznj48OE8wB/N8Ver1V4wZHu2Fu1XCX7vwJlLiBLCSdpAfJge1smTJ1cBvgRcRvNgATSq8ujRo2TgKinj4rLpsPngtRYwh/pkQaUpyL4FoU+GykHJ+wk0hqoxOlyuzWarlOG3tbCwMD8lJaXq2rVr3OrVq8lIBViDIoWqGLfhjxw58nbXrl0u8FUXklge+kuxvosE/R/gaQWozkSU1jawiRxAUzX6FBDas3Ds2LHFoIccCpFyMIk8vLdBlBArEmUuLrsSc6jKonMIuBxh1qxZDiTGfPRXYBwPIa8vWLZsWXFmZibBXgkYSyHwvw59AoQcIOfp06cWIlE4p/sbCfZzJ2N6JsikJM0+F1Bi/hrxxFNRgXFIZCrU5CqEUL31YRg1+yqUiLrZ/a2QxpJ4NpTJHDYXYAQ1mEYDfJK4MEpqBeiWGusK8vfydeXys/2efdL4lq7lOV6yXWNjvtsaM25r+/EiorX94vY/AQYATDX9g6EDmtEAAAAASUVORK5CYII=" /></a>'," </div>",' <button class="btn overview" href="#" rel="tooltip" data-original-title="缩略图" style="position:absolute; right:100px; top: 7px;">',' <i class="im-overview icon-more"></i>'," </button>",' <div class="btn-group" style="position:absolute; right:250px; top: 7px;">',' <button class="btn actualsize" href="#" rel="tooltip" data-original-title="1:1比例">',' <i class="im-actualsize icon-more"></i>'," </button>",' <button class="btn adaptive active" href="#" rel="tooltip" data-original-title="自适应">',' <i class="im-adaptive icon-more"></i>'," </button>",' <button class="btn fullscreen" href="#" rel="tooltip" data-original-title="全屏">',' <i class="im-fullscreen icon-more"></i>'," </button>"," </div>",' <button class="btn navigation active" href="#" rel="tooltip" data-original-title="导航栏" style="position:absolute; right:50px; top: 7px;">',' <i class="im-controls icon-more"></i>'," </button>","</div>"].join(""),loading:['<div class="player-wait" style="position: absolute; width: 100%; height:100%; top: 0; left: 0; z-index: 9999; background-position: initial initial; background-repeat: initial initial;">',' <div style="position: absolute; top: 50%; left: 50%; margin-top:-16px; margin-left:-16px; width:32px; height:32px; background:url(/staticfs/common/js/play/img/ajax-loader.gif) no-repeat 50% 50%;"></div>',"</div>"].join("")},mobile_template:{overview:'<i class="im-overview icon-more" style="position:absolute; bottom: 15px; left: 15px;"></i>',progress_bar:['<div class="progress" style="bottom: 0px;">',' <span style=""></span>',"</div>"].join("")}},define("interaction_play/presentate",["bootstrap"],function(){}),function(){var e=this,t=e._,n={},r=Array.prototype,i=Object.prototype,s=Function.prototype,o=r.push,u=r.slice,a=r.concat,f=i.toString,l=i.hasOwnProperty,c=r.forEach,h=r.map,p=r.reduce,d=r.reduceRight,v=r.filter,m=r.every,g=r.some,y=r.indexOf,b=r.lastIndexOf,w=Array.isArray,E=Object.keys,S=s.bind,x=function(e){return e instanceof x?e:this instanceof x?(this._wrapped=e,void 0):new x(e)};"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=x),exports._=x):e._=x,x.VERSION="1.4.4";var T=x.each=x.forEach=function(e,t,r){if(null!=e)if(c&&e.forEach===c)e.forEach(t,r);else if(e.length===+e.length){for(var i=0,s=e.length;s>i;i++)if(t.call(r,e[i],i,e)===n)return}else for(var o in e)if(x.has(e,o)&&t.call(r,e[o],o,e)===n)return};x.map=x.collect=function(e,t,n){var r=[];return null==e?r:h&&e.map===h?e.map(t,n):(T(e,function(e,i,s){r[r.length]=t.call(n,e,i,s)}),r)};var N="Reduce of empty array with no initial value";x.reduce=x.foldl=x.inject=function(e,t,n,r){var i=arguments.length>2;if(null==e&&(e=[]),p&&e.reduce===p)return r&&(t=x.bind(t,r)),i?e.reduce(t,n):e.reduce(t);if(T(e,function(e,s,o){i?n=t.call(r,n,e,s,o):(n=e,i=!0)}),!i)throw new TypeError(N);return n},x.reduceRight=x.foldr=function(e,t,n,r){var i=arguments.length>2;if(null==e&&(e=[]),d&&e.reduceRight===d)return r&&(t=x.bind(t,r)),i?e.reduceRight(t,n):e.reduceRight(t);var s=e.length;if(s!==+s){var o=x.keys(e);s=o.length}if(T(e,function(u,a,f){a=o?o[--s]:--s,i?n=t.call(r,n,e[a],a,f):(n=e[a],i=!0)}),!i)throw new TypeError(N);return n},x.find=x.detect=function(e,t,n){var r;return C(e,function(e,i,s){return t.call(n,e,i,s)?(r=e,!0):void 0}),r},x.filter=x.select=function(e,t,n){var r=[];return null==e?r:v&&e.filter===v?e.filter(t,n):(T(e,function(e,i,s){t.call(n,e,i,s)&&(r[r.length]=e)}),r)},x.reject=function(e,t,n){return x.filter(e,function(e,r,i){return!t.call(n,e,r,i)},n)},x.every=x.all=function(e,t,r){t||(t=x.identity);var i=!0;return null==e?i:m&&e.every===m?e.every(t,r):(T(e,function(e,s,o){return(i=i&&t.call(r,e,s,o))?void 0:n}),!!i)};var C=x.some=x.any=function(e,t,r){t||(t=x.identity);var i=!1;return null==e?i:g&&e.some===g?e.some(t,r):(T(e,function(e,s,o){return i||(i=t.call(r,e,s,o))?n:void 0}),!!i)};x.contains=x.include=function(e,t){return null==e?!1:y&&e.indexOf===y?e.indexOf(t)!=-1:C(e,function(e){return e===t})},x.invoke=function(e,t){var n=u.call(arguments,2),r=x.isFunction(t);return x.map(e,function(e){return(r?t:e[t]).apply(e,n)})},x.pluck=function(e,t){return x.map(e,function(e){return e[t]})},x.where=function(e,t,n){return x.isEmpty(t)?n?null:[]:x[n?"find":"filter"](e,function(e){for(var n in t)if(t[n]!==e[n])return!1;return!0})},x.findWhere=function(e,t){return x.where(e,t,!0)},x.max=function(e,t,n){if(!t&&x.isArray(e)&&e[0]===+e[0]&&65535>e.length)return Math.max.apply(Math,e);if(!t&&x.isEmpty(e))return-1/0;var r={computed:-1/0,value:-1/0};return T(e,function(e,i,s){var o=t?t.call(n,e,i,s):e;o>=r.computed&&(r={value:e,computed:o})}),r.value},x.min=function(e,t,n){if(!t&&x.isArray(e)&&e[0]===+e[0]&&65535>e.length)return Math.min.apply(Math,e);if(!t&&x.isEmpty(e))return 1/0;var r={computed:1/0,value:1/0};return T(e,function(e,i,s){var o=t?t.call(n,e,i,s):e;r.computed>o&&(r={value:e,computed:o})}),r.value},x.shuffle=function(e){var t,n=0,r=[];return T(e,function(e){t=x.random(n++),r[n-1]=r[t],r[t]=e}),r};var k=function(e){return x.isFunction(e)?e:function(t){return t[e]}};x.sortBy=function(e,t,n){var r=k(t);return x.pluck(x.map(e,function(e,t,i){return{value:e,index:t,criteria:r.call(n,e,t,i)}}).sort(function(e,t){var n=e.criteria,r=t.criteria;if(n!==r){if(n>r||n===void 0)return 1;if(r>n||r===void 0)return-1}return e.index<t.index?-1:1}),"value")};var L=function(e,t,n,r){var i={},s=k(t||x.identity);return T(e,function(t,o){var u=s.call(n,t,o,e);r(i,u,t)}),i};x.groupBy=function(e,t,n){return L(e,t,n,function(e,t,n){(x.has(e,t)?e[t]:e[t]=[]).push(n)})},x.countBy=function(e,t,n){return L(e,t,n,function(e,t){x.has(e,t)||(e[t]=0),e[t]++})},x.sortedIndex=function(e,t,n,r){n=null==n?x.identity:k(n);for(var i=n.call(r,t),s=0,o=e.length;o>s;){var u=s+o>>>1;i>n.call(r,e[u])?s=u+1:o=u}return s},x.toArray=function(e){return e?x.isArray(e)?u.call(e):e.length===+e.length?x.map(e,x.identity):x.values(e):[]},x.size=function(e){return null==e?0:e.length===+e.length?e.length:x.keys(e).length},x.first=x.head=x.take=function(e,t,n){return null==e?void 0:null==t||n?e[0]:u.call(e,0,t)},x.initial=function(e,t,n){return u.call(e,0,e.length-(null==t||n?1:t))},x.last=function(e,t,n){return null==e?void 0:null==t||n?e[e.length-1]:u.call(e,Math.max(e.length-t,0))},x.rest=x.tail=x.drop=function(e,t,n){return u.call(e,null==t||n?1:t)},x.compact=function(e){return x.filter(e,x.identity)};var A=function(e,t,n){return T(e,function(e){x.isArray(e)?t?o.apply(n,e):A(e,t,n):n.push(e)}),n};x.flatten=function(e,t){return A(e,t,[])},x.without=function(e){return x.difference(e,u.call(arguments,1))},x.uniq=x.unique=function(e,t,n,r){x.isFunction(t)&&(r=n,n=t,t=!1);var i=n?x.map(e,n,r):e,s=[],o=[];return T(i,function(n,r){(t?r&&o[o.length-1]===n:x.contains(o,n))||(o.push(n),s.push(e[r]))}),s},x.union=function(){return x.uniq(a.apply(r,arguments))},x.intersection=function(e){var t=u.call(arguments,1);return x.filter(x.uniq(e),function(e){return x.every(t,function(t){return x.indexOf(t,e)>=0})})},x.difference=function(e){var t=a.apply(r,u.call(arguments,1));return x.filter(e,function(e){return!x.contains(t,e)})},x.zip=function(){for(var e=u.call(arguments),t=x.max(x.pluck(e,"length")),n=Array(t),r=0;t>r;r++)n[r]=x.pluck(e,""+r);return n},x.object=function(e,t){if(null==e)return{};for(var n={},r=0,i=e.length;i>r;r++)t?n[e[r]]=t[r]:n[e[r][0]]=e[r][1];return n},x.indexOf=function(e,t,n){if(null==e)return-1;var r=0,i=e.length;if(n){if("number"!=typeof n)return r=x.sortedIndex(e,t),e[r]===t?r:-1;r=0>n?Math.max(0,i+n):n}if(y&&e.indexOf===y)return e.indexOf(t,n);for(;i>r;r++)if(e[r]===t)return r;return-1},x.lastIndexOf=function(e,t,n){if(null==e)return-1;var r=null!=n;if(b&&e.lastIndexOf===b)return r?e.lastIndexOf(t,n):e.lastIndexOf(t);for(var i=r?n:e.length;i--;)if(e[i]===t)return i;return-1},x.range=function(e,t,n){1>=arguments.length&&(t=e||0,e=0),n=arguments[2]||1;for(var r=Math.max(Math.ceil((t-e)/n),0),i=0,s=Array(r);r>i;)s[i++]=e,e+=n;return s},x.bind=function(e,t){if(e.bind===S&&S)return S.apply(e,u.call(arguments,1));var n=u.call(arguments,2);return function(){return e.apply(t,n.concat(u.call(arguments)))}},x.partial=function(e){var t=u.call(arguments,1);return function(){return e.apply(this,t.concat(u.call(arguments)))}},x.bindAll=function(e){var t=u.call(arguments,1);return 0===t.length&&(t=x.functions(e)),T(t,function(t){e[t]=x.bind(e[t],e)}),e},x.memoize=function(e,t){var n={};return t||(t=x.identity),function(){var r=t.apply(this,arguments);return x.has(n,r)?n[r]:n[r]=e.apply(this,arguments)}},x.delay=function(e,t){var n=u.call(arguments,2);return setTimeout(function(){return e.apply(null,n)},t)},x.defer=function(e){return x.delay.apply(x,[e,1].concat(u.call(arguments,1)))},x.throttle=function(e,t){var n,r,i,s,o=0,u=function(){o=new Date,i=null,s=e.apply(n,r)};return function(){var a=new Date,f=t-(a-o);return n=this,r=arguments,0>=f?(clearTimeout(i),i=null,o=a,s=e.apply(n,r)):i||(i=setTimeout(u,f)),s}},x.debounce=function(e,t,n){var r,i;return function(){var s=this,o=arguments,u=function(){r=null,n||(i=e.apply(s,o))},a=n&&!r;return clearTimeout(r),r=setTimeout(u,t),a&&(i=e.apply(s,o)),i}},x.once=function(e){var t,n=!1;return function(){return n?t:(n=!0,t=e.apply(this,arguments),e=null,t)}},x.wrap=function(e,t){return function(){var n=[e];return o.apply(n,arguments),t.apply(this,n)}},x.compose=function(){var e=arguments;return function(){for(var t=arguments,n=e.length-1;n>=0;n--)t=[e[n].apply(this,t)];return t[0]}},x.after=function(e,t){return 0>=e?t():function(){return 1>--e?t.apply(this,arguments):void 0}},x.keys=E||function(e){if(e!==Object(e))throw new TypeError("Invalid object");var t=[];for(var n in e)x.has(e,n)&&(t[t.length]=n);return t},x.values=function(e){var t=[];for(var n in e)x.has(e,n)&&t.push(e[n]);return t},x.pairs=function(e){var t=[];for(var n in e)x.has(e,n)&&t.push([n,e[n]]);return t},x.invert=function(e){var t={};for(var n in e)x.has(e,n)&&(t[e[n]]=n);return t},x.functions=x.methods=function(e){var t=[];for(var n in e)x.isFunction(e[n])&&t.push(n);return t.sort()},x.extend=function(e){return T(u.call(arguments,1),function(t){if(t)for(var n in t)e[n]=t[n]}),e},x.pick=function(e){var t={},n=a.apply(r,u.call(arguments,1));return T(n,function(n){n in e&&(t[n]=e[n])}),t},x.omit=function(e){var t={},n=a.apply(r,u.call(arguments,1));for(var i in e)x.contains(n,i)||(t[i]=e[i]);return t},x.defaults=function(e){return T(u.call(arguments,1),function(t){if(t)for(var n in t)null==e[n]&&(e[n]=t[n])}),e},x.clone=function(e){return x.isObject(e)?x.isArray(e)?e.slice():x.extend({},e):e},x.tap=function(e,t){return t(e),e};var O=function(e,t,n,r){if(e===t)return 0!==e||1/e==1/t;if(null==e||null==t)return e===t;e instanceof x&&(e=e._wrapped),t instanceof x&&(t=t._wrapped);var i=f.call(e);if(i!=f.call(t))return!1;switch(i){case"[object String]":return e==t+"";case"[object Number]":return e!=+e?t!=+t:0==e?1/e==1/t:e==+t;case"[object Date]":case"[object Boolean]":return+e==+t;case"[object RegExp]":return e.source==t.source&&e.global==t.global&&e.multiline==t.multiline&&e.ignoreCase==t.ignoreCase}if("object"!=typeof e||"object"!=typeof t)return!1;for(var s=n.length;s--;)if(n[s]==e)return r[s]==t;n.push(e),r.push(t);var o=0,u=!0;if("[object Array]"==i){if(o=e.length,u=o==t.length)for(;o--&&(u=O(e[o],t[o],n,r)););}else{var a=e.constructor,l=t.constructor;if(a!==l&&!(x.isFunction(a)&&a instanceof a&&x.isFunction(l)&&l instanceof l))return!1;for(var c in e)if(x.has(e,c)&&(o++,!(u=x.has(t,c)&&O(e[c],t[c],n,r))))break;if(u){for(c in t)if(x.has(t,c)&&!(o--))break;u=!o}}return n.pop(),r.pop(),u};x.isEqual=function(e,t){return O(e,t,[],[])},x.isEmpty=function(e){if(null==e)return!0;if(x.isArray(e)||x.isString(e))return 0===e.length;for(var t in e)if(x.has(e,t))return!1;return!0},x.isElement=function(e){return!!e&&1===e.nodeType},x.isArray=w||function(e){return"[object Array]"==f.call(e)},x.isObject=function(e){return e===Object(e)},T(["Arguments","Function","String","Number","Date","RegExp"],function(e){x["is"+e]=function(t){return f.call(t)=="[object "+e+"]"}}),x.isArguments(arguments)||(x.isArguments=function(e){return!!e&&!!x.has(e,"callee")}),"function"!=typeof /./&&(x.isFunction=function(e){return"function"==typeof e}),x.isFinite=function(e){return isFinite(e)&&!isNaN(parseFloat(e))},x.isNaN=function(e){return x.isNumber(e)&&e!=+e},x.isBoolean=function(e){return e===!0||e===!1||"[object Boolean]"==f.call(e)},x.isNull=function(e){return null===e},x.isUndefined=function(e){return e===void 0},x.has=function(e,t){return l.call(e,t)},x.noConflict=function(){return e._=t,this},x.identity=function(e){return e},x.times=function(e,t,n){for(var r=Array(e),i=0;e>i;i++)r[i]=t.call(n,i);return r},x.random=function(e,t){return null==t&&(t=e,e=0),e+Math.floor(Math.random()*(t-e+1))};var M={escape:{"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","/":"&#x2F;"}};M.unescape=x.invert(M.escape);var _={escape:RegExp("["+x.keys(M.escape).join("")+"]","g"),unescape:RegExp("("+x.keys(M.unescape).join("|")+")","g")};x.each(["escape","unescape"],function(e){x[e]=function(t){return null==t?"":(""+t).replace(_[e],function(t){return M[e][t]})}}),x.result=function(e,t){if(null==e)return null;var n=e[t];return x.isFunction(n)?n.call(e):n},x.mixin=function(e){T(x.functions(e),function(t){var n=x[t]=e[t];x.prototype[t]=function(){var e=[this._wrapped];return o.apply(e,arguments),j.call(this,n.apply(x,e))}})};var D=0;x.uniqueId=function(e){var t=++D+"";return e?e+t:t},x.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var P=/(.)^/,H={"'":"'","\\":"\\","\r":"r","\n":"n"," ":"t","\u2028":"u2028","\u2029":"u2029"},B=/\\|'|\r|\n|\t|\u2028|\u2029/g;x.template=function(e,t,n){var r;n=x.defaults({},n,x.templateSettings);var i=RegExp([(n.escape||P).source,(n.interpolate||P).source,(n.evaluate||P).source].join("|")+"|$","g"),s=0,o="__p+='";e.replace(i,function(t,n,r,i,u){return o+=e.slice(s,u).replace(B,function(e){return"\\"+H[e]}),n&&(o+="'+\n((__t=("+n+"))==null?'':_.escape(__t))+\n'"),r&&(o+="'+\n((__t=("+r+"))==null?'':__t)+\n'"),i&&(o+="';\n"+i+"\n__p+='"),s=u+t.length,t}),o+="';\n",n.variable||(o="with(obj||{}){\n"+o+"}\n"),o="var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');};\n"+o+"return __p;\n";try{r=Function(n.variable||"obj","_",o)}catch(u){throw u.source=o,u}if(t)return r(t,x);var a=function(e){return r.call(this,e,x)};return a.source="function("+(n.variable||"obj")+"){\n"+o+"}",a},x.chain=function(e){return x(e).chain()};var j=function(e){return this._chain?x(e).chain():e};x.mixin(x),T(["pop","push","reverse","shift","sort","splice","unshift"],function(e){var t=r[e];x.prototype[e]=function(){var n=this._wrapped;return t.apply(n,arguments),"shift"!=e&&"splice"!=e||0!==n.length||delete n[0],j.call(this,n)}}),T(["concat","join","slice"],function(e){var t=r[e];x.prototype[e]=function(){return j.call(this,t.apply(this._wrapped,arguments))}}),x.extend(x.prototype,{chain:function(){return this._chain=!0,this},value:function(){return this._wrapped}})}.call(this),define("underscore",function(e){return function(){var t,n;return t||e._}}(this)),function(){var e=this,t=e.Backbone,n=[],r=n.push,i=n.slice,s=n.splice,o;o="undefined"!=typeof exports?exports:e.Backbone={},o.VERSION="0.9.10";var u=e._;!u&&"undefined"!=typeof require&&(u=require("underscore")),o.$=e.jQuery||e.Zepto||e.ender,o.noConflict=function(){return e.Backbone=t,this},o.emulateHTTP=!1,o.emulateJSON=!1;var a=/\s+/,f=function(e,t,n,r){if(!n)return!0;if("object"==typeof n)for(var i in n)e[t].apply(e,[i,n[i]].concat(r));else{if(!a.test(n))return!0;n=n.split(a),i=0;for(var s=n.length;i<s;i++)e[t].apply(e,[n[i]].concat(r))}},l=function(e,t){var n,r=-1,i=e.length;switch(t.length){case 0:for(;++r<i;)(n=e[r]).callback.call(n.ctx);break;case 1:for(;++r<i;)(n=e[r]).callback.call(n.ctx,t[0]);break;case 2:for(;++r<i;)(n=e[r]).callback.call(n.ctx,t[0],t[1]);break;case 3:for(;++r<i;)(n=e[r]).callback.call(n.ctx,t[0],t[1],t[2]);break;default:for(;++r<i;)(n=e[r]).callback.apply(n.ctx,t)}},n=o.Events={on:function(e,t,n){return!f(this,"on",e,[t,n])||!t?this:(this._events||(this._events={}),(this._events[e]||(this._events[e]=[])).push({callback:t,context:n,ctx:n||this}),this)},once:function(e,t,n){if(!f(this,"once",e,[t,n])||!t)return this;var r=this,i=u.once(function(){r.off(e,i),t.apply(this,arguments)});return i._callback=t,this.on(e,i,n),this},off:function(e,t,n){var r,i,s,o,a,l,c,h;if(!this._events||!f(this,"off",e,[t,n]))return this;if(!e&&!t&&!n)return this._events={},this;o=e?[e]:u.keys(this._events),a=0;for(l=o.length;a<l;a++)if(e=o[a],r=this._events[e]){s=[];if(t||n){c=0;for(h=r.length;c<h;c++)i=r[c],(t&&t!==i.callback&&t!==i.callback._callback||n&&n!==i.context)&&s.push(i)}this._events[e]=s}return this},trigger:function(e){if(!this._events)return this;var t=i.call(arguments,1);if(!f(this,"trigger",e,t))return this;var n=this._events[e],r=this._events.all;return n&&l(n,t),r&&l(r,arguments),this},listenTo:function(e,t,n){var r=this._listeners||(this._listeners={}),i=e._listenerId||(e._listenerId=u.uniqueId("l"));return r[i]=e,e.on(t,"object"==typeof t?this:n,this),this},stopListening:function(e,t,n){var r=this._listeners;if(r){if(e)e.off(t,"object"==typeof t?this:n,this),!t&&!n&&delete r[e._listenerId];else{"object"==typeof t&&(n=this);for(var i in r)r[i].off(t,n,this);this._listeners={}}return this}}};n.bind=n.on,n.unbind=n.off,u.extend(o,n);var c=o.Model=function(e,t){var n,r=e||{};this.cid=u.uniqueId("c"),this.attributes={},t&&t.collection&&(this.collection=t.collection),t&&t.parse&&(r=this.parse(r,t)||{});if(n=u.result(this,"defaults"))r=u.defaults({},r,n);this.set(r,t),this.changed={},this.initialize.apply(this,arguments)};u.extend(c.prototype,n,{changed:null,idAttribute:"id",initialize:function(){},toJSON:function(){return u.clone(this.attributes)},sync:function(){return o.sync.apply(this,arguments)},get:function(e){return this.attributes[e]},escape:function(e){return u.escape(this.get(e))},has:function(e){return null!=this.get(e)},set:function(e,t,n){var r,i,s,o,a,f,l;if(null==e)return this;"object"==typeof e?(i=e,n=t):(i={})[e]=t,n||(n={});if(!this._validate(i,n))return!1;s=n.unset,o=n.silent,e=[],a=this._changing,this._changing=!0,a||(this._previousAttributes=u.clone(this.attributes),this.changed={}),l=this.attributes,f=this._previousAttributes,this.idAttribute in i&&(this.id=i[this.idAttribute]);for(r in i)t=i[r],u.isEqual(l[r],t)||e.push(r),u.isEqual(f[r],t)?delete this.changed[r]:this.changed[r]=t,s?delete l[r]:l[r]=t;if(!o){e.length&&(this._pending=!0),t=0;for(r=e.length;t<r;t++)this.trigger("change:"+e[t],this,l[e[t]],n)}if(a)return this;if(!o)for(;this._pending;)this._pending=!1,this.trigger("change",this,n);return this._changing=this._pending=!1,this},unset:function(e,t){return this.set(e,void 0,u.extend({},t,{unset:!0}))},clear:function(e){var t={},n;for(n in this.attributes)t[n]=void 0;return this.set(t,u.extend({},e,{unset:!0}))},hasChanged:function(e){return null==e?!u.isEmpty(this.changed):u.has(this.changed,e)},changedAttributes:function(e){if(!e)return this.hasChanged()?u.clone(this.changed):!1;var t,n=!1,r=this._changing?this._previousAttributes:this.attributes,i;for(i in e)u.isEqual(r[i],t=e[i])||((n||(n={}))[i]=t);return n},previous:function(e){return null==e||!this._previousAttributes?null:this._previousAttributes[e]},previousAttributes:function(){return u.clone(this._previousAttributes)},fetch:function(e){e=e?u.clone(e):{},void 0===e.parse&&(e.parse=!0);var t=e.success;return e.success=function(e,n,r){if(!e.set(e.parse(n,r),r))return!1;t&&t(e,n,r)},this.sync("read",this,e)},save:function(e,t,n){var r,i,s=this.attributes;return null==e||"object"==typeof e?(r=e,n=t):(r={})[e]=t,r&&(!n||!n.wait)&&!this.set(r,n)?!1:(n=u.extend({validate:!0},n),this._validate(r,n)?(r&&n.wait&&(this.attributes=u.extend({},s,r)),void 0===n.parse&&(n.parse=!0),i=n.success,n.success=function(e,t,n){e.attributes=s;var o=e.parse(t,n);n.wait&&(o=u.extend(r||{},o));if(u.isObject(o)&&!e.set(o,n))return!1;i&&i(e,t,n)},e=this.isNew()?"create":n.patch?"patch":"update","patch"===e&&(n.attrs=r),e=this.sync(e,this,n),r&&n.wait&&(this.attributes=s),e):!1)},destroy:function(e){e=e?u.clone(e):{};var t=this,n=e.success,r=function(){t.trigger("destroy",t,t.collection,e)};e.success=function(e,t,i){(i.wait||e.isNew())&&r(),n&&n(e,t,i)};if(this.isNew())return e.success(this,null,e),!1;var i=this.sync("delete",this,e);return e.wait||r(),i},url:function(){var e=u.result(this,"urlRoot")||u.result(this.collection,"url")||k();return this.isNew()?e:e+("/"===e.charAt(e.length-1)?"":"/")+encodeURIComponent(this.id)},parse:function(e){return e},clone:function(){return new this.constructor(this.attributes)},isNew:function(){return null==this.id},isValid:function(e){return!this.validate||!this.validate(this.attributes,e)},_validate:function(e,t){if(!t.validate||!this.validate)return!0;e=u.extend({},this.attributes,e);var n=this.validationError=this.validate(e,t)||null;return n?(this.trigger("invalid",this,n,t||{}),!1):!0}});var h=o.Collection=function(e,t){t||(t={}),t.model&&(this.model=t.model),void 0!==t.comparator&&(this.comparator=t.comparator),this.models=[],this._reset(),this.initialize.apply(this,arguments),e&&this.reset(e,u.extend({silent:!0},t))};u.extend(h.prototype,n,{model:c,initialize:function(){},toJSON:function(e){return this.map(function(t){return t.toJSON(e)})},sync:function(){return o.sync.apply(this,arguments)},add:function(e,t){e=u.isArray(e)?e.slice():[e],t||(t={});var n,i,o,a,f,l,c,h,p,d;c=[],h=t.at,p=this.comparator&&null==h&&0!=t.sort,d=u.isString(this.comparator)?this.comparator:null,n=0;for(i=e.length;n<i;n++)(o=this._prepareModel(a=e[n],t))?(f=this.get(o))?t.merge&&(f.set(a===o?o.attributes:a,t),p&&!l&&f.hasChanged(d)&&(l=!0)):(c.push(o),o.on("all",this._onModelEvent,this),this._byId[o.cid]=o,null!=o.id&&(this._byId[o.id]=o)):this.trigger("invalid",this,a,t);c.length&&(p&&(l=!0),this.length+=c.length,null!=h?s.apply(this.models,[h,0].concat(c)):r.apply(this.models,c)),l&&this.sort({silent:!0});if(t.silent)return this;n=0;for(i=c.length;n<i;n++)(o=c[n]).trigger("add",o,this,t);return l&&this.trigger("sort",this,t),this},remove:function(e,t){e=u.isArray(e)?e.slice():[e],t||(t={});var n,r,i,s;n=0;for(r=e.length;n<r;n++)if(s=this.get(e[n]))delete this._byId[s.id],delete this._byId[s.cid],i=this.indexOf(s),this.models.splice(i,1),this.length--,t.silent||(t.index=i,s.trigger("remove",s,this,t)),this._removeReference(s);return this},push:function(e,t){return e=this._prepareModel(e,t),this.add(e,u.extend({at:this.length},t)),e},pop:function(e){var t=this.at(this.length-1);return this.remove(t,e),t},unshift:function(e,t){return e=this._prepareModel(e,t),this.add(e,u.extend({at:0},t)),e},shift:function(e){var t=this.at(0);return this.remove(t,e),t},slice:function(e,t){return this.models.slice(e,t)},get:function(e){if(null!=e)return this._idAttr||(this._idAttr=this.model.prototype.idAttribute),this._byId[e.id||e.cid||e[this._idAttr]||e]},at:function(e){return this.models[e]},where:function(e){return u.isEmpty(e)?[]:this.filter(function(t){for(var n in e)if(e[n]!==t.get(n))return!1;return!0})},sort:function(e){if(!this.comparator)throw Error("Cannot sort a set without a comparator");return e||(e={}),u.isString(this.comparator)||1===this.comparator.length?this.models=this.sortBy(this.comparator,this):this.models.sort(u.bind(this.comparator,this)),e.silent||this.trigger("sort",this,e),this},pluck:function(e){return u.invoke(this.models,"get",e)},update:function(e,t){t=u.extend({add:!0,merge:!0,remove:!0},t),t.parse&&(e=this.parse(e,t));var n,r,i,s,o=[],a=[],f={};u.isArray(e)||(e=e?[e]:[]);if(t.add&&!t.remove)return this.add(e,t);r=0;for(i=e.length;r<i;r++)n=e[r],s=this.get(n),t.remove&&s&&(f[s.cid]=!0),(t.add&&!s||t.merge&&s)&&o.push(n);if(t.remove){r=0;for(i=this.models.length;r<i;r++)n=this.models[r],f[n.cid]||a.push(n)}return a.length&&this.remove(a,t),o.length&&this.add(o,t),this},reset:function(e,t){t||(t={}),t.parse&&(e=this.parse(e,t));for(var n=0,r=this.models.length;n<r;n++)this._removeReference(this.models[n]);return t.previousModels=this.models.slice(),this._reset(),e&&this.add(e,u.extend({silent:!0},t)),t.silent||this.trigger("reset",this,t),this},fetch:function(e){e=e?u.clone(e):{},void 0===e.parse&&(e.parse=!0);var t=e.success;return e.success=function(e,n,r){e[r.update?"update":"reset"](n,r),t&&t(e,n,r)},this.sync("read",this,e)},create:function(e,t){t=t?u.clone(t):{};if(!(e=this._prepareModel(e,t)))return!1;t.wait||this.add(e,t);var n=this,r=t.success;return t.success=function(e,t,i){i.wait&&n.add(e,i),r&&r(e,t,i)},e.save(null,t),e},parse:function(e){return e},clone:function(){return new this.constructor(this.models)},_reset:function(){this.length=0,this.models.length=0,this._byId={}},_prepareModel:function(e,t){if(e instanceof c)return e.collection||(e.collection=this),e;t||(t={}),t.collection=this;var n=new this.model(e,t);return n._validate(e,t)?n:!1},_removeReference:function(e){this===e.collection&&delete e.collection,e.off("all",this._onModelEvent,this)},_onModelEvent:function(e,t,n,r){("add"===e||"remove"===e)&&n!==this||("destroy"===e&&this.remove(t,r),t&&e==="change:"+t.idAttribute&&(delete this._byId[t.previous(t.idAttribute)],null!=t.id&&(this._byId[t.id]=t)),this.trigger.apply(this,arguments))},sortedIndex:function(e,t,n){t||(t=this.comparator);var r=u.isFunction(t)?t:function(e){return e.get(t)};return u.sortedIndex(this.models,e,r,n)}}),u.each("forEach each map collect reduce foldl inject reduceRight foldr find detect filter select reject every all some any include contains invoke max min toArray size first head take initial rest tail drop last without indexOf shuffle lastIndexOf isEmpty chain".split(" "),function(e){h.prototype[e]=function(){var t=i.call(arguments);return t.unshift(this.models),u[e].apply(u,t)}}),u.each(["groupBy","countBy","sortBy"],function(e){h.prototype[e]=function(t,n){var r=u.isFunction(t)?t:function(e){return e.get(t)};return u[e](this.models,r,n)}});var p=o.Router=function(e){e||(e={}),e.routes&&(this.routes=e.routes),this._bindRoutes(),this.initialize.apply(this,arguments)},d=/\((.*?)\)/g,v=/(\(\?)?:\w+/g,m=/\*\w+/g,g=/[\-{}\[\]+?.,\\\^$|#\s]/g;u.extend(p.prototype,n,{initialize:function(){},route:function(e,t,n){return u.isRegExp(e)||(e=this._routeToRegExp(e)),n||(n=this[t]),o.history.route(e,u.bind(function(r){r=this._extractParameters(e,r),n&&n.apply(this,r),this.trigger.apply(this,["route:"+t].concat(r)),this.trigger("route",t,r),o.history.trigger("route",this,t,r)},this)),this},navigate:function(e,t){return o.history.navigate(e,t),this},_bindRoutes:function(){if(this.routes)for(var e,t=u.keys(this.routes);null!=(e=t.pop());)this.route(e,this.routes[e])},_routeToRegExp:function(e){return e=e.replace(g,"\\$&").replace(d,"(?:$1)?").replace(v,function(e,t){return t?e:"([^/]+)"}).replace(m,"(.*?)"),RegExp("^"+e+"$")},_extractParameters:function(e,t){return e.exec(t).slice(1)}});var y=o.History=function(){this.handlers=[],u.bindAll(this,"checkUrl"),"undefined"!=typeof window&&(this.location=window.location,this.history=window.history)},b=/^[#\/]|\s+$/g,w=/^\/+|\/+$/g,E=/msie [\w.]+/,S=/\/$/;y.started=!1,u.extend(y.prototype,n,{interval:50,getHash:function(e){return(e=(e||this).location.href.match(/#(.*)$/))?e[1]:""},getFragment:function(e,t){if(null==e)if(this._hasPushState||!this._wantsHashChange||t){e=this.location.pathname;var n=this.root.replace(S,"");e.indexOf(n)||(e=e.substr(n.length))}else e=this.getHash();return e.replace(b,"")},start:function(e){if(y.started)throw Error("Backbone.history has already been started");y.started=!0,this.options=u.extend({},{root:"/"},this.options,e),this.root=this.options.root,this._wantsHashChange=!1!==this.options.hashChange,this._wantsPushState=!!this.options.pushState,this._hasPushState=!(!this.options.pushState||!this.history||!this.history.pushState),e=this.getFragment();var t=document.documentMode,t=E.exec(navigator.userAgent.toLowerCase())&&(!t||7>=t);this.root=("/"+this.root+"/").replace(w,"/"),t&&this._wantsHashChange&&(this.iframe=o.$('<iframe src="javascript:0" tabindex="-1" />').hide().appendTo("body")[0].contentWindow,this.navigate(e)),this._hasPushState?o.$(window).on("popstate",this.checkUrl):this._wantsHashChange&&"onhashchange"in window&&!t?o.$(window).on("hashchange",this.checkUrl):this._wantsHashChange&&(this._checkUrlInterval=setInterval(this.checkUrl,this.interval)),this.fragment=e,e=this.location,t=e.pathname.replace(/[^\/]$/,"$&/")===this.root;if(this._wantsHashChange&&this._wantsPushState&&!this._hasPushState&&!t)return this.fragment=this.getFragment(null,!0),this.location.replace(this.root+this.location.search+"#"+this.fragment),!0;this._wantsPushState&&this._hasPushState&&t&&e.hash&&(this.fragment=this.getHash().replace(b,""),this.history.replaceState({},document.title,this.root+this.fragment+e.search));if(!this.options.silent)return this.loadUrl()},stop:function(){o.$(window).off("popstate",this.checkUrl).off("hashchange",this.checkUrl),clearInterval(this._checkUrlInterval),y.started=!1},route:function(e,t){this.handlers.unshift({route:e,callback:t})},checkUrl:function(){var e=this.getFragment();e===this.fragment&&this.iframe&&(e=this.getFragment(this.getHash(this.iframe)));if(e===this.fragment)return!1;this.iframe&&this.navigate(e),this.loadUrl()||this.loadUrl(this.getHash())},loadUrl:function(e){var t=this.fragment=this.getFragment(e);return u.any(this.handlers,function(e){if(e.route.test(t))return e.callback(t),!0})},navigate:function(e,t){if(!y.started)return!1;if(!t||!0===t)t={trigger:t};e=this.getFragment(e||"");if(this.fragment!==e){this.fragment=e;var n=this.root+e;if(this._hasPushState)this.history[t.replace?"replaceState":"pushState"]({},document.title,n);else{if(!this._wantsHashChange)return this.location.assign(n);this._updateHash(this.location,e,t.replace),this.iframe&&e!==this.getFragment(this.getHash(this.iframe))&&(t.replace||this.iframe.document.open().close(),this._updateHash(this.iframe.location,e,t.replace))}t.trigger&&this.loadUrl(e)}},_updateHash:function(e,t,n){n?(n=e.href.replace(/(javascript:|#).*$/,""),e.replace(n+"#"+t)):e.hash="#"+t}}),o.history=new y;var x=o.View=function(e){this.cid=u.uniqueId("view"),this._configure(e||{}),this._ensureElement(),this.initialize.apply(this,arguments),this.delegateEvents()},T=/^(\S+)\s*(.*)$/,N="model collection el id attributes className tagName events".split(" ");u.extend(x.prototype,n,{tagName:"div",$:function(e){return this.$el.find(e)},initialize:function(){},render:function(){return this},remove:function(){return this.$el.remove(),this.stopListening(),this},setElement:function(e,t){return this.$el&&this.undelegateEvents(),this.$el=e instanceof o.$?e:o.$(e),this.el=this.$el[0],!1!==t&&this.delegateEvents(),this},delegateEvents:function(e){if(e||(e=u.result(this,"events"))){this.undelegateEvents();for(var t in e){var n=e[t];u.isFunction(n)||(n=this[e[t]]);if(!n)throw Error('Method "'+e[t]+'" does not exist');var r=t.match(T),i=r[1],r=r[2],n=u.bind(n,this),i=i+(".delegateEvents"+this.cid);""===r?this.$el.on(i,n):this.$el.on(i,r,n)}}},undelegateEvents:function(){this.$el.off(".delegateEvents"+this.cid)},_configure:function(e){this.options&&(e=u.extend({},u.result(this,"options"),e)),u.extend(this,u.pick(e,N)),this.options=e},_ensureElement:function(){if(this.el)this.setElement(u.result(this,"el"),!1);else{var e=u.extend({},u.result(this,"attributes"));this.id&&(e.id=u.result(this,"id")),this.className&&(e["class"]=u.result(this,"className")),e=o.$("<"+u.result(this,"tagName")+">").attr(e),this.setElement(e,!1)}}});var C={create:"POST",update:"PUT",patch:"PATCH","delete":"DELETE",read:"GET"};o.sync=function(e,t,n){var r=C[e];u.defaults(n||(n={}),{emulateHTTP:o.emulateHTTP,emulateJSON:o.emulateJSON});var i={type:r,dataType:"json"};n.url||(i.url=u.result(t,"url")||k()),null==n.data&&t&&("create"===e||"update"===e||"patch"===e)&&(i.contentType="application/json",i.data=JSON.stringify(n.attrs||t.toJSON(n))),n.emulateJSON&&(i.contentType="application/x-www-form-urlencoded",i.data=i.data?{model:i.data}:{});if(n.emulateHTTP&&("PUT"===r||"DELETE"===r||"PATCH"===r)){i.type="POST",n.emulateJSON&&(i.data._method=r);var s=n.beforeSend;n.beforeSend=function(e){e.setRequestHeader("X-HTTP-Method-Override",r);if(s)return s.apply(this,arguments)}}"GET"!==i.type&&!n.emulateJSON&&(i.processData=!1);var a=n.success;n.success=function(e){a&&a(t,e,n),t.trigger("sync",t,e,n)};var f=n.error;return n.error=function(e){f&&f(t,e,n),t.trigger("error",t,e,n)},e=n.xhr=o.ajax(u.extend(i,n)),t.trigger("request",t,e,n),e},o.ajax=function(){return o.$.ajax.apply(o.$,arguments)},c.extend=h.extend=p.extend=x.extend=y.extend=function(e,t){var n=this,r;r=e&&u.has(e,"constructor")?e.constructor:function(){return n.apply(this,arguments)},u.extend(r,n,t);var i=function(){this.constructor=r};return i.prototype=n.prototype,r.prototype=new i,e&&u.extend(r.prototype,e),r.__super__=n.prototype,r};var k=function(){throw Error('A "url" property or function must be specified')}}.call(this),define("backbone",["underscore","jquery"],function(e){return function(){var t,n;return t||e.Backbone}}(this)),(window._gsQueue||(window._gsQueue=[])).push(function(){window._gsDefine("TweenMax",["core.Animation","core.SimpleTimeline","TweenLite"],function(e,t,n){var r=function(e,t,r){n.call(this,e,t,r),this._cycle=0,this._yoyo=this.vars.yoyo===!0,this._repeat=this.vars.repeat||0,this._repeatDelay=this.vars.repeatDelay||0,this._dirty=!0},i=function(e){return e.jquery||typeof e.each=="function"&&e[0]&&e[0].nodeType&&e[0].style},s=function(e){var t=[];return e.each(function(){t.push(this)}),t},o=r.prototype=n.to({},.1,{}),u=[];r.version="1.9.1",o.constructor=r,o.kill()._gc=!1,r.killTweensOf=r.killDelayedCallsTo=n.killTweensOf,r.getTweensOf=n.getTweensOf,r.ticker=n.ticker,o.invalidate=function(){return this._yoyo=this.vars.yoyo===!0,this._repeat=this.vars.repeat||0,this._repeatDelay=this.vars.repeatDelay||0,this._uncache(!0),n.prototype.invalidate.call(this)},o.updateTo=function(e,t){var r=this.ratio,i;t&&this.timeline&&this._startTime<this._timeline._time&&(this._startTime=this._timeline._time,this._uncache(!1),this._gc?this._enabled(!0,!1):this._timeline.insert(this,this._startTime-this._delay));for(i in e)this.vars[i]=e[i];if(this._initted)if(t)this._initted=!1;else{this._notifyPluginsOfEnabled&&this._firstPT&&n._onPluginEvent("_onDisable",this);if(this._time/this._duration>.998){var s=this._time;this.render(0,!0,!1),this._initted=!1,this.render(s,!0,!1)}else if(this._time>0){this._initted=!1,this._init();var o=1/(1-r),u=this._firstPT,a;while(u)a=u.s+u.c,u.c*=o,u.s=a-u.c,u=u._next}}return this},o.render=function(e,t,n){var r=this._dirty?this.totalDuration():this._totalDuration,i=this._time,s=this._totalTime,o=this._cycle,a,f,l,c,h,p,d;if(e>=r)this._totalTime=r,this._cycle=this._repeat,this._yoyo&&(this._cycle&1)!==0?(this._time=0,this.ratio=this._ease._calcEnd?this._ease.getRatio(0):0):(this._time=this._duration,this.ratio=this._ease._calcEnd?this._ease.getRatio(1):1),this._reversed||(a=!0,f="onComplete"),this._duration===0&&((e===0||this._rawPrevTime<0)&&this._rawPrevTime!==e&&(n=!0),this._rawPrevTime=e);else if(e<=0){this._totalTime=this._time=this._cycle=0,this.ratio=this._ease._calcEnd?this._ease.getRatio(0):0;if(s!==0||this._duration===0&&this._rawPrevTime>0)f="onReverseComplete",a=this._reversed;e<0?(this._active=!1,this._duration===0&&(this._rawPrevTime>=0&&(n=!0),this._rawPrevTime=e)):this._initted||(n=!0)}else{this._totalTime=this._time=e,this._repeat!==0&&(c=this._duration+this._repeatDelay,this._cycle=this._totalTime/c>>0,this._cycle!==0&&this._cycle===this._totalTime/c&&this._cycle--,this._time=this._totalTime-this._cycle*c,this._yoyo&&(this._cycle&1)!==0&&(this._time=this._duration-this._time),this._time>this._duration?this._time=this._duration:this._time<0&&(this._time=0));if(this._easeType){h=this._time/this._duration,p=this._easeType,d=this._easePower;if(p===1||p===3&&h>=.5)h=1-h;p===3&&(h*=2),d===1?h*=h:d===2?h*=h*h:d===3?h*=h*h*h:d===4&&(h*=h*h*h*h),p===1?this.ratio=1-h:p===2?this.ratio=h:this._time/this._duration<.5?this.ratio=h/2:this.ratio=1-h/2}else this.ratio=this._ease.getRatio(this._time/this._duration)}if(i===this._time&&!n){s!==this._totalTime&&this._onUpdate&&(t||this._onUpdate.apply(this.vars.onUpdateScope||this,this.vars.onUpdateParams||u));return}if(!this._initted){this._init();if(!this._initted)return;this._time&&!a?this.ratio=this._ease.getRatio(this._time/this._duration):a&&this._ease._calcEnd&&(this.ratio=this._ease.getRatio(this._time===0?0:1))}this._active||this._paused||(this._active=!0),s===0&&(this._startAt&&this._startAt.render(e,t,n),this.vars.onStart&&(this._totalTime!==0||this._duration===0)&&(t||this.vars.onStart.apply(this.vars.onStartScope||this,this.vars.onStartParams||u))),l=this._firstPT;while(l)l.f?l.t[l.p](l.c*this.ratio+l.s):l.t[l.p]=l.c*this.ratio+l.s,l=l._next;this._onUpdate&&(e<0&&this._startAt&&this._startAt.render(e,t,n),t||this._onUpdate.apply(this.vars.onUpdateScope||this,this.vars.onUpdateParams||u)),this._cycle!==o&&(t||this._gc||this.vars.onRepeat&&this.vars.onRepeat.apply(this.vars.onRepeatScope||this,this.vars.onRepeatParams||u)),f&&(this._gc||(e<0&&this._startAt&&(this._onUpdate||this._startAt.render(e,t,n)),a&&(this._timeline.autoRemoveChildren&&this._enabled(!1,!1),this._active=!1),t||this.vars[f]&&this.vars[f].apply(this.vars[f+"Scope"]||this,this.vars[f+"Params"]||u)))},r.to=function(e,t,n){return new r(e,t,n)},r.from=function(e,t,n){return n.runBackwards=!0,n.immediateRender=n.immediateRender!=0,new r(e,t,n)},r.fromTo=function(e,t,n,i){return i.startAt=n,i.immediateRender=i.immediateRender!=0&&n.immediateRender!=0,new r(e,t,i)},r.staggerTo=r.allTo=function(e,t,o,a,f,l,c){a=a||0;var h=o.delay||0,p=[],d=function(){o.onComplete&&o.onComplete.apply(o.onCompleteScope||this,o.onCompleteParams||u),f.apply(c||this,l||u)},v,m,g,y;e instanceof Array||(typeof e=="string"&&(e=n.selector(e)||e),i(e)&&(e=s(e))),v=e.length;for(g=0;g<v;g++){m={};for(y in o)m[y]=o[y];m.delay=h,g===v-1&&f&&(m.onComplete=d),p[g]=new r(e[g],t,m),h+=a}return p},r.staggerFrom=r.allFrom=function(e,t,n,i,s,o,u){return n.runBackwards=!0,n.immediateRender=n.immediateRender!=0,r.staggerTo(e,t,n,i,s,o,u)},r.staggerFromTo=r.allFromTo=function(e,t,n,i,s,o,u,a){return i.startAt=n,i.immediateRender=i.immediateRender!=0&&n.immediateRender!=0,r.staggerTo(e,t,i,s,o,u,a)},r.delayedCall=function(e,t,n,i,s){return new r(t,0,{delay:e,onComplete:t,onCompleteParams:n,onCompleteScope:i,onReverseComplete:t,onReverseCompleteParams:n,onReverseCompleteScope:i,immediateRender:!1,useFrames:s,overwrite:0})},r.set=function(e,t){return new r(e,0,t)},r.isTweening=function(e){var t=n.getTweensOf(e),r=t.length,i;while(--r>-1){i=t[r];if(i._active||i._startTime===i._timeline._time&&i._timeline._active)return!0}return!1};var a=function(e,t){var r=[],i=0,s=e._first;while(s)s instanceof n?r[i++]=s:(t&&(r[i++]=s),r=r.concat(a(s,t)),i=r.length),s=s._next;return r},f=r.getAllTweens=function(t){return a(e._rootTimeline,t).concat(a(e._rootFramesTimeline,t))};r.killAll=function(e,n,r,i){n==null&&(n=!0),r==null&&(r=!0);var s=f(i!=0),o=s.length,u=n&&r&&i,a,l,c;for(c=0;c<o;c++){l=s[c];if(u||l instanceof t||(a=l.target===l.vars.onComplete)&&r||n&&!a)e?l.totalTime(l.totalDuration()):l._enabled(!1,!1)}},r.killChildTweensOf=function(e,t){if(e==null)return;var o=n._tweenLookup,u,a,f,l,c;typeof e=="string"&&(e=n.selector(e)||e),i(e)&&(e=s(e));if(e instanceof Array){l=e.length;while(--l>-1)r.killChildTweensOf(e[l],t);return}u=[];for(f in o){a=o[f].target.parentNode;while(a)a===e&&(u=u.concat(o[f].tweens)),a=a.parentNode}c=u.length;for(l=0;l<c;l++)t&&u[l].totalTime(u[l].totalDuration()),u[l]._enabled(!1,!1)};var l=function(e,n,r,i){n===undefined&&(n=!0),r===undefined&&(r=!0);var s=f(i),o=n&&r&&i,u=s.length,a,l;while(--u>-1)l=s[u],(o||l instanceof t||(a=l.target===l.vars.onComplete)&&r||n&&!a)&&l.paused(e)};return r.pauseAll=function(e,t,n){l(!0,e,t,n)},r.resumeAll=function(e,t,n){l(!1,e,t,n)},o.progress=function(e){return arguments.length?this.totalTime(this.duration()*(this._yoyo&&(this._cycle&1)!==0?1-e:e)+this._cycle*(this._duration+this._repeatDelay),!1):this._time/this.duration()},o.totalProgress=function(e){return arguments.length?this.totalTime(this.totalDuration()*e,!1):this._totalTime/this.totalDuration()},o.time=function(e,t){return arguments.length?(this._dirty&&this.totalDuration(),e>this._duration&&(e=this._duration),this._yoyo&&(this._cycle&1)!==0?e=this._duration-e+this._cycle*(this._duration+this._repeatDelay):this._repeat!==0&&(e+=this._cycle*(this._duration+this._repeatDelay)),this.totalTime(e,t)):this._time},o.duration=function(t){return arguments.length?e.prototype.duration.call(this,t):this._duration},o.totalDuration=function(e){return arguments.length?this._repeat===-1?this:this.duration((e-this._repeat*this._repeatDelay)/(this._repeat+1)):(this._dirty&&(this._totalDuration=this._repeat===-1?999999999999:this._duration*(this._repeat+1)+this._repeatDelay*this._repeat,this._dirty=!1),this._totalDuration)},o.repeat=function(e){return arguments.length?(this._repeat=e,this._uncache(!0)):this._repeat},o.repeatDelay=function(e){return arguments.length?(this._repeatDelay=e,this._uncache(!0)):this._repeatDelay},o.yoyo=function(e){return arguments.length?(this._yoyo=e,this):this._yoyo},r},!0),window._gsDefine("TimelineLite",["core.Animation","core.SimpleTimeline","TweenLite"],function(e,t,n){var r=function(e){t.call(this,e),this._labels={},this.autoRemoveChildren=this.vars.autoRemoveChildren===!0,this.smoothChildTiming=this.vars.smoothChildTiming===!0,this._sortChildren=!0,this._onUpdate=this.vars.onUpdate;var n=this.vars,r=i.length,s,o;while(--r>-1){o=n[i[r]];if(o){s=o.length;while(--s>-1)o[s]==="{self}"&&(o=n[i[r]]=o.concat(),o[s]=this)}}n.tweens instanceof Array&&this.add(n.tweens,0,n.align,n.stagger)},i=["onStartParams","onUpdateParams","onCompleteParams","onReverseCompleteParams","onRepeatParams"],s=[],o=function(e){var t={},n;for(n in e)t[n]=e[n];return t},u=r.prototype=new t;return r.version="1.9.1",u.constructor=r,u.kill()._gc=!1,u.to=function(e,t,r,i){return this.add(new n(e,t,r),i)},u.from=function(e,t,r,i){return this.add(n.from(e,t,r),i)},u.fromTo=function(e,t,r,i,s){return this.add(n.fromTo(e,t,r,i),s)},u.staggerTo=function(e,t,i,s,u,a,f,l){var c=new r({onComplete:a,onCompleteParams:f,onCompleteScope:l}),h,p;typeof e=="string"&&(e=n.selector(e)||e),!(e instanceof Array)&&typeof e.each=="function"&&e[0]&&e[0].nodeType&&e[0].style&&(p=[],e.each(function(){p.push(this)}),e=p),s=s||0;for(h=0;h<e.length;h++)i.startAt&&(i.startAt=o(i.startAt)),c.add(new n(e[h],t,o(i)),h*s);return this.add(c,u)},u.staggerFrom=function(e,t,n,r,i,s,o,u){return n.immediateRender=n.immediateRender!=0,n.runBackwards=!0,this.staggerTo(e,t,n,r,i,s,o,u)},u.staggerFromTo=function(e,t,n,r,i,s,o,u,a){return r.startAt=n,r.immediateRender=r.immediateRender!=0&&n.immediateRender!=0,this.staggerTo(e,t,r,i,s,o,u,a)},u.call=function(e,t,r,i){return this.add(n.delayedCall(0,e,t,r),i)},u.set=function(e,t,r){return r=this._parseTimeOrLabel(r,0,!0),t.immediateRender==null&&(t.immediateRender=r===this._time&&!this._paused),this.add(new n(e,0,t),r)},r.exportRoot=function(e,t){e=e||{},e.smoothChildTiming==null&&(e.smoothChildTiming=!0);var i=new r(e),s=i._timeline,o,u;t==null&&(t=!0),s._remove(i,!0),i._startTime=0,i._rawPrevTime=i._time=i._totalTime=s._time,o=s._first;while(o)u=o._next,(!t||!(o instanceof n&&o.target===o.vars.onComplete))&&i.add(o,o._startTime-o._delay),o=u;return s.add(i,0),i},u.add=function(i,s,o,u){var a,f,l,c,h;typeof s!="number"&&(s=this._parseTimeOrLabel(s,0,!0,i));if(!(i instanceof e)){if(i instanceof Array){o=o||"normal",u=u||0,a=s,f=i.length;for(l=0;l<f;l++)(c=i[l])instanceof Array&&(c=new r({tweens:c})),this.add(c,a),typeof c!="string"&&typeof c!="function"&&(o==="sequence"?a=c._startTime+c.totalDuration()/c._timeScale:o==="start"&&(c._startTime-=c.delay())),a+=u;return this._uncache(!0)}if(typeof i=="string")return this.addLabel(i,s);if(typeof i!="function")throw"Cannot add "+i+" into the timeline: it is neither a tween, timeline, function, nor a string.";i=n.delayedCall(0,i)}t.prototype.add.call(this,i,s);if(this._gc&&!this._paused&&this._time===this._duration&&this._time<this.duration()){h=this;while(h._gc&&h._timeline)h._timeline.smoothChildTiming?h.totalTime(h._totalTime,!0):h._enabled(!0,!1),h=h._timeline}return this},u.remove=function(t){if(t instanceof e)return this._remove(t,!1);if(t instanceof Array){var n=t.length;while(--n>-1)this.remove(t[n]);return this}return typeof t=="string"?this.removeLabel(t):this.kill(null,t)},u.append=function(e,t){return this.add(e,this._parseTimeOrLabel(null,t,!0,e))},u.insert=u.insertMultiple=function(e,t,n,r){return this.add(e,t||0,n,r)},u.appendMultiple=function(e,t,n,r){return this.add(e,this._parseTimeOrLabel(null,t,!0,e),n,r)},u.addLabel=function(e,t){return this._labels[e]=this._parseTimeOrLabel(t),this},u.removeLabel=function(e){return delete this._labels[e],this},u.getLabelTime=function(e){return this._labels[e]!=null?this._labels[e]:-1},u._parseTimeOrLabel=function(t,n,r,i){var s;if(i instanceof e&&i.timeline===this)this.remove(i);else if(i instanceof Array){s=i.length;while(--s>-1)i[s]instanceof e&&i[s].timeline===this&&this.remove(i[s])}if(typeof n=="string")return this._parseTimeOrLabel(n,r&&typeof t=="number"&&this._labels[n]==null?t-this.duration():0,r);n=n||0;if(typeof t!="string"||!isNaN(t)&&this._labels[t]==null)t==null&&(t=this.duration());else{s=t.indexOf("=");if(s===-1)return this._labels[t]==null?r?this._labels[t]=this.duration()+n:n:this._labels[t]+n;n=parseInt(t.charAt(s-1)+"1",10)*Number(t.substr(s+1)),t=s>1?this._parseTimeOrLabel(t.substr(0,s-1),0,r):this.duration()}return Number(t)+n},u.seek=function(e,t){return this.totalTime(typeof e=="number"?e:this._parseTimeOrLabel(e),t!==!1)},u.stop=function(){return this.paused(!0)},u.gotoAndPlay=function(e,t){return this.play(e,t)},u.gotoAndStop=function(e,t){return this.pause(e,t)},u.render=function(e,t,n){this._gc&&this._enabled(!0,!1),this._active=!this._paused;var r=this._dirty?this.totalDuration():this._totalDuration,i=this._time,o=this._startTime,u=this._timeScale,a=this._paused,f,l,c,h,p;if(e>=r)this._totalTime=this._time=r,this._reversed||this._hasPausedChild()||(l=!0,h="onComplete",this._duration===0&&(e===0||this._rawPrevTime<0)&&this._rawPrevTime!==e&&(p=!0)),this._rawPrevTime=e,e=r+1e-6;else if(e<=0){this._totalTime=this._time=0;if(i!==0||this._duration===0&&this._rawPrevTime>0)h="onReverseComplete",l=this._reversed;e<0?(this._active=!1,this._duration===0&&this._rawPrevTime>=0&&(p=!0)):this._initted||(p=!0),this._rawPrevTime=e,e=-0.000001}else this._totalTime=this._time=this._rawPrevTime=e;if(this._time===i&&!n&&!p)return;this._initted||(this._initted=!0),i===0&&this.vars.onStart&&this._time!==0&&(t||this.vars.onStart.apply(this.vars.onStartScope||this,this.vars.onStartParams||s));if(this._time>i){f=this._first;while(f){c=f._next;if(this._paused&&!a)break;if(f._active||f._startTime<=this._time&&!f._paused&&!f._gc)f._reversed?f.render((f._dirty?f.totalDuration():f._totalDuration)-(e-f._startTime)*f._timeScale,t,n):f.render((e-f._startTime)*f._timeScale,t,n);f=c}}else{f=this._last;while(f){c=f._prev;if(this._paused&&!a)break;if(f._active||f._startTime<=i&&!f._paused&&!f._gc)f._reversed?f.render((f._dirty?f.totalDuration():f._totalDuration)-(e-f._startTime)*f._timeScale,t,n):f.render((e-f._startTime)*f._timeScale,t,n);f=c}}this._onUpdate&&(t||this._onUpdate.apply(this.vars.onUpdateScope||this,this.vars.onUpdateParams||s)),h&&!this._gc&&(o===this._startTime||u!==this._timeScale)&&(this._time===0||r>=this.totalDuration())&&(l&&(this._timeline.autoRemoveChildren&&this._enabled(!1,!1),this._active=!1),t||this.vars[h]&&this.vars[h].apply(this.vars[h+"Scope"]||this,this.vars[h+"Params"]||s))},u._hasPausedChild=function(){var e=this._first;while(e){if(e._paused||e instanceof r&&e._hasPausedChild())return!0;e=e._next}return!1},u.getChildren=function(e,t,r,i){i=i||-9999999999;var s=[],o=this._first,u=0;while(o)o._startTime<i||(o instanceof n?t!==!1&&(s[u++]=o):(r!==!1&&(s[u++]=o),e!==!1&&(s=s.concat(o.getChildren(!0,t,r)),u=s.length))),o=o._next;return s},u.getTweensOf=function(e,t){var r=n.getTweensOf(e),i=r.length,s=[],o=0;while(--i>-1)if(r[i].timeline===this||t&&this._contains(r[i]))s[o++]=r[i];return s},u._contains=function(e){var t=e.timeline;while(t){if(t===this)return!0;t=t.timeline}return!1},u.shiftChildren=function(e,t,n){n=n||0;var r=this._first,i=this._labels,s;while(r)r._startTime>=n&&(r._startTime+=e),r=r._next;if(t)for(s in i)i[s]>=n&&(i[s]+=e);return this._uncache(!0)},u._kill=function(e,t){if(!e&&!t)return this._enabled(!1,!1);var n=t?this.getTweensOf(t):this.getChildren(!0,!0,!1),r=n.length,i=!1;while(--r>-1)n[r]._kill(e,t)&&(i=!0);return i},u.clear=function(e){var t=this.getChildren(!1,!0,!0),n=t.length;this._time=this._totalTime=0;while(--n>-1)t[n]._enabled(!1,!1);return e!==!1&&(this._labels={}),this._uncache(!0)},u.invalidate=function(){var e=this._first;while(e)e.invalidate(),e=e._next;return this},u._enabled=function(e,n){if(e===this._gc){var r=this._first;while(r)r._enabled(e,!0),r=r._next}return t.prototype._enabled.call(this,e,n)},u.progress=function(e){return arguments.length?this.totalTime(this.duration()*e,!1):this._time/this.duration()},u.duration=function(e){return arguments.length?(this.duration()!==0&&e!==0&&this.timeScale(this._duration/e),this):(this._dirty&&this.totalDuration(),this._duration)},u.totalDuration=function(e){if(!arguments.length){if(this._dirty){var t=0,n=this._last,r=999999999999,i,s;while(n)i=n._prev,n._dirty&&n.totalDuration(),n._startTime>r&&this._sortChildren&&!n._paused?this.add(n,n._startTime-n._delay):r=n._startTime,n._startTime<0&&!n._paused&&(t-=n._startTime,this._timeline.smoothChildTiming&&(this._startTime+=n._startTime/this._timeScale),this.shiftChildren(-n._startTime,!1,-9999999999),r=0),s=n._startTime+n._totalDuration/n._timeScale,s>t&&(t=s),n=i;this._duration=this._totalDuration=t,this._dirty=!1}return this._totalDuration}return this.totalDuration()!==0&&e!==0&&this.timeScale(this._totalDuration/e),this},u.usesFrames=function(){var t=this._timeline;while(t._timeline)t=t._timeline;return t===e._rootFramesTimeline},u.rawTime=function(){return this._paused||this._totalTime!==0&&this._totalTime!==this._totalDuration?this._totalTime:(this._timeline.rawTime()-this._startTime)*this._timeScale},r},!0),window._gsDefine("TimelineMax",["TimelineLite","TweenLite","easing.Ease"],function(e,t,n){var r=function(t){e.call(this,t),this._repeat=this.vars.repeat||0,this._repeatDelay=this.vars.repeatDelay||0,this._cycle=0,this._yoyo=this.vars.yoyo===!0,this._dirty=!0},i=[],s=new n(null,null,1,0),o=function(e){while(e){if(e._paused)return!0;e=e._timeline}return!1},u=r.prototype=new e;return u.constructor=r,u.kill()._gc=!1,r.version="1.9.1",u.invalidate=function(){return this._yoyo=this.vars.yoyo===!0,this._repeat=this.vars.repeat||0,this._repeatDelay=this.vars.repeatDelay||0,this._uncache(!0),e.prototype.invalidate.call(this)},u.addCallback=function(e,n,r,i){return this.add(t.delayedCall(0,e,r,i),n)},u.removeCallback=function(e,t){if(t==null)this._kill(null,e);else{var n=this.getTweensOf(e,!1),r=n.length,i=this._parseTimeOrLabel(t);while(--r>-1)n[r]._startTime===i&&n[r]._enabled(!1,!1)}return this},u.tweenTo=function(e,n){n=n||{};var r={ease:s,overwrite:2,useFrames:this.usesFrames(),immediateRender:!1},o,u;for(o in n)r[o]=n[o];return r.time=this._parseTimeOrLabel(e),u=new t(this,Math.abs(Number(r.time)-this._time)/this._timeScale||.001,r),r.onStart=function(){u.target.paused(!0),u.vars.time!==u.target.time()&&u.duration(Math.abs(u.vars.time-u.target.time())/u.target._timeScale),n.onStart&&n.onStart.apply(n.onStartScope||u,n.onStartParams||i)},u},u.tweenFromTo=function(e,t,n){n=n||{},n.startAt={time:this._parseTimeOrLabel(e)};var r=this.tweenTo(t,n);return r.duration(Math.abs(r.vars.time-r.vars.startAt.time)/this._timeScale||.001)},u.render=function(e,t,n){this._gc&&this._enabled(!0,!1),this._active=!this._paused;var r=this._dirty?this.totalDuration():this._totalDuration,s=this._duration,o=this._time,u=this._totalTime,a=this._startTime,f=this._timeScale,l=this._rawPrevTime,c=this._paused,h=this._cycle,p,d,v,m,g;if(e>=r)this._locked||(this._totalTime=r,this._cycle=this._repeat),this._reversed||this._hasPausedChild()||(d=!0,m="onComplete",s===0&&(e===0||this._rawPrevTime<0)&&this._rawPrevTime!==e&&(g=!0)),this._rawPrevTime=e,this._yoyo&&(this._cycle&1)!==0?(this._time=0,e=-0.000001):(this._time=s,e=s+1e-6);else if(e<=0){this._locked||(this._totalTime=this._cycle=0),this._time=0;if(o!==0||s===0&&this._rawPrevTime>0&&!this._locked)m="onReverseComplete",d=this._reversed;e<0?(this._active=!1,s===0&&this._rawPrevTime>=0&&(g=!0)):this._initted||(g=!0),this._rawPrevTime=e,e=s===0?0:-0.000001}else{this._time=this._rawPrevTime=e;if(!this._locked){this._totalTime=e;if(this._repeat!==0){var y=s+this._repeatDelay;this._cycle=this._totalTime/y>>0,this._cycle!==0&&this._cycle===this._totalTime/y&&this._cycle--,this._time=this._totalTime-this._cycle*y,this._yoyo&&(this._cycle&1)!==0&&(this._time=s-this._time),this._time>s?(this._time=s,e=s+1e-6):this._time<0?this._time=e=0:e=this._time}}}if(this._cycle!==h&&!this._locked){var b=this._yoyo&&(h&1)!==0,w=b===(this._yoyo&&(this._cycle&1)!==0),E=this._totalTime,S=this._cycle,x=this._rawPrevTime,T=this._time;this._totalTime=h*s,this._cycle<h?b=!b:this._totalTime+=s,this._time=o,this._rawPrevTime=s===0?l-1e-5:l,this._cycle=h,this._locked=!0,o=b?0:s,this.render(o,t,s===0),t||this._gc||this.vars.onRepeat&&this.vars.onRepeat.apply(this.vars.onRepeatScope||this,this.vars.onRepeatParams||i),w&&(o=b?s+1e-6:-0.000001,this.render(o,!0,!1)),this._time=T,this._totalTime=E,this._cycle=S,this._rawPrevTime=x,this._locked=!1}if(this._time===o&&!n&&!g){u!==this._totalTime&&this._onUpdate&&(t||this._onUpdate.apply(this.vars.onUpdateScope||this,this.vars.onUpdateParams||i));return}this._initted||(this._initted=!0),u===0&&this.vars.onStart&&this._totalTime!==0&&(t||this.vars.onStart.apply(this.vars.onStartScope||this,this.vars.onStartParams||i));if(this._time>o){p=this._first;while(p){v=p._next;if(this._paused&&!c)break;if(p._active||p._startTime<=this._time&&!p._paused&&!p._gc)p._reversed?p.render((p._dirty?p.totalDuration():p._totalDuration)-(e-p._startTime)*p._timeScale,t,n):p.render((e-p._startTime)*p._timeScale,t,n);p=v}}else{p=this._last;while(p){v=p._prev;if(this._paused&&!c)break;if(p._active||p._startTime<=o&&!p._paused&&!p._gc)p._reversed?p.render((p._dirty?p.totalDuration():p._totalDuration)-(e-p._startTime)*p._timeScale,t,n):p.render((e-p._startTime)*p._timeScale,t,n);p=v}}this._onUpdate&&(t||this._onUpdate.apply(this.vars.onUpdateScope||this,this.vars.onUpdateParams||i)),m&&(this._locked||!this._gc&&(a===this._startTime||f!==this._timeScale)&&(this._time===0||r>=this.totalDuration())&&(d&&(this._timeline.autoRemoveChildren&&this._enabled(!1,!1),this._active=!1),t||this.vars[m]&&this.vars[m].apply(this.vars[m+"Scope"]||this,this.vars[m+"Params"]||i)))},u.getActive=function(e,t,n){e==null&&(e=!0),t==null&&(t=!0),n==null&&(n=!1);var r=[],i=this.getChildren(e,t,n),s=0,u=i.length,a,f;for(a=0;a<u;a++)f=i[a],f._paused||f._timeline._time>=f._startTime&&f._timeline._time<f._startTime+f._totalDuration/f._timeScale&&(o(f._timeline)||(r[s++]=f));return r},u.getLabelAfter=function(e){e||e!==0&&(e=this._time);var t=this.getLabelsArray(),n=t.length,r;for(r=0;r<n;r++)if(t[r].time>e)return t[r].name;return null},u.getLabelBefore=function(e){e==null&&(e=this._time);var t=this.getLabelsArray(),n=t.length;while(--n>-1)if(t[n].time<e)return t[n].name;return null},u.getLabelsArray=function(){var e=[],t=0,n;for(n in this._labels)e[t++]={time:this._labels[n],name:n};return e.sort(function(e,t){return e.time-t.time}),e},u.progress=function(e){return arguments.length?this.totalTime(this.duration()*(this._yoyo&&(this._cycle&1)!==0?1-e:e)+this._cycle*(this._duration+this._repeatDelay),!1):this._time/this.duration()},u.totalProgress=function(e){return arguments.length?this.totalTime(this.totalDuration()*e,!1):this._totalTime/this.totalDuration()},u.totalDuration=function(t){return arguments.length?this._repeat===-1?this:this.duration((t-this._repeat*this._repeatDelay)/(this._repeat+1)):(this._dirty&&(e.prototype.totalDuration.call(this),this._totalDuration=this._repeat===-1?999999999999:this._duration*(this._repeat+1)+this._repeatDelay*this._repeat),this._totalDuration)},u.time=function(e,t){return arguments.length?(this._dirty&&this.totalDuration(),e>this._duration&&(e=this._duration),this._yoyo&&(this._cycle&1)!==0?e=this._duration-e+this._cycle*(this._duration+this._repeatDelay):this._repeat!==0&&(e+=this._cycle*(this._duration+this._repeatDelay)),this.totalTime(e,t)):this._time},u.repeat=function(e){return arguments.length?(this._repeat=e,this._uncache(!0)):this._repeat},u.repeatDelay=function(e){return arguments.length?(this._repeatDelay=e,this._uncache(!0)):this._repeatDelay},u.yoyo=function(e){return arguments.length?(this._yoyo=e,this):this._yoyo},u.currentLabel=function(e){return arguments.length?this.seek(e,!0):this.getLabelBefore(this._time+1e-8)},r},!0),function(){var e=180/Math.PI,t=Math.PI/180,n=[],r=[],i=[],s={},o=function(e,t,n,r){this.a=e,this.b=t,this.c=n,this.d=r,this.da=r-e,this.ca=n-e,this.ba=t-e},u=",x,y,z,left,top,right,bottom,marginTop,marginLeft,marginRight,marginBottom,paddingLeft,paddingTop,paddingRight,paddingBottom,backgroundPosition,backgroundPosition_y,",a=function(e,t,n,r){var i={a:e},s={},o={},u={c:r},a=(e+t)/2,f=(t+n)/2,l=(n+r)/2,c=(a+f)/2,h=(f+l)/2,p=(h-c)/8;return i.b=a+(e-a)/4,s.b=c+p,i.c=s.a=(i.b+s.b)/2,s.c=o.a=(c+h)/2,o.b=h-p,u.b=l+(r-l)/4,o.c=u.a=(o.b+u.b)/2,[i,s,o,u]},f=function(e,t,s,o,u){var f=e.length-1,l=0,c=e[0].a,h,p,d,v,m,g,y,b,w,E,S,x,T;for(h=0;h<f;h++)m=e[l],p=m.a,d=m.d,v=e[l+1].d,u?(S=n[h],x=r[h],T=(x+S)*t*.25/(o?.5:i[h]||.5),g=d-(d-p)*(o?t*.5:T/S),y=d+(v-d)*(o?t*.5:T/x),b=d-(g+(y-g)*(S*3/(S+x)+.5)/4)):(g=d-(d-p)*t*.5,y=d+(v-d)*t*.5,b=d-(g+y)/2),g+=b,y+=b,m.c=w=g,h!==0?m.b=c:m.b=c=m.a+(m.c-m.a)*.6,m.da=d-p,m.ca=w-p,m.ba=c-p,s?(E=a(p,c,w,d),e.splice(l,1,E[0],E[1],E[2],E[3]),l+=4):l++,c=y;m=e[l],m.b=c,m.c=c+(m.d-c)*.4,m.da=m.d-m.a,m.ca=m.c-m.a,m.ba=c-m.a,s&&(E=a(m.a,c,m.c,m.d),e.splice(l,1,E[0],E[1],E[2],E[3]))},l=function(e,t,i,s){var u=[],a,f,l,c,h,p;if(s){e=[s].concat(e),f=e.length;while(--f>-1)typeof (p=e[f][t])=="string"&&p.charAt(1)==="="&&(e[f][t]=s[t]+Number(p.charAt(0)+p.substr(2)))}a=e.length-2;if(a<0)return u[0]=new o(e[0][t],0,0,e[a<-1?0:1][t]),u;for(f=0;f<a;f++)l=e[f][t],c=e[f+1][t],u[f]=new o(l,0,0,c),i&&(h=e[f+2][t],n[f]=(n[f]||0)+(c-l)*(c-l),r[f]=(r[f]||0)+(h-c)*(h-c));return u[f]=new o(e[f][t],0,0,e[f+1][t]),u},c=function(e,t,o,a,c,h){var p={},d=[],v=h||e[0],m,g,y,b,w,E,S,x;c=typeof c=="string"?","+c+",":u,t==null&&(t=1);for(g in e[0])d.push(g);if(e.length>1){x=e[e.length-1],S=!0,m=d.length;while(--m>-1){g=d[m];if(Math.abs(v[g]-x[g])>.05){S=!1;break}}S&&(e=e.concat(),h&&e.unshift(h),e.push(e[1]),h=e[e.length-3])}n.length=r.length=i.length=0,m=d.length;while(--m>-1)g=d[m],s[g]=c.indexOf(","+g+",")!==-1,p[g]=l(e,g,s[g],h);m=n.length;while(--m>-1)n[m]=Math.sqrt(n[m]),r[m]=Math.sqrt(r[m]);if(!a){m=d.length;while(--m>-1)if(s[g]){y=p[d[m]],E=y.length-1;for(b=0;b<E;b++)w=y[b+1].da/r[b]+y[b].da/n[b],i[b]=(i[b]||0)+w*w}m=i.length;while(--m>-1)i[m]=Math.sqrt(i[m])}m=d.length,b=o?4:1;while(--m>-1)g=d[m],y=p[g],f(y,t,o,a,s[g]),S&&(y.splice(0,b),y.splice(y.length-b,b));return p},h=function(e,t,n){t=t||"soft";var r={},i=t==="cubic"?3:2,s=t==="soft",u=[],a,f,l,c,h,p,d,v,m,g,y;s&&n&&(e=[n].concat(e));if(e==null||e.length<i+1)throw"invalid Bezier data";for(m in e[0])u.push(m);p=u.length;while(--p>-1){m=u[p],r[m]=h=[],g=0,v=e.length;for(d=0;d<v;d++)a=n==null?e[d][m]:typeof (y=e[d][m])=="string"&&y.charAt(1)==="="?n[m]+Number(y.charAt(0)+y.substr(2)):Number(y),s&&d>1&&d<v-1&&(h[g++]=(a+h[g-2])/2),h[g++]=a;v=g-i+1,g=0;for(d=0;d<v;d+=i)a=h[d],f=h[d+1],l=h[d+2],c=i===2?0:h[d+3],h[g++]=y=i===3?new o(a,f,l,c):new o(a,(2*f+a)/3,(2*f+l)/3,l);h.length=g}return r},p=function(e,t,n){var r=1/n,i=e.length,s,o,u,a,f,l,c,h,p,d,v;while(--i>-1){d=e[i],u=d.a,a=d.d-u,f=d.c-u,l=d.b-u,s=o=0;for(h=1;h<=n;h++)c=r*h,p=1-c,s=o-(o=(c*c*a+3*p*(c*f+p*l))*c),v=i*n+h-1,t[v]=(t[v]||0)+s*s}},d=function(e,t){t=t>>0||6;var n=[],r=[],i=0,s=0,o=t-1,u=[],a=[],f,l,c,h;for(f in e)p(e[f],n,t);c=n.length;for(l=0;l<c;l++)i+=Math.sqrt(n[l]),h=l%t,a[h]=i,h===o&&(s+=i,h=l/t>>0,u[h]=a,r[h]=s,i=0,a=[]);return{length:s,lengths:r,segments:u}},v=window._gsDefine.plugin({propName:"bezier",priority:-1,API:2,init:function(e,t,n){this._target=e,t instanceof Array&&(t={values:t}),this._func={},this._round={},this._props=[],this._timeRes=t.timeResolution==null?6:parseInt(t.timeResolution,10);var r=t.values||[],i={},s=r[0],o=t.autoRotate||n.vars.orientToBezier,u,a,f,l,p;this._autoRotate=o?o instanceof Array?o:[["x","y","rotation",o===!0?0:Number(o)||0]]:null;for(u in s)this._props.push(u);f=this._props.length;while(--f>-1)u=this._props[f],this._overwriteProps.push(u),a=this._func[u]=typeof e[u]=="function",i[u]=a?e[u.indexOf("set")||typeof e["get"+u.substr(3)]!="function"?u:"get"+u.substr(3)]():parseFloat(e[u]),p||i[u]!==r[0][u]&&(p=i);this._beziers=t.type!=="cubic"&&t.type!=="quadratic"&&t.type!=="soft"?c(r,isNaN(t.curviness)?1:t.curviness,!1,t.type==="thruBasic",t.correlate,p):h(r,t.type,i),this._segCount=this._beziers[u].length;if(this._timeRes){var v=d(this._beziers,this._timeRes);this._length=v.length,this._lengths=v.lengths,this._segments=v.segments,this._l1=this._li=this._s1=this._si=0,this._l2=this._lengths[0],this._curSeg=this._segments[0],this._s2=this._curSeg[0],this._prec=1/this._curSeg.length}if(o=this._autoRotate){o[0]instanceof Array||(this._autoRotate=o=[o]),f=o.length;while(--f>-1)for(l=0;l<3;l++)u=o[f][l],this._func[u]=typeof e[u]=="function"?e[u.indexOf("set")||typeof e["get"+u.substr(3)]!="function"?u:"get"+u.substr(3)]:!1}return!0},set:function(t){var n=this._segCount,r=this._func,i=this._target,s,o,u,a,f,l,c,h,p,d;if(!this._timeRes)s=t<0?0:t>=1?n-1:n*t>>0,l=(t-s*(1/n))*n;else{p=this._lengths,d=this._curSeg,t*=this._length,u=this._li;if(t>this._l2&&u<n-1){h=n-1;while(u<h&&(this._l2=p[++u])<=t);this._l1=p[u-1],this._li=u,this._curSeg=d=this._segments[u],this._s2=d[this._s1=this._si=0]}else if(t<this._l1&&u>0){while(u>0&&(this._l1=p[--u])>=t);u===0&&t<this._l1?this._l1=0:u++,this._l2=p[u],this._li=u,this._curSeg=d=this._segments[u],this._s1=d[(this._si=d.length-1)-1]||0,this._s2=d[this._si]}s=u,t-=this._l1,u=this._si;if(t>this._s2&&u<d.length-1){h=d.length-1;while(u<h&&(this._s2=d[++u])<=t);this._s1=d[u-1],this._si=u}else if(t<this._s1&&u>0){while(u>0&&(this._s1=d[--u])>=t);u===0&&t<this._s1?this._s1=0:u++,this._s2=d[u],this._si=u}l=(u+(t-this._s1)/(this._s2-this._s1))*this._prec}o=1-l,u=this._props.length;while(--u>-1)a=this._props[u],f=this._beziers[a][s],c=(l*l*f.da+3*o*(l*f.ca+o*f.ba))*l+f.a,this._round[a]&&(c=c+(c>0?.5:-0.5)>>0),r[a]?i[a](c):i[a]=c;if(this._autoRotate){var v=this._autoRotate,m,g,y,b,w,E,S;u=v.length;while(--u>-1)a=v[u][2],E=v[u][3]||0,S=v[u][4]===!0?1:e,f=this._beziers[v[u][0]][s],m=this._beziers[v[u][1]][s],g=f.a+(f.b-f.a)*l,b=f.b+(f.c-f.b)*l,g+=(b-g)*l,b+=(f.c+(f.d-f.c)*l-b)*l,y=m.a+(m.b-m.a)*l,w=m.b+(m.c-m.b)*l,y+=(w-y)*l,w+=(m.c+(m.d-m.c)*l-w)*l,c=Math.atan2(w-y,b-g)*S+E,r[a]?r[a].call(i,c+3.1415):i[a]=c+3.1415}}}),m=v.prototype;v.bezierThrough=c,v.cubicToQuadratic=a,v._autoCSS=!0,v.quadraticToCubic=function(e,t,n){return new o(e,(2*t+e)/3,(2*t+n)/3,n)},v._cssRegister=function(){var e=window._gsDefine.globals.CSSPlugin;if(!e)return;var n=e._internals,r=n._parseToProxy,i=n._setPluginRatio,s=n.CSSPropTween;n._registerComplexSpecialProp("bezier",{parser:function(e,n,o,u,a,f){n instanceof Array&&(n={values:n}),f=new v;var l=n.values,c=l.length-1,h=[],p={},d,m,g;if(c<0)return a;for(d=0;d<=c;d++)g=r(e,l[d],u,a,f,c!==d),h[d]=g.end;for(m in n)p[m]=n[m];return p.values=h,a=new s(e,"bezier",0,0,g.pt,2),a.data=g,a.plugin=f,a.setRatio=i,p.autoRotate===0&&(p.autoRotate=!0),p.autoRotate&&!(p.autoRotate instanceof Array)&&(d=p.autoRotate===!0?0:Number(p.autoRotate)*t,p.autoRotate=g.end.left!=null?[["left","top","rotation",d,!0]]:g.end.x!=null?[["x","y","rotation",d,!0]]:!1),p.autoRotate&&(u._transform||u._enableTransforms(!1),g.autoRotate=u._target._gsTransform),f._onInitTween(g.proxy,p,u._tween),a}})},m._roundProps=function(e,t){var n=this._overwriteProps,r=n.length;while(--r>-1)if(e[n[r]]||e.bezier||e.bezierThrough)this._round[n[r]]=t},m._kill=function(e){var t=this._props,n,r;for(n in this._beziers)if(n in e){delete this._beziers[n],delete this._func[n],r=t.length;while(--r>-1)t[r]===n&&t.splice(r,1)}return this._super._kill.call(this,e)}}(),window._gsDefine("plugins.CSSPlugin",["plugins.TweenPlugin","TweenLite"],function(e,t){var n=function(){e.call(this,"css"),this._overwriteProps.length=0},r,i,s,o,u={},a=n.prototype=new e("css");a.constructor=n,n.version="1.9.1",n.API=2,n.defaultTransformPerspective=0,a="px",n.suffixMap={top:a,right:a,bottom:a,left:a,width:a,height:a,fontSize:a,padding:a,margin:a,perspective:a};var f=/(?:\d|\-\d|\.\d|\-\.\d)+/g,l=/(?:\d|\-\d|\.\d|\-\.\d|\+=\d|\-=\d|\+=.\d|\-=\.\d)+/g,c=/(?:\+=|\-=|\-|\b)[\d\-\.]+[a-zA-Z0-9]*(?:%|\b)/gi,h=/[^\d\-\.]/g,p=/(?:\d|\-|\+|=|#|\.)*/g,d=/opacity *= *([^)]*)/,v=/opacity:([^;]*)/,m=/alpha\(opacity *=.+?\)/i,g=/([A-Z])/g,y=/-([a-z])/gi,b=/(^(?:url\(\"|url\())|(?:(\"\))$|\)$)/gi,w=function(e,t){return t.toUpperCase()},E=/(?:Left|Right|Width)/i,S=/(M11|M12|M21|M22)=[\d\-\.e]+/gi,x=/progid\:DXImageTransform\.Microsoft\.Matrix\(.+?\)/i,T=/,(?=[^\)]*(?:\(|$))/gi,N=Math.PI/180,C=180/Math.PI,k={},L=document,A=L.createElement("div"),O=L.createElement("img"),M=n._internals={_specialProps:u},_=navigator.userAgent,D,P,H,B,j,F,I=function(){var e=_.indexOf("Android"),t=L.createElement("div"),n;return H=_.indexOf("Safari")!==-1&&_.indexOf("Chrome")===-1&&(e===-1||Number(_.substr(e+8,1))>3),j=H&&Number(_.substr(_.indexOf("Version/")+8,1))<6,B=_.indexOf("Firefox")!==-1,/MSIE ([0-9]{1,}[\.0-9]{0,})/.exec(_),F=parseFloat(RegExp.$1),t.innerHTML="<a style='top:1px;opacity:.55;'>a</a>",n=t.getElementsByTagName("a")[0],n?/^0.55/.test(n.style.opacity):!1}(),q=function(e){return d.test(typeof e=="string"?e:(e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?parseFloat(RegExp.$1)/100:1},R=function(e){window.console&&console.log(e)},U="",z="",W=function(e,t){t=t||A;var n=t.style,r,i;if(n[e]!==undefined)return e;e=e.charAt(0).toUpperCase()+e.substr(1),r=["O","Moz","ms","Ms","Webkit"],i=5;while(--i>-1&&n[r[i]+e]===undefined);return i>=0?(z=i===3?"ms":r[i],U="-"+z.toLowerCase()+"-",z+e):null},X=L.defaultView?L.defaultView.getComputedStyle:function(){},V=n.getStyle=function(e,t,n,r,i){var s;return!I&&t==="opacity"?q(e):(!r&&e.style[t]?s=e.style[t]:(n=n||X(e,null))?(e=n.getPropertyValue(t.replace(g,"-$1").toLowerCase()),s=e||n.length?e:n[t]):e.currentStyle&&(n=e.currentStyle,s=n[t]),i==null||!!s&&s!=="none"&&s!=="auto"&&s!=="auto auto"?s:i)},$=function(e,t,n){var r={},i=e._gsOverwrittenClassNamePT,s,o;if(i&&!n){while(i)i.setRatio(0),i=i._next;e._gsOverwrittenClassNamePT=null}if(t=t||X(e,null))if(s=t.length)while(--s>-1)r[t[s].replace(y,w)]=t.getPropertyValue(t[s]);else for(s in t)r[s]=t[s];else if(t=e.currentStyle||e.style)for(s in t)r[s.replace(y,w)]=t[s];return I||(r.opacity=q(e)),o=xt(e,t,!1),r.rotation=o.rotation*C,r.skewX=o.skewX*C,r.scaleX=o.scaleX,r.scaleY=o.scaleY,r.x=o.x,r.y=o.y,St&&(r.z=o.z,r.rotationX=o.rotationX*C,r.rotationY=o.rotationY*C,r.scaleZ=o.scaleZ),r.filters&&delete r.filters,r},J=function(e,t,n,r){var i={},s=e.style,o,u,a;for(u in n)u!=="cssText"&&u!=="length"&&isNaN(u)&&t[u]!==(o=n[u])&&u.indexOf("Origin")===-1&&(typeof o=="number"||typeof o=="string")&&(i[u]=o!==""&&o!=="auto"&&o!=="none"||typeof t[u]!="string"||t[u].replace(h,"")===""?o:0,s[u]!==undefined&&(a=new lt(s,u,s[u],a)));if(r)for(u in r)u!=="className"&&(i[u]=r[u]);return{difs:i,firstMPT:a}},K={width:["Left","Right"],height:["Top","Bottom"]},Q=["marginLeft","marginRight","marginTop","marginBottom"],G=function(e,t,n){var r=parseFloat(t==="width"?e.offsetWidth:e.offsetHeight),i=K[t],s=i.length;n=n||X(e,null);while(--s>-1)r-=parseFloat(V(e,"padding"+i[s],n,!0))||0,r-=parseFloat(V(e,"border"+i[s]+"Width",n,!0))||0;return r},Y=function(e,t,n,r,i){if(r==="px"||!r)return n;if(r==="auto"||!n)return 0;var s=E.test(t),o=e,u=A.style,a=n<0,f;return a&&(n=-n),r==="%"&&t.indexOf("border")!==-1?f=n/100*(s?e.clientWidth:e.clientHeight):(u.cssText="border-style:solid; border-width:0; position:absolute; line-height:0;",r==="%"||!o.appendChild?(o=e.parentNode||L.body,u[s?"width":"height"]=n+r):u[s?"borderLeftWidth":"borderTopWidth"]=n+r,o.appendChild(A),f=parseFloat(A[s?"offsetWidth":"offsetHeight"]),o.removeChild(A),f===0&&!i&&(f=Y(e,t,n,r,!0))),a?-f:f},Z=function(e,t){if(e==null||e===""||e==="auto"||e==="auto auto")e="0 0";var n=e.split(" "),r=e.indexOf("left")!==-1?"0%":e.indexOf("right")!==-1?"100%":n[0],i=e.indexOf("top")!==-1?"0%":e.indexOf("bottom")!==-1?"100%":n[1];i==null?i="0":i==="center"&&(i="50%");if(r==="center"||isNaN(parseFloat(r)))r="50%";return t&&(t.oxp=r.indexOf("%")!==-1,t.oyp=i.indexOf("%")!==-1,t.oxr=r.charAt(1)==="=",t.oyr=i.charAt(1)==="=",t.ox=parseFloat(r.replace(h,"")),t.oy=parseFloat(i.replace(h,""))),r+" "+i+(n.length>2?" "+n[2]:"")},et=function(e,t){return typeof e=="string"&&e.charAt(1)==="="?parseInt(e.charAt(0)+"1",10)*parseFloat(e.substr(2)):parseFloat(e)-parseFloat(t)},tt=function(e,t){return e==null?t:typeof e=="string"&&e.charAt(1)==="="?parseInt(e.charAt(0)+"1",10)*Number(e.substr(2))+t:parseFloat(e)},nt=function(e,t,n,r){var i=1e-6,s,o,u,a,f;return e==null?f=t:typeof e=="number"?f=e*N:(s=Math.PI*2,o=e.split("_"),u=Number(o[0].replace(h,""))*(e.indexOf("rad")===-1?N:1)-(e.charAt(1)==="="?0:t),a=o[1],a&&r&&(r[n]=t+u),a==="short"?(u%=s,u!==u%(s/2)&&(u=u<0?u+s:u-s)):a==="cw"&&u<0?u=(u+s*9999999999)%s-(u/s|0)*s:a==="ccw"&&u>0&&(u=(u-s*9999999999)%s-(u/s|0)*s),f=t+u),f<i&&f>-i&&(f=0),f},rt={aqua:[0,255,255],lime:[0,255,0],silver:[192,192,192],black:[0,0,0],maroon:[128,0,0],teal:[0,128,128],blue:[0,0,255],navy:[0,0,128],white:[255,255,255],fuchsia:[255,0,255],olive:[128,128,0],yellow:[255,255,0],orange:[255,165,0],gray:[128,128,128],purple:[128,0,128],green:[0,128,0],red:[255,0,0],pink:[255,192,203],cyan:[0,255,255],transparent:[255,255,255,0]},it=function(e,t,n){return e=e<0?e+1:e>1?e-1:e,(e*6<1?t+(n-t)*e*6:e<.5?n:e*3<2?t+(n-t)*(2/3-e)*6:t)*255+.5|0},st=function(e){var t,n,r,i,s,o;return!e||e===""?rt.black:typeof e=="number"?[e>>16,e>>8&255,e&255]:(e.charAt(e.length-1)===","&&(e=e.substr(0,e.length-1)),rt[e]?rt[e]:e.charAt(0)==="#"?(e.length===4&&(t=e.charAt(1),n=e.charAt(2),r=e.charAt(3),e="#"+t+t+n+n+r+r),e=parseInt(e.substr(1),16),[e>>16,e>>8&255,e&255]):e.substr(0,3)==="hsl"?(e=e.match(f),i=Number(e[0])%360/360,s=Number(e[1])/100,o=Number(e[2])/100,n=o<=.5?o*(s+1):o+s-o*s,t=o*2-n,e.length>3&&(e[3]=Number(e[3])),e[0]=it(i+1/3,t,n),e[1]=it(i,t,n),e[2]=it(i-1/3,t,n),e):(e=e.match(f)||rt.transparent,e[0]=Number(e[0]),e[1]=Number(e[1]),e[2]=Number(e[2]),e.length>3&&(e[3]=Number(e[3])),e))},ot="(?:\\b(?:(?:rgb|rgba|hsl|hsla)\\(.+?\\))|\\B#.+?\\b";for(a in rt)ot+="|"+a+"\\b";ot=new RegExp(ot+")","gi");var ut=function(e,t,n,r){if(e==null)return function(e){return e};var i=t?(e.match(ot)||[""])[0]:"",s=e.split(i).join("").match(c)||[],o=e.substr(0,e.indexOf(s[0])),u=e.charAt(e.length-1)===")"?")":"",a=e.indexOf(" ")!==-1?" ":",",l=s.length,h=l>0?s[0].replace(f,""):"",p;return l?t?(p=function(e){var t,f,d,v;if(typeof e=="number")e+=h;else if(r&&T.test(e)){v=e.replace(T,"|").split("|");for(d=0;d<v.length;d++)v[d]=p(v[d]);return v.join(",")}t=(e.match(ot)||[i])[0],f=e.split(t).join("").match(c)||[],d=f.length;if(l>d--)while(++d<l)f[d]=n?f[(d-1)/2>>0]:s[d];return o+f.join(a)+a+t+u+(e.indexOf("inset")!==-1?" inset":"")},p):(p=function(e){var t,i,f;if(typeof e=="number")e+=h;else if(r&&T.test(e)){i=e.replace(T,"|").split("|");for(f=0;f<i.length;f++)i[f]=p(i[f]);return i.join(",")}t=e.match(c)||[],f=t.length;if(l>f--)while(++f<l)t[f]=n?t[(f-1)/2>>0]:s[f];return o+t.join(a)+u},p):function(e){return e}},at=function(e){return e=e.split(","),function(t,n,r,i,s,o,u){var a=(n+"").split(" "),f;u={};for(f=0;f<4;f++)u[e[f]]=a[f]=a[f]||a[(f-1)/2>>0];return i.parse(t,u,s,o)}},ft=M._setPluginRatio=function(e){this.plugin.setRatio(e);var t=this.data,n=t.proxy,r=t.firstMPT,i=1e-6,s,o,u,a;while(r)s=n[r.v],r.r?s=s>0?s+.5>>0:s-.5>>0:s<i&&s>-i&&(s=0),r.t[r.p]=s,r=r._next;t.autoRotate&&(t.autoRotate.rotation=n.rotation);if(e===1){r=t.firstMPT;while(r){o=r.t;if(!o.type)o.e=o.s+o.xs0;else if(o.type===1){a=o.xs0+o.s+o.xs1;for(u=1;u<o.l;u++)a+=o["xn"+u]+o["xs"+(u+1)];o.e=a}r=r._next}}},lt=function(e,t,n,r,i){this.t=e,this.p=t,this.v=n,this.r=i,r&&(r._prev=this,this._next=r)},ct=M._parseToProxy=function(e,t,n,r,i,s){var o=r,u={},a={},f=n._transform,l=k,c,h,p,d,v;n._transform=null,k=t,r=v=n.parse(e,t,r,i),k=l,s&&(n._transform=f,o&&(o._prev=null,o._prev&&(o._prev._next=null)));while(r&&r!==o){if(r.type<=1){h=r.p,a[h]=r.s+r.c,u[h]=r.s,s||(d=new lt(r,"s",h,d,r.r),r.c=0);if(r.type===1){c=r.l;while(--c>0)p="xn"+c,h=r.p+"_"+p,a[h]=r.data[p],u[h]=r[p],s||(d=new lt(r,p,h,d,r.rxp[p]))}}r=r._next}return{proxy:u,end:a,firstMPT:d,pt:v}},ht=M.CSSPropTween=function(e,t,n,i,s,u,a,f,l,c,h){this.t=e,this.p=t,this.s=n,this.c=i,this.n=a||"css_"+t,e instanceof ht||o.push(this.n),this.r=f,this.type=u||0,l&&(this.pr=l,r=!0),this.b=c===undefined?n:c,this.e=h===undefined?n+i:h,s&&(this._next=s,s._prev=this)},pt=n.parseComplex=function(e,t,n,r,i,s,o,u,a,c){o=new ht(e,t,0,0,o,c?2:1,null,!1,u,n,r),r+="";var h=n.split(", ").join(",").split(" "),p=r.split(", ").join(",").split(" "),d=h.length,v=D!==!1,m,g,y,b,w,E,S,x,N,C,k,L;if(r.indexOf(",")!==-1||n.indexOf(",")!==-1)h=h.join(" ").replace(T,", ").split(" "),p=p.join(" ").replace(T,", ").split(" "),d=h.length;d!==p.length&&(h=(s||"").split(" "),d=h.length),o.plugin=a,o.setRatio=c;for(m=0;m<d;m++){b=h[m],w=p[m],x=parseFloat(b);if(x||x===0)o.appendXtra("",x,et(w,x),w.replace(l,""),v&&w.indexOf("px")!==-1,!0);else if(i&&(b.charAt(0)==="#"||b.indexOf("rgb")===0||rt[b]||b.indexOf("hsl")===0))L=w.charAt(w.length-1)===","?"),":")",b=st(b),w=st(w),N=b.length+w.length>6,N&&!I&&w[3]===0?(o["xs"+o.l]+=o.l?" transparent":"transparent",o.e=o.e.split(p[m]).join("transparent")):(I||(N=!1),o.appendXtra(N?"rgba(":"rgb(",b[0],w[0]-b[0],",",!0,!0).appendXtra("",b[1],w[1]-b[1],",",!0).appendXtra("",b[2],w[2]-b[2],N?",":L,!0),N&&(b=b.length<4?1:b[3],o.appendXtra("",b,(w.length<4?1:w[3])-b,L,!1)));else{E=b.match(f);if(!E)o["xs"+o.l]+=o.l?" "+b:b;else{S=w.match(l);if(!S||S.length!==E.length)return o;y=0;for(g=0;g<E.length;g++)k=E[g],C=b.indexOf(k,y),o.appendXtra(b.substr(y,C-y),Number(k),et(S[g],k),"",v&&b.substr(C+k.length,2)==="px",g===0),y=C+k.length;o["xs"+o.l]+=b.substr(y)}}}if(r.indexOf("=")!==-1&&o.data){L=o.xs0+o.data.s;for(m=1;m<o.l;m++)L+=o["xs"+m]+o.data["xn"+m];o.e=L+o["xs"+m]}return o.l||(o.type=-1,o.xs0=o.e),o.xfirst||o},dt=9;a=ht.prototype,a.l=a.pr=0;while(--dt>0)a["xn"+dt]=0,a["xs"+dt]="";a.xs0="",a._next=a._prev=a.xfirst=a.data=a.plugin=a.setRatio=a.rxp=null,a.appendXtra=function(e,t,n,r,i,s){var o=this,u=o.l;return o["xs"+u]+=s&&u?" "+e:e||"",!n&&u!==0&&!o.plugin?(o["xs"+u]+=t+(r||""),o):(o.l++,o.type=o.setRatio?2:1,o["xs"+o.l]=r||"",u>0?(o.data["xn"+u]=t+n,o.rxp["xn"+u]=i,o["xn"+u]=t,o.plugin||(o.xfirst=new ht(o,"xn"+u,t,n,o.xfirst||o,0,o.n,i,o.pr),o.xfirst.xs0=0),o):(o.data={s:t+n},o.rxp={},o.s=t,o.c=n,o.r=i,o))};var vt=function(e,t){t=t||{},this.p=t.prefix?W(e)||e:e,u[e]=u[this.p]=this,this.format=t.formatter||ut(t.defaultValue,t.color,t.collapsible,t.multi),t.parser&&(this.parse=t.parser),this.clrs=t.color,this.multi=t.multi,this.keyword=t.keyword,this.dflt=t.defaultValue,this.pr=t.priority||0},mt=M._registerComplexSpecialProp=function(e,t,n){typeof t!="object"&&(t={parser:n});var r=e.split(","),i=t.defaultValue,s,o;n=n||[i];for(s=0;s<r.length;s++)t.prefix=s===0&&t.prefix,t.defaultValue=n[s]||i,o=new vt(r[s],t)},gt=function(e){if(!u[e]){var t=e.charAt(0).toUpperCase()+e.substr(1)+"Plugin";mt(e,{parser:function(e,n,r,i,s,o,a){var f=(window.GreenSockGlobals||window).com.greensock.plugins[t];return f?(f._cssRegister(),u[r].parse(e,n,r,i,s,o,a)):(R("Error: "+t+" js file not loaded."),s)}})}};a=vt.prototype,a.parseComplex=function(e,t,n,r,i,s){var o=this.keyword,u,a,f,l,c,h;this.multi&&(T.test(n)||T.test(t)?(a=t.replace(T,"|").split("|"),f=n.replace(T,"|").split("|")):o&&(a=[t],f=[n]));if(f){l=f.length>a.length?f.length:a.length;for(u=0;u<l;u++)t=a[u]=a[u]||this.dflt,n=f[u]=f[u]||this.dflt,o&&(c=t.indexOf(o),h=n.indexOf(o),c!==h&&(n=h===-1?f:a,n[u]+=" "+o));t=a.join(", "),n=f.join(", ")}return pt(e,this.p,t,n,this.clrs,this.dflt,r,this.pr,i,s)},a.parse=function(e,t,n,r,i,o,u){return this.parseComplex(e.style,this.format(V(e,this.p,s,!1,this.dflt)),this.format(t),i,o)},n.registerSpecialProp=function(e,t,n){mt(e,{parser:function(e,r,i,s,o,u,a){var f=new ht(e,i,0,0,o,2,i,!1,n);return f.plugin=u,f.setRatio=t(e,r,s._tween,i),f},priority:n})};var yt="scaleX,scaleY,scaleZ,x,y,z,skewX,rotation,rotationX,rotationY,perspective".split(","),bt=W("transform"),wt=U+"transform",Et=W("transformOrigin"),St=W("perspective")!==null,xt=function(e,t,r){var i=r?e._gsTransform||{skewY:0}:{skewY:0},s=i.scaleX<0,o=2e-5,u=1e5,a=-Math.PI+1e-4,f=Math.PI-1e-4,l=St?parseFloat(V(e,Et,t,!1,"0 0 0").split(" ")[2])||i.zOrigin||0:0,c,h,p,d,v,m,g,y,b,w,E,x,T;bt?c=V(e,wt,t,!0):e.currentStyle&&(c=e.currentStyle.filter.match(S),c=c&&c.length===4?c[0].substr(4)+","+Number(c[2].substr(4))+","+Number(c[1].substr(4))+","+c[3].substr(4)+","+(i?i.x:0)+","+(i?i.y:0):null),h=(c||"").match(/(?:\-|\b)[\d\-\.e]+\b/gi)||[],p=h.length;while(--p>-1)d=Number(h[p]),h[p]=(v=d-(d|=0))?(v*u+(v<0?-0.5:.5)|0)/u+d:d;if(h.length===16){var N=h[8],C=h[9],k=h[10],L=h[12],A=h[13],O=h[14];i.zOrigin&&(O=-i.zOrigin,L=N*O-h[12],A=C*O-h[13],O=k*O+i.zOrigin-h[14]);if(!r||L!==i.x||A!==i.y||O!==i.z){var M=h[0],_=h[1],D=h[2],P=h[3],H=h[4],B=h[5],j=h[6],F=h[7],I=h[11],q=i.rotationX=Math.atan2(j,k),R=q<a||q>f,U,z,W,X,$,J,K,Q;q&&($=Math.cos(-q),J=Math.sin(-q),U=H*$+N*J,z=B*$+C*J,W=j*$+k*J,X=F*$+I*J,N=H*-J+N*$,C=B*-J+C*$,k=j*-J+k*$,I=F*-J+I*$,H=U,B=z,j=W),q=i.rotationY=Math.atan2(N,M),q&&(K=q<a||q>f,$=Math.cos(-q),J=Math.sin(-q),U=M*$-N*J,z=_*$-C*J,W=D*$-k*J,X=P*$-I*J,C=_*J+C*$,k=D*J+k*$,I=P*J+I*$,M=U,_=z,D=W),q=i.rotation=Math.atan2(_,B),q&&(Q=q<a||q>f,$=Math.cos(-q),J=Math.sin(-q),M=M*$+H*J,z=_*$+B*J,B=_*-J+B*$,j=D*-J+j*$,_=z),Q&&R?i.rotation=i.rotationX=0:Q&&K?i.rotation=i.rotationY=0:K&&R&&(i.rotationY=i.rotationX=0),i.scaleX=(Math.sqrt(M*M+_*_)*u+.5>>0)/u,i.scaleY=(Math.sqrt(B*B+C*C)*u+.5>>0)/u,i.scaleZ=(Math.sqrt(j*j+k*k)*u+.5>>0)/u,i.skewX=0,i.perspective=I?1/(I<0?-I:I):0,i.x=L,i.y=A,i.z=O}}else if(!St||h.length===0||i.x!==h[4]||i.y!==h[5]||!i.rotationX&&!i.rotationY){var G=h.length>=6,Y=G?h[0]:1,Z=h[1]||0,et=h[2]||0,tt=G?h[3]:1;i.x=h[4]||0,i.y=h[5]||0,m=Math.sqrt(Y*Y+Z*Z),g=Math.sqrt(tt*tt+et*et),y=Y||Z?Math.atan2(Z,Y):i.rotation||0,b=et||tt?Math.atan2(et,tt)+y:i.skewX||0,w=m-Math.abs(i.scaleX||0),E=g-Math.abs(i.scaleY||0),Math.abs(b)>Math.PI/2&&Math.abs(b)<Math.PI*1.5&&(s?(m*=-1,b+=y<=0?Math.PI:-Math.PI,y+=y<=0?Math.PI:-Math.PI):(g*=-1,b+=b<=0?Math.PI:-Math.PI)),x=(y-i.rotation)%Math.PI,T=(b-i.skewX)%Math.PI;if(i.skewX===undefined||w>o||w<-o||E>o||E<-o||x>a&&x<f&&x*u>>0!==0||T>a&&T<f&&T*u>>0!==0)i.scaleX=m,i.scaleY=g,i.rotation=y,i.skewX=b;St&&(i.rotationX=i.rotationY=i.z=0,i.perspective=parseFloat(n.defaultTransformPerspective)||0,i.scaleZ=1)}i.zOrigin=l;for(p in i)i[p]<o&&i[p]>-o&&(i[p]=0);return r&&(e._gsTransform=i),i},Tt=function(e){var t=this.data,n=-t.rotation,r=n+t.skewX,i=1e5,s=(Math.cos(n)*t.scaleX*i>>0)/i,o=(Math.sin(n)*t.scaleX*i>>0)/i,u=(Math.sin(r)*-t.scaleY*i>>0)/i,a=(Math.cos(r)*t.scaleY*i>>0)/i,f=this.t.style,l=this.t.currentStyle,c,h;if(!l)return;h=o,o=-u,u=-h,c=l.filter,f.filter="";var v=this.t.offsetWidth,m=this.t.offsetHeight,g=l.position!=="absolute",y="progid:DXImageTransform.Microsoft.Matrix(M11="+s+", M12="+o+", M21="+u+", M22="+a,b=t.x,w=t.y,E,S;t.ox!=null&&(E=(t.oxp?v*t.ox*.01:t.ox)-v/2,S=(t.oyp?m*t.oy*.01:t.oy)-m/2,b+=E-(E*s+S*o),w+=S-(E*u+S*a));if(!g){var T=F<8?1:-1,N,C,k;E=t.ieOffsetX||0,S=t.ieOffsetY||0,t.ieOffsetX=Math.round((v-((s<0?-s:s)*v+(o<0?-o:o)*m))/2+b),t.ieOffsetY=Math.round((m-((a<0?-a:a)*m+(u<0?-u:u)*v))/2+w);for(dt=0;dt<4;dt++)C=Q[dt],N=l[C],h=N.indexOf("px")!==-1?parseFloat(N):Y(this.t,C,parseFloat(N),N.replace(p,""))||0,h!==t[C]?k=dt<2?-t.ieOffsetX:-t.ieOffsetY:k=dt<2?E-t.ieOffsetX:S-t.ieOffsetY,f[C]=(t[C]=Math.round(h-k*(dt===0||dt===2?1:T)))+"px";y+=", sizingMethod='auto expand')"}else E=v/2,S=m/2,y+=", Dx="+(E-(E*s+S*o)+b)+", Dy="+(S-(E*u+S*a)+w)+")";c.indexOf("DXImageTransform.Microsoft.Matrix(")!==-1?f.filter=c.replace(x,y):f.filter=y+" "+c,(e===0||e===1)&&s===1&&o===0&&u===0&&a===1&&(!g||y.indexOf("Dx=0, Dy=0")!==-1)&&(!d.test(c)||parseFloat(RegExp.$1)===100)&&c.indexOf("gradient(")===-1&&f.removeAttribute("filter")},Nt=function(e){var t=this.data,n=this.t.style,r=t.perspective,i=t.scaleX,s=0,o=0,u=0,a=0,f=t.scaleY,l=0,c=0,h=0,p=0,d=t.scaleZ,v=0,m=0,g=0,y=r?-1/r:0,b=t.rotation,w=t.zOrigin,E=",",S=1e5,x,T,N,C,k,L,A,O,M;B&&(A=V(this.t,"top",null,!1,"0"),O=parseFloat(A)||0,M=A.substr((O+"").length),t._ffFix=!t._ffFix,n.top=(t._ffFix?O+.05:O-.05)+(M===""?"px":M));if(b||t.skewX)N=i*Math.cos(b),C=f*Math.sin(b),b-=t.skewX,s=i*-Math.sin(b),f*=Math.cos(b),i=N,a=C;b=t.rotationY,b&&(x=Math.cos(b),T=Math.sin(b),N=i*x,C=a*x,k=d*-T,L=y*-T,o=i*T,l=a*T,d*=x,y*=x,i=N,a=C,h=k,m=L),b=t.rotationX,b&&(x=Math.cos(b),T=Math.sin(b),N=s*x+o*T,C=f*x+l*T,k=p*x+d*T,L=g*x+y*T,o=s*-T+o*x,l=f*-T+l*x,d=p*-T+d*x,y=g*-T+y*x,s=N,f=C,p=k,g=L),w&&(v-=w,u=o*v,c=l*v,v=d*v+w),u=(N=(u+=t.x)-(u|=0))?(N*S+(N<0?-0.5:.5)|0)/S+u:u,c=(N=(c+=t.y)-(c|=0))?(N*S+(N<0?-0.5:.5)|0)/S+c:c,v=(N=(v+=t.z)-(v|=0))?(N*S+(N<0?-0.5:.5)|0)/S+v:v,n[bt]="matrix3d("+(i*S>>0)/S+E+(a*S>>0)/S+E+(h*S>>0)/S+E+(m*S>>0)/S+E+(s*S>>0)/S+E+(f*S>>0)/S+E+(p*S>>0)/S+E+(g*S>>0)/S+E+(o*S>>0)/S+E+(l*S>>0)/S+E+(d*S>>0)/S+E+(y*S>>0)/S+E+u+E+c+E+v+E+(r?1+ -v/r:1)+")"},Ct=function(e){var t=this.data,n=this.t,r,i,s,o,u,a,f,l;B&&(r=V(n,"top",null,!1,"0"),i=parseFloat(r)||0,s=r.substr((i+"").length),t._ffFix=!t._ffFix,n.style.top=(t._ffFix?i+.05:i-.05)+(s===""?"px":s)),!t.rotation&&!t.skewX?n.style[bt]="matrix("+t.scaleX+",0,0,"+t.scaleY+","+t.x+","+t.y+")":(o=t.rotation,u=o-t.skewX,a=1e5,f=t.scaleX*a,l=t.scaleY*a,n.style[bt]="matrix("+(Math.cos(o)*f>>0)/a+","+(Math.sin(o)*f>>0)/a+","+(Math.sin(u)*-l>>0)/a+","+(Math.cos(u)*l>>0)/a+","+t.x+","+t.y+")")};mt("transform,scale,scaleX,scaleY,scaleZ,x,y,z,rotation,rotationX,rotationY,rotationZ,skewX,skewY,shortRotation,shortRotationX,shortRotationY,shortRotationZ,transformOrigin,transformPerspective,directionalRotation",{parser:function(e,t,n,r,i,o,u){if(r._transform)return i;var a=r._transform=xt(e,s,!0),f=e.style,l=1e-6,c=yt.length,h=u,p={},d,v,m,g,y,b,w;if(typeof h.transform=="string"&&bt)m=f.cssText,f[bt]=h.transform,f.display="block",d=xt(e,null,!1),f.cssText=m;else if(typeof h=="object"){d={scaleX:tt(h.scaleX!=null?h.scaleX:h.scale,a.scaleX),scaleY:tt(h.scaleY!=null?h.scaleY:h.scale,a.scaleY),scaleZ:tt(h.scaleZ!=null?h.scaleZ:h.scale,a.scaleZ),x:tt(h.x,a.x),y:tt(h.y,a.y),z:tt(h.z,a.z),perspective:tt(h.transformPerspective,a.perspective)},w=h.directionalRotation;if(w!=null)if(typeof w=="object")for(m in w)h[m]=w[m];else h.rotation=w;d.rotation=nt("rotation"in h?h.rotation:"shortRotation"in h?h.shortRotation+"_short":"rotationZ"in h?h.rotationZ:a.rotation*C,a.rotation,"rotation",p),St&&(d.rotationX=nt("rotationX"in h?h.rotationX:"shortRotationX"in h?h.shortRotationX+"_short":a.rotationX*C||0,a.rotationX,"rotationX",p),d.rotationY=nt("rotationY"in h?h.rotationY:"shortRotationY"in h?h.shortRotationY+"_short":a.rotationY*C||0,a.rotationY,"rotationY",p)),d.skewX=h.skewX==null?a.skewX:nt(h.skewX,a.skewX),d.skewY=h.skewY==null?a.skewY:nt(h.skewY,a.skewY);if(v=d.skewY-a.skewY)d.skewX+=v,d.rotation+=v}y=a.z||a.rotationX||a.rotationY||d.z||d.rotationX||d.rotationY||d.perspective,!y&&h.scale!=null&&(d.scaleZ=1);while(--c>-1){n=yt[c],g=d[n]-a[n];if(g>l||g<-l||k[n]!=null)b=!0,i=new ht(a,n,a[n],g,i),n in p&&(i.e=p[n]),i.xs0=0,i.plugin=o,r._overwriteProps.push(i.n)}g=h.transformOrigin;if(g||St&&y&&a.zOrigin)bt?(b=!0,g=(g||V(e,n,s,!1,"50% 50%"))+"",n=Et,i=new ht(f,n,0,0,i,-1,"css_transformOrigin"),i.b=f[n],i.plugin=o,St?(m=a.zOrigin,g=g.split(" "),a.zOrigin=(g.length>2?parseFloat(g[2]):m)||0,i.xs0=i.e=f[n]=g[0]+" "+(g[1]||"50%")+" 0px",i=new ht(a,"zOrigin",0,0,i,-1,i.n),i.b=m,i.xs0=i.e=a.zOrigin):i.xs0=i.e=f[n]=g):Z(g+"",a);return b&&(r._transformType=y||this._transformType===3?3:2),i},prefix:!0}),mt("boxShadow",{defaultValue:"0px 0px 0px 0px #999",prefix:!0,color:!0,multi:!0,keyword:"inset"}),mt("borderRadius",{defaultValue:"0px",parser:function(e,t,n,r,o,u){t=this.format(t);var a=["borderTopLeftRadius","borderTopRightRadius","borderBottomRightRadius","borderBottomLeftRadius"],f=e.style,l,c,h,p,d,v,m,g,y,b,w,E,S,x,T,N;y=parseFloat(e.offsetWidth),b=parseFloat(e.offsetHeight),l=t.split(" ");for(c=0;c<a.length;c++)this.p.indexOf("border")&&(a[c]=W(a[c])),d=p=V(e,a[c],s,!1,"0px"),d.indexOf(" ")!==-1&&(p=d.split(" "),d=p[0],p=p[1]),v=h=l[c],m=parseFloat(d),E=d.substr((m+"").length),S=v.charAt(1)==="=",S?(g=parseInt(v.charAt(0)+"1",10),v=v.substr(2),g*=parseFloat(v),w=v.substr((g+"").length-(g<0?1:0))||""):(g=parseFloat(v),w=v.substr((g+"").length)),w===""&&(w=i[n]||E),w!==E&&(x=Y(e,"borderLeft",m,E),T=Y(e,"borderTop",m,E),w==="%"?(d=x/y*100+"%",p=T/b*100+"%"):w==="em"?(N=Y(e,"borderLeft",1,"em"),d=x/N+"em",p=T/N+"em"):(d=x+"px",p=T+"px"),S&&(v=parseFloat(d)+g+w,h=parseFloat(p)+g+w)),o=pt(f,a[c],d+" "+p,v+" "+h,!1,"0px",o);return o},prefix:!0,formatter:ut("0px 0px 0px 0px",!1,!0)}),mt("backgroundPosition",{defaultValue:"0 0",parser:function(e,t,n,r,i,o){var u="background-position",a=s||X(e,null),f=this.format((a?F?a.getPropertyValue(u+"-x")+" "+a.getPropertyValue(u+"-y"):a.getPropertyValue(u):e.currentStyle.backgroundPositionX+" "+e.currentStyle.backgroundPositionY)||"0 0"),l=this.format(t),c,h,p,d,v,m;if(f.indexOf("%")!==-1!=(l.indexOf("%")!==-1)){m=V(e,"backgroundImage").replace(b,"");if(m&&m!=="none"){c=f.split(" "),h=l.split(" "),O.setAttribute("src",m),p=2;while(--p>-1)f=c[p],d=f.indexOf("%")!==-1,d!==(h[p].indexOf("%")!==-1)&&(v=p===0?e.offsetWidth-O.width:e.offsetHeight-O.height,c[p]=d?parseFloat(f)/100*v+"px":parseFloat(f)/v*100+"%");f=c.join(" ")}}return this.parseComplex(e.style,f,l,i,o)},formatter:Z}),mt("backgroundSize",{defaultValue:"0 0",formatter:Z}),mt("perspective",{defaultValue:"0px",prefix:!0}),mt("perspectiveOrigin",{defaultValue:"50% 50%",prefix:!0}),mt("transformStyle",{prefix:!0}),mt("backfaceVisibility",{prefix:!0}),mt("margin",{parser:at("marginTop,marginRight,marginBottom,marginLeft")}),mt("padding",{parser:at("paddingTop,paddingRight,paddingBottom,paddingLeft")}),mt("clip",{defaultValue:"rect(0px,0px,0px,0px)"}),mt("textShadow",{defaultValue:"0px 0px 0px #999",color:!0,multi:!0}),mt("autoRound,strictUnits",{parser:function(e,t,n,r,i){return i}}),mt("border",{defaultValue:"0px solid #000",parser:function(e,t,n,r,i,o){return this.parseComplex(e.style,this.format(V(e,"borderTopWidth",s,!1,"0px")+" "+V(e,"borderTopStyle",s,!1,"solid")+" "+V(e,"borderTopColor",s,!1,"#000")),this.format(t),i,o)},color:!0,formatter:function(e){var t=e.split(" ");return t[0]+" "+(t[1]||"solid")+" "+(e.match(ot)||["#000"])[0]}}),mt("float,cssFloat,styleFloat",{parser:function(e,t,n,r,i,s){var o=e.style,u="cssFloat"in o?"cssFloat":"styleFloat";return new ht(o,u,0,0,i,-1,n,!1,0,o[u],t)}});var kt=function(e){var t=this.t,n=t.filter,r=this.s+this.c*e>>0,i;r===100&&(n.indexOf("atrix(")===-1&&n.indexOf("radient(")===-1?(t.removeAttribute("filter"),i=!V(this.data,"filter")):(t.filter=n.replace(m,""),i=!0)),i||(this.xn1&&(t.filter=n=n||"alpha(opacity=100)"),n.indexOf("opacity")===-1?t.filter+=" alpha(opacity="+r+")":t.filter=n.replace(d,"opacity="+r))};mt("opacity,alpha,autoAlpha",{defaultValue:"1",parser:function(e,t,n,r,i,o){var u=parseFloat(V(e,"opacity",s,!1,"1")),a=e.style,f;return t=parseFloat(t),n==="autoAlpha"&&(f=V(e,"visibility",s),u===1&&f==="hidden"&&t!==0&&(u=0),i=new ht(a,"visibility",0,0,i,-1,null,!1,0,u!==0?"visible":"hidden",t===0?"hidden":"visible"),i.xs0="visible",r._overwriteProps.push(i.n)),I?i=new ht(a,"opacity",u,t-u,i):(i=new ht(a,"opacity",u*100,(t-u)*100,i),i.xn1=n==="autoAlpha"?1:0,a.zoom=1,i.type=2,i.b="alpha(opacity="+i.s+")",i.e="alpha(opacity="+(i.s+i.c)+")",i.data=e,i.plugin=o,i.setRatio=kt),i}});var Lt=function(e){if(e===1||e===0){this.t.className=e===1?this.e:this.b;var t=this.data,n=this.t.style,r=n.removeProperty?"removeProperty":"removeAttribute";while(t)t.v?n[t.p]=t.v:n[r](t.p.replace(g,"-$1").toLowerCase()),t=t._next}else this.t.className!==this.b&&(this.t.className=this.b)};mt("className",{parser:function(e,t,n,i,o,u,a){var f=e.className,l=e.style.cssText,c,h;return o=i._classNamePT=new ht(e,n,0,0,o,2),o.setRatio=Lt,o.pr=-11,r=!0,o.b=f,o.e=t.charAt(1)!=="="?t:t.charAt(0)==="+"?f+" "+t.substr(2):f.split(t.substr(2)).join(""),i._tween._duration&&(h=$(e,s,!0),e.className=o.e,c=J(e,h,$(e),a),e.className=f,o.data=c.firstMPT,e.style.cssText=l,o=o.xfirst=i.parse(e,c.difs,o,u)),o}});var At=function(e){if(e===1||e===0)if(this.data._totalTime===this.data._totalDuration){var t=this.e==="all",n=this.t.style,r=t?n.cssText.split(";"):this.e.split(","),i=n.removeProperty?"removeProperty":"removeAttribute",s=r.length,o=u.transform.parse,a;while(--s>-1)a=r[s],t&&(a=a.substr(0,a.indexOf(":")).split(" ").join("")),u[a]&&(a=u[a].parse===o?bt:u[a].p),a&&n[i](a.replace(g,"-$1").toLowerCase())}};mt("clearProps",{parser:function(e,t,n,i,s){return s=new ht(e,n,0,0,s,2),s.setRatio=At,s.e=t,s.pr=-10,s.data=i._tween,r=!0,s}}),a="bezier,throwProps,physicsProps,physics2D".split(","),dt=a.length;while(dt--)gt(a[dt]);return a=n.prototype,a._firstPT=null,a._onInitTween=function(e,t,u){if(!e.nodeType)return!1;this._target=e,this._tween=u,this._vars=t,D=t.autoRound,r=!1,i=t.suffixMap||n.suffixMap,s=X(e,""),o=this._overwriteProps;var a=e.style,f,l,c,h,p,d,m,g,y;if(P&&a.zIndex===""){f=V(e,"zIndex",s);if(f==="auto"||f==="")a.zIndex=0}typeof t=="string"&&(h=a.cssText,f=$(e,s),a.cssText=h+";"+t,f=J(e,f,$(e)).difs,!I&&v.test(t)&&(f.opacity=parseFloat(RegExp.$1)),t=f,a.cssText=h),this._firstPT=l=this.parse(e,t,null);if(this._transformType){y=this._transformType===3;if(!bt)a.zoom=1;else if(H){P=!0;if(a.zIndex===""){m=V(e,"zIndex",s);if(m==="auto"||m==="")a.zIndex=0}j&&(a.WebkitBackfaceVisibility=this._vars.WebkitBackfaceVisibility||(y?"visible":"hidden"))}c=l;while(c&&c._next)c=c._next;g=new ht(e,"transform",0,0,null,2),this._linkCSSP(g,null,c),g.setRatio=y&&St?Nt:bt?Ct:Tt,g.data=this._transform||xt(e,s,!0),o.pop()}if(r){while(l){d=l._next,c=h;while(c&&c.pr>l.pr)c=c._next;(l._prev=c?c._prev:p)?l._prev._next=l:h=l,(l._next=c)?c._prev=l:p=l,l=d}this._firstPT=h}return!0},a.parse=function(e,t,n,r){var o=e.style,a,f,l,c,h,d,v,m,g,y;for(a in t){d=t[a],f=u[a];if(f)n=f.parse(e,d,a,this,n,r,t);else{h=V(e,a,s)+"",g=typeof d=="string";if(a==="color"||a==="fill"||a==="stroke"||a.indexOf("Color")!==-1||g&&!d.indexOf("rgb"))g||(d=st(d),d=(d.length>3?"rgba(":"rgb(")+d.join(",")+")"),n=pt(o,a,h,d,!0,"transparent",n,0,r);else if(!g||d.indexOf(" ")===-1&&d.indexOf(",")===-1){l=parseFloat(h),v=l||l===0?h.substr((l+"").length):"";if(h===""||h==="auto")a==="width"||a==="height"?(l=G(e,a,s),v="px"):(l=a!=="opacity"?0:1,v="");y=g&&d.charAt(1)==="=",y?(c=parseInt(d.charAt(0)+"1",10),d=d.substr(2),c*=parseFloat(d),m=d.replace(p,"")):(c=parseFloat(d),m=g?d.substr((c+"").length)||"":""),m===""&&(m=i[a]||v),d=c||c===0?(y?c+l:c)+m:t[a],v!==m&&m!==""&&(c||c===0)&&(l||l===0)&&(l=Y(e,a,l,v),m==="%"?(l/=Y(e,a,100,"%")/100,l>100&&(l=100),t.strictUnits!==!0&&(h=l+"%")):m==="em"?l/=Y(e,a,1,"em"):(c=Y(e,a,c,m),m="px"),y&&(c||c===0)&&(d=c+l+m)),y&&(c+=l),!l&&l!==0||!c&&c!==0?!!d||d+""!="NaN"&&d!=null?(n=new ht(o,a,c||l||0,0,n,-1,"css_"+a,!1,0,h,d),n.xs0=a==="display"&&d==="none"?h:d):R("invalid "+a+" tween value: "+t[a]):(n=new ht(o,a,l,c-l,n,0,"css_"+a,D!==!1&&(m==="px"||a==="zIndex"),0,h,d),n.xs0=m)}else n=pt(o,a,h,d,!0,null,n,0,r)}r&&n&&!n.plugin&&(n.plugin=r)}return n},a.setRatio=function(e){var t=this._firstPT,n=1e-6,r,i,s;if(e!==1||this._tween._time!==this._tween._duration&&this._tween._time!==0)if(e||this._tween._time!==this._tween._duration&&this._tween._time!==0||this._tween._rawPrevTime===-0.000001)while(t){r=t.c*e+t.s,t.r?r=r>0?r+.5>>0:r-.5>>0:r<n&&r>-n&&(r=0);if(!t.type)t.t[t.p]=r+t.xs0;else if(t.type===1){s=t.l;if(s===2)t.t[t.p]=t.xs0+r+t.xs1+t.xn1+t.xs2;else if(s===3)t.t[t.p]=t.xs0+r+t.xs1+t.xn1+t.xs2+t.xn2+t.xs3;else if(s===4)t.t[t.p]=t.xs0+r+t.xs1+t.xn1+t.xs2+t.xn2+t.xs3+t.xn3+t.xs4;else if(s===5)t.t[t.p]=t.xs0+r+t.xs1+t.xn1+t.xs2+t.xn2+t.xs3+t.xn3+t.xs4+t.xn4+t.xs5;else{i=t.xs0+r+t.xs1;for(s=1;s<t.l;s++)i+=t["xn"+s]+t["xs"+(s+1)];t.t[t.p]=i}}else t.type===-1?t.t[t.p]=t.xs0:t.setRatio&&t.setRatio(e);t=t._next}else while(t)t.type!==2?t.t[t.p]=t.b:t.setRatio(e),t=t._next;else while(t)t.type!==2?t.t[t.p]=t.e:t.setRatio(e),t=t._next},a._enableTransforms=function(e){this._transformType=e||this._transformType===3?3:2},a._linkCSSP=function(e,t,n,r){return e&&(t&&(t._prev=e),e._next&&(e._next._prev=e._prev),n?n._next=e:!r&&this._firstPT===null&&(this._firstPT=e),e._prev?e._prev._next=e._next:this._firstPT===e&&(this._firstPT=e._next),e._next=t,e._prev=n),e},a._kill=function(t){var n=t,r=!1,i,s,o;if(t.css_autoAlpha||t.css_alpha){n={};for(s in t)n[s]=t[s];n.css_opacity=1,n.css_autoAlpha&&(n.css_visibility=1)}return t.css_className&&(i=this._classNamePT)&&(o=i.xfirst,o&&o._prev?this._linkCSSP(o._prev,i._next,o._prev._prev):o===this._firstPT&&(this._firstPT=null),i._next&&this._linkCSSP(i._next,i._next._next,o._prev),this._target._gsOverwrittenClassNamePT=this._linkCSSP(i,this._target._gsOverwrittenClassNamePT),this._classNamePT=null,r=!0),e.prototype._kill.call(this,n)||r},e.activate([n]),n},!0),function(){var e=window._gsDefine.plugin({propName:"roundProps",priority:-1,API:2,init:function(e,t,n){return this._tween=n,!0}}),t=e.prototype;t._onInitAllProps=function(){var e=this._tween,t=e.vars.roundProps instanceof Array?e.vars.roundProps:e.vars.roundProps.split(","),n=t.length,r={},i=e._propLookup.roundProps,s,o,u;while(--n>-1)r[t[n]]=1;n=t.length;while(--n>-1){s=t[n],o=e._firstPT;while(o)u=o._next,o.pg?o.t._roundProps(r,!0):o.n===s&&(this._add(o.t,s,o.s,o.c),u&&(u._prev=o._prev),o._prev?o._prev._next=u:e._firstPT===o&&(e._firstPT=u),o._next=o._prev=null,e._propLookup[s]=i),o=u}return!1},t._add=function(e,t,n,r){this._addTween(e,t,n,n+r,t,!0),this._overwriteProps.push(t)}}(),window._gsDefine.plugin({propName:"attr",API:2,init:function(e,t,n){var r;if(typeof e.setAttribute!="function")return!1;this._target=e,this._proxy={};for(r in t)this._addTween(this._proxy,r,parseFloat(e.getAttribute(r)),t[r],r),this._overwriteProps.push(r);return!0},set:function(e){this._super.setRatio.call(this,e);var t=this._overwriteProps,n=t.length,r;while(--n>-1)r=t[n],this._target.setAttribute(r,this._proxy[r]+"")}}),window._gsDefine.plugin({propName:"directionalRotation",API:2,init:function(e,t,n){typeof t!="object"&&(t={rotation:t}),this.finals={},this._tween=n;var r=t.useRadians===!0?Math.PI*2:360,i,s,o,u,a,f,l;for(i in t)i!=="useRadians"&&(f=(t[i]+"").split("_"),s=f[0],l=f[1],o=parseFloat(typeof e[i]!="function"?e[i]:e[i.indexOf("set")||typeof e["get"+i.substr(3)]!="function"?i:"get"+i.substr(3)]()),u=this.finals[i]=typeof s=="string"&&s.charAt(1)==="="?o+parseInt(s.charAt(0)+"1",10)*Number(s.substr(2)):Number(s)||0,a=u-o,l==="short"?(a%=r,a!==a%(r/2)&&(a=a<0?a+r:a-r)):l==="cw"&&a<0?a=(a+r*9999999999)%r-(a/r|0)*r:l==="ccw"&&a>0&&(a=(a-r*9999999999)%r-(a/r|0)*r),this._addTween(e,i,o,o+a,i),this._overwriteProps.push(i));return!0},set:function(e){var t;if(e!==1)this._super.setRatio.call(this,e);else{t=this._firstPT;while(t)t.f?t.t[t.p](this.finals[t.p]):t.t[t.p]=this.finals[t.p],t=t._next}}})._autoCSS=!0,window._gsDefine("easing.Back",["easing.Ease"],function(e){var t=window.GreenSockGlobals||window,n=t.com.greensock,r=Math.PI*2,i=Math.PI/2,s=n._class,o=function(t,n){var r=s("easing."+t,function(){},!0),i=r.prototype=new e;return i.constructor=r,i.getRatio=n,r},u=e.register||function(){},a=function(e,t,n,r,i){var o=s("easing."+e,{easeOut:new t,easeIn:new n,easeInOut:new r},!0);return u(o,e),o},f=function(t,n){var r=s("easing."+t,function(e){this._p1=e||e===0?e:1.70158,this._p2=this._p1*1.525},!0),i=r.prototype=new e;return i.constructor=r,i.getRatio=n,i.config=function(e){return new r(e)},r},l=a("Back",f("BackOut",function(e){return(e-=1)*e*((this._p1+1)*e+this._p1)+1}),f("BackIn",function(e){return e*e*((this._p1+1)*e-this._p1)}),f("BackInOut",function(e){return(e*=2)<1?.5*e*e*((this._p2+1)*e-this._p2):.5*((e-=2)*e*((this._p2+1)*e+this._p2)+2)})),c=s("easing.SlowMo",function(e,t,n){t=t||t===0?t:.7,e==null?e=.7:e>1&&(e=1),this._p=e!==1?t:0,this._p1=(1-e)/2,this._p2=e,this._p3=this._p1+this._p2,this._calcEnd=n===!0},!0),h=c.prototype=new e,p,d;return h.constructor=c,h.getRatio=function(e){var t=e+(.5-e)*this._p;return e<this._p1?this._calcEnd?1-(e=1-e/this._p1)*e:t-(e=1-e/this._p1)*e*e*e*t:e>this._p3?this._calcEnd?1-(e=(e-this._p3)/this._p1)*e:t+(e-t)*(e=(e-this._p3)/this._p1)*e*e*e:this._calcEnd?1:t},c.ease=new c(.7,.7),h.config=c.config=function(e,t,n){return new c(e,t,n)},p=s("easing.SteppedEase",function(e){e=e||1,this._p1=1/e,this._p2=e+1},!0),h=p.prototype=new e,h.constructor=p,h.getRatio=function(e){return e<0?e=0:e>=1&&(e=.999999999),(this._p2*e>>0)*this._p1},h.config=p.config=function(e){return new p(e)},a("Bounce",o("BounceOut",function(e){return e<1/2.75?7.5625*e*e:e<2/2.75?7.5625*(e-=1.5/2.75)*e+.75:e<2.5/2.75?7.5625*(e-=2.25/2.75)*e+.9375:7.5625*(e-=2.625/2.75)*e+.984375}),o("BounceIn",function(e){return(e=1-e)<1/2.75?1-7.5625*e*e:e<2/2.75?1-(7.5625*(e-=1.5/2.75)*e+.75):e<2.5/2.75?1-(7.5625*(e-=2.25/2.75)*e+.9375):1-(7.5625*(e-=2.625/2.75)*e+.984375)}),o("BounceInOut",function(e){var t=e<.5;return t?e=1-e*2:e=e*2-1,e<1/2.75?e=7.5625*e*e:e<2/2.75?e=7.5625*(e-=1.5/2.75)*e+.75:e<2.5/2.75?e=7.5625*(e-=2.25/2.75)*e+.9375:e=7.5625*(e-=2.625/2.75)*e+.984375,t?(1-e)*.5:e*.5+.5})),a("Circ",o("CircOut",function(e){return Math.sqrt(1-(e-=1)*e)}),o("CircIn",function(e){return-(Math.sqrt(1-e*e)-1)}),o("CircInOut",function(e){return(e*=2)<1?-0.5*(Math.sqrt(1-e*e)-1):.5*(Math.sqrt(1-(e-=2)*e)+1)})),d=function(t,n,i){var o=s("easing."+t,function(e,t){this._p1=e||1,this._p2=t||i,this._p3=this._p2/r*(Math.asin(1/this._p1)||0)},!0),u=o.prototype=new e;return u.constructor=o,u.getRatio=n,u.config=function(e,t){return new o(e,t)},o},a("Elastic",d("ElasticOut",function(e){return this._p1*Math.pow(2,-10*e)*Math.sin((e-this._p3)*r/this._p2)+1},.3),d("ElasticIn",function(e){return-(this._p1*Math.pow(2,10*(e-=1))*Math.sin((e-this._p3)*r/this._p2))},.3),d("ElasticInOut",function(e){return(e*=2)<1?-0.5*this._p1*Math.pow(2,10*(e-=1))*Math.sin((e-this._p3)*r/this._p2):this._p1*Math.pow(2,-10*(e-=1))*Math.sin((e-this._p3)*r/this._p2)*.5+1},.45)),a("Expo",o("ExpoOut",function(e){return 1-Math.pow(2,-10*e)}),o("ExpoIn",function(e){return Math.pow(2,10*(e-1))-.001}),o("ExpoInOut",function(e){return(e*=2)<1?.5*Math.pow(2,10*(e-1)):.5*(2-Math.pow(2,-10*(e-1)))})),a("Sine",o("SineOut",function(e){return Math.sin(e*i)}),o("SineIn",function(e){return-Math.cos(e*i)+1}),o("SineInOut",function(e){return-0.5*(Math.cos(Math.PI*e)-1)})),s("easing.EaseLookup",{find:function(t){return e.map[t]}},!0),u(t.SlowMo,"SlowMo","ease,"),u(p,"SteppedEase","ease,"),l},!0)}),function(e){var t=e.GreenSockGlobals||e,n=function(e){var n=e.split("."),r=t,i;for(i=0;i<n.length;i++)r[n[i]]=r=r[n[i]]||{};return r},r=n("com.greensock"),i=function(){},s,o,u,a,f,l={},c=function(r,i,s,o){this.sc=l[r]?l[r].sc:[],l[r]=this,this.gsClass=null,this.func=s;var u=[];this.check=function(a){var f=i.length,h=f,p,d,v,m;while(--f>-1)(p=l[i[f]]||new c(i[f],[])).gsClass?(u[f]=p.gsClass,h--):a&&p.sc.push(this);if(h===0&&s){d=("com.greensock."+r).split("."),v=d.pop(),m=n(d.join("."))[v]=this.gsClass=s.apply(s,u),o&&(t[v]=m,typeof define=="function"&&define.amd?define((e.GreenSockAMDPath?e.GreenSockAMDPath+"/":"")+r.split(".").join("/"),[],function(){return m}):typeof module!="undefined"&&module.exports&&(module.exports=m));for(f=0;f<this.sc.length;f++)this.sc[f].check()}},this.check(!0)},h=e._gsDefine=function(e,t,n,r){return new c(e,t,n,r)},p=r._class=function(e,t,n){return t=t||function(){},h(e,[],function(){return t},n),t};h.globals=t;var d=[0,0,1,1],v=[],m=p("easing.Ease",function(e,t,n,r){this._func=e,this._type=n||0,this._power=r||0,this._params=t?d.concat(t):d},!0),g=m.map={},y=m.register=function(e,t,n,i){var s=t.split(","),o=s.length,u=(n||"easeIn,easeOut,easeInOut").split(","),a,f,l,c;while(--o>-1){f=s[o],a=i?p("easing."+f,null,!0):r.easing[f]||{},l=u.length;while(--l>-1)c=u[l],g[f+"."+c]=g[c+f]=a[c]=e.getRatio?e:e[c]||new e}};u=m.prototype,u._calcEnd=!1,u.getRatio=function(e){if(this._func)return this._params[0]=e,this._func.apply(null,this._params);var t=this._type,n=this._power,r=t===1?1-e:t===2?e:e<.5?e*2:(1-e)*2;return n===1?r*=r:n===2?r*=r*r:n===3?r*=r*r*r:n===4&&(r*=r*r*r*r),t===1?1-r:t===2?r:e<.5?r/2:1-r/2},s=["Linear","Quad","Cubic","Quart","Quint,Strong"],o=s.length;while(--o>-1)u=s[o]+",Power"+o,y(new m(null,null,1,o),u,"easeOut",!0),y(new m(null,null,2,o),u,"easeIn"+(o===0?",easeNone":"")),y(new m(null,null,3,o),u,"easeInOut");g.linear=r.easing.Linear.easeIn,g.swing=r.easing.Quad.easeInOut;var b=p("events.EventDispatcher",function(e){this._listeners={},this._eventTarget=e||this});u=b.prototype,u.addEventListener=function(e,t,n,r,i){i=i||0;var s=this._listeners[e],o=0,u,l;s==null&&(this._listeners[e]=s=[]),l=s.length;while(--l>-1)u=s[l],u.c===t&&u.s===n?s.splice(l,1):o===0&&u.pr<i&&(o=l+1);s.splice(o,0,{c:t,s:n,up:r,pr:i}),this===a&&!f&&a.wake()},u.removeEventListener=function(e,t){var n=this._listeners[e],r;if(n){r=n.length;while(--r>-1)if(n[r].c===t){n.splice(r,1);return}}},u.dispatchEvent=function(e){var t=this._listeners[e],n,r,i;if(t){n=t.length,r=this._eventTarget;while(--n>-1)i=t[n],i.up?i.c.call(i.s||r,{type:e,target:r}):i.c.call(i.s||r)}};var w=e.requestAnimationFrame,E=e.cancelAnimationFrame,S=Date.now||function(){return(new Date).getTime()};s=["ms","moz","webkit","o"],o=s.length;while(--o>-1&&!w)w=e[s[o]+"RequestAnimationFrame"],E=e[s[o]+"CancelAnimationFrame"]||e[s[o]+"CancelRequestAnimationFrame"];p("Ticker",function(e,t){var n=this,r=S(),s=t!==!1&&w,o,u,l,c,h,p=function(e){n.time=(S()-r)/1e3;if(!o||n.time>=h||e===!0)n.frame++,h=n.time+c,n.dispatchEvent("tick");e!==!0&&(l=u(p))};b.call(n),this.time=this.frame=0,this.tick=function(){p(!0)},this.sleep=function(){if(l==null)return;!s||!E?clearTimeout(l):E(l),u=i,l=null,n===a&&(f=!1)},this.wake=function(){l&&n.sleep(),u=o===0?i:!s||!w?function(e){return setTimeout(e,c*1e3)}:w,n===a&&(f=!0),p()},this.fps=function(e){if(!arguments.length)return o;o=e,c=1/(o||60),h=this.time+c,n.wake()},this.useRAF=function(e){if(!arguments.length)return s;s=e,n.fps(o)},n.fps(e),setTimeout(function(){s&&!l&&n.useRAF(!1)},1e3)}),u=r.Ticker.prototype=new r.events.EventDispatcher,u.constructor=r.Ticker;var x=p("core.Animation",function(e,t){this.vars=t||{},this._duration=this._totalDuration=e||0,this._delay=Number(this.vars.delay)||0,this._timeScale=1,this._active=this.vars.immediateRender===!0,this.data=this.vars.data,this._reversed=this.vars.reversed===!0;if(!H)return;f||a.wake();var n=this.vars.useFrames?P:H;n.add(this,n._time),this.vars.paused&&this.paused(!0)});a=x.ticker=new r.Ticker,u=x.prototype,u._dirty=u._gc=u._initted=u._paused=!1,u._totalTime=u._time=0,u._rawPrevTime=-1,u._next=u._last=u._onUpdate=u._timeline=u.timeline=null,u._paused=!1,u.play=function(e,t){return arguments.length&&this.seek(e,t),this.reversed(!1),this.paused(!1)},u.pause=function(e,t){return arguments.length&&this.seek(e,t),this.paused(!0)},u.resume=function(e,t){return arguments.length&&this.seek(e,t),this.paused(!1)},u.seek=function(e,t){return this.totalTime(Number(e),t!==!1)},u.restart=function(e,t){return this.reversed(!1),this.paused(!1),this.totalTime(e?-this._delay:0,t!==!1)},u.reverse=function(e,t){return arguments.length&&this.seek(e||this.totalDuration(),t),this.reversed(!0),this.paused(!1)},u.render=function(){},u.invalidate=function(){return this},u._enabled=function(e,t){return f||a.wake(),this._gc=!e,this._active=e&&!this._paused&&this._totalTime>0&&this._totalTime<this._totalDuration,t!==!0&&(e&&!this.timeline?this._timeline.add(this,this._startTime-this._delay):!e&&this.timeline&&this._timeline._remove(this,!0)),!1},u._kill=function(e,t){return this._enabled(!1,!1)},u.kill=function(e,t){return this._kill(e,t),this},u._uncache=function(e){var t=e?this:this.timeline;while(t)t._dirty=!0,t=t.timeline;return this},u.eventCallback=function(e,t,n,r){if(e==null)return null;if(e.substr(0,2)==="on"){var i=this.vars,s;if(arguments.length===1)return i[e];if(t==null)delete i[e];else{i[e]=t,i[e+"Params"]=n,i[e+"Scope"]=r;if(n){s=n.length;while(--s>-1)n[s]==="{self}"&&(n=i[e+"Params"]=n.concat(),n[s]=this)}}e==="onUpdate"&&(this._onUpdate=t)}return this},u.delay=function(e){return arguments.length?(this._timeline.smoothChildTiming&&this.startTime(this._startTime+e-this._delay),this._delay=e,this):this._delay},u.duration=function(e){return arguments.length?(this._duration=this._totalDuration=e,this._uncache(!0),this._timeline.smoothChildTiming&&this._time>0&&this._time<this._duration&&e!==0&&this.totalTime(this._totalTime*(e/this._duration),!0),this):(this._dirty=!1,this._duration)},u.totalDuration=function(e){return this._dirty=!1,arguments.length?this.duration(e):this._totalDuration},u.time=function(e,t){return arguments.length?(this._dirty&&this.totalDuration(),e>this._duration&&(e=this._duration),this.totalTime(e,t)):this._time},u.totalTime=function(e,t){f||a.wake();if(!arguments.length)return this._totalTime;if(this._timeline){e<0&&(e+=this.totalDuration());if(this._timeline.smoothChildTiming){this._dirty&&this.totalDuration();var n=this._totalDuration,r=this._timeline;e>n&&(e=n),this._startTime=(this._paused?this._pauseTime:r._time)-(this._reversed?n-e:e)/this._timeScale,r._dirty||this._uncache(!1);if(!r._active)while(r._timeline)r.totalTime(r._totalTime,!0),r=r._timeline}this._gc&&this._enabled(!0,!1),this._totalTime!==e&&this.render(e,t,!1)}return this},u.startTime=function(e){return arguments.length?(e!==this._startTime&&(this._startTime=e,this.timeline&&this.timeline._sortChildren&&this.timeline.add(this,e-this._delay)),this):this._startTime},u.timeScale=function(e){if(!arguments.length)return this._timeScale;e=e||1e-6;if(this._timeline&&this._timeline.smoothChildTiming){var t=this._pauseTime||this._pauseTime===0?this._pauseTime:this._timeline.totalTime();this._startTime=t-(t-this._startTime)*this._timeScale/e}return this._timeScale=e,this._uncache(!1)},u.reversed=function(e){return arguments.length?(e!=this._reversed&&(this._reversed=e,this.totalTime(this._totalTime,!0)),this):this._reversed},u.paused=function(e){return arguments.length?(e!=this._paused&&this._timeline&&(!f&&!e&&a.wake(),!e&&this._timeline.smoothChildTiming&&(this._startTime+=this._timeline.rawTime()-this._pauseTime,this._uncache(!1)),this._pauseTime=e?this._timeline.rawTime():null,this._paused=e,this._active=!this._paused&&this._totalTime>0&&this._totalTime<this._totalDuration),this._gc&&!e&&this._enabled(!0,!1),this):this._paused};var T=p("core.SimpleTimeline",function(e){x.call(this,0,e),this.autoRemoveChildren=this.smoothChildTiming=!0});u=T.prototype=new x,u.constructor=T,u.kill()._gc=!1,u._first=u._last=null,u._sortChildren=!1,u.add=function(e,t,n,r){var i,s;e._startTime=Number(t||0)+e._delay,e._paused&&this!==e._timeline&&(e._pauseTime=e._startTime+(this.rawTime()-e._startTime)/e._timeScale),e.timeline&&e.timeline._remove(e,!0),e.timeline=e._timeline=this,e._gc&&e._enabled(!0,!0),i=this._last;if(this._sortChildren){s=e._startTime;while(i&&i._startTime>s)i=i._prev}return i?(e._next=i._next,i._next=e):(e._next=this._first,this._first=e),e._next?e._next._prev=e:this._last=e,e._prev=i,this._timeline&&this._uncache(!0),this},u.insert=u.add,u._remove=function(e,t){return e.timeline===this&&(t||e._enabled(!1,!0),e.timeline=null,e._prev?e._prev._next=e._next:this._first===e&&(this._first=e._next),e._next?e._next._prev=e._prev:this._last===e&&(this._last=e._prev),this._timeline&&this._uncache(!0)),this},u.render=function(e,t,n){var r=this._first,i;this._totalTime=this._time=this._rawPrevTime=e;while(r){i=r._next;if(r._active||e>=r._startTime&&!r._paused)r._reversed?r.render((r._dirty?r.totalDuration():r._totalDuration)-(e-r._startTime)*r._timeScale,t,n):r.render((e-r._startTime)*r._timeScale,t,n);r=i}},u.rawTime=function(){return f||a.wake(),this._totalTime};var N=p("TweenLite",function(e,t,n){x.call(this,t,n);if(e==null)throw"Cannot tween a null target.";this.target=e=typeof e!="string"?e:N.selector(e)||e;var r=e.jquery||typeof e.each=="function"&&e[0]&&e[0].nodeType&&e[0].style,i=this.vars.overwrite,s,o,u;this._overwrite=i=i==null?D[N.defaultOverwrite]:typeof i=="number"?i>>0:D[i];if((r||e instanceof Array)&&typeof e[0]!="number"){this._targets=u=r&&!e.slice?k(e):e.slice(0),this._propLookup=[],this._siblings=[];for(s=0;s<u.length;s++){o=u[s];if(!o){u.splice(s--,1);continue}if(typeof o=="string"){o=u[s--]=N.selector(o),typeof o=="string"&&u.splice(s+1,1);continue}if(typeof o.each=="function"&&o[0]&&o[0].nodeType&&o[0].style){u.splice(s--,1),this._targets=u=u.concat(k(o));continue}this._siblings[s]=B(o,this,!1),i===1&&this._siblings[s].length>1&&j(o,this,null,1,this._siblings[s])}}else this._propLookup={},this._siblings=B(e,this,!1),i===1&&this._siblings.length>1&&j(e,this,null,1,this._siblings);(this.vars.immediateRender||t===0&&this._delay===0&&this.vars.immediateRender!==!1)&&this.render(-this._delay,!1,!0)},!0),C=function(e){return typeof e.each=="function"&&e[0]&&e[0].nodeType&&e[0].style},k=function(e){var t=[];return e.each(function(){t.push(this)}),t},L=function(e,t){var n={},r;for(r in e)!_[r]&&(!(r in t)||r==="x"||r==="y"||r==="width"||r==="height"||r==="className")&&(!A[r]||A[r]&&A[r]._autoCSS)&&(n[r]=e[r],delete e[r]);e.css=n};u=N.prototype=new x,u.constructor=N,u.kill()._gc=!1,u.ratio=0,u._firstPT=u._targets=u._overwrittenProps=u._startAt=null,u._notifyPluginsOfEnabled=!1,N.version="1.9.1",N.defaultEase=u._ease=new m(null,null,1,1),N.defaultOverwrite="auto",N.ticker=a,N.autoSleep=!0,N.selector=e.$||e.jQuery||function(t){return e.$?(N.selector=e.$,e.$(t)):e.document?e.document.getElementById(t.charAt(0)==="#"?t.substr(1):t):t};var A=N._plugins={},O=N._tweenLookup={},M=0,_={ease:1,delay:1,overwrite:1,onComplete:1,onCompleteParams:1,onCompleteScope:1,useFrames:1,runBackwards:1,startAt:1,onUpdate:1,onUpdateParams:1,onUpdateScope:1,onStart:1,onStartParams:1,onStartScope:1,onReverseComplete:1,onReverseCompleteParams:1,onReverseCompleteScope:1,onRepeat:1,onRepeatParams:1,onRepeatScope:1,easeParams:1,yoyo:1,orientToBezier:1,immediateRender:1,repeat:1,repeatDelay:1,data:1,paused:1,reversed:1,autoCSS:1},D={none:0,all:1,auto:2,concurrent:3,allOnStart:4,preexisting:5,"true":1,"false":0},P=x._rootFramesTimeline=new T,H=x._rootTimeline=new T;H._startTime=a.time,P._startTime=a.frame,H._active=P._active=!0,x._updateRoot=function(){H.render((a.time-H._startTime)*H._timeScale,!1,!1),P.render((a.frame-P._startTime)*P._timeScale,!1,!1);if(!(a.frame%120)){var e,t,n;for(n in O){t=O[n].tweens,e=t.length;while(--e>-1)t[e]._gc&&t.splice(e,1);t.length===0&&delete O[n]}n=H._first;if(!n||n._paused)if(N.autoSleep&&!P._first&&a._listeners.tick.length===1){while(n&&n._paused)n=n._next;n||a.sleep()}}},a.addEventListener("tick",x._updateRoot);var B=function(e,t,n){var r=e._gsTweenID,i,s;O[r||(e._gsTweenID=r="t"+M++)]||(O[r]={target:e,tweens:[]});if(t){i=O[r].tweens,i[s=i.length]=t;if(n)while(--s>-1)i[s]===t&&i.splice(s,1)}return O[r].tweens},j=function(e,t,n,r,i){var s,o,u,a;if(r===1||r>=4){a=i.length;for(s=0;s<a;s++)if((u=i[s])!==t)u._gc||u._enabled(!1,!1)&&(o=!0);else if(r===5)break;return o}var f=t._startTime+1e-10,l=[],c=0,h=t._duration===0,p;s=i.length;while(--s>-1)(u=i[s])!==t&&!u._gc&&!u._paused&&(u._timeline!==t._timeline?(p=p||F(t,0,h),F(u,p,h)===0&&(l[c++]=u)):u._startTime<=f&&u._startTime+u.totalDuration()/u._timeScale+1e-10>f&&((h||!u._initted)&&f-u._startTime<=2e-10||(l[c++]=u)));s=c;while(--s>-1)u=l[s],r===2&&u._kill(n,e)&&(o=!0),(r!==2||!u._firstPT&&u._initted)&&u._enabled(!1,!1)&&(o=!0);return o},F=function(e,t,n){var r=e._timeline,i=r._timeScale,s=e._startTime;while(r._timeline){s+=r._startTime,i*=r._timeScale;if(r._paused)return-100;r=r._timeline}return s/=i,s>t?s-t:n&&s===t||!e._initted&&s-t<2e-10?1e-10:(s+=e.totalDuration()/e._timeScale/i)>t?0:s-t-1e-10};u._init=function(){var e=this.vars,t=this._overwrittenProps,n=this._duration,r=e.ease,i,s,o;if(e.startAt){e.startAt.overwrite=0,e.startAt.immediateRender=!0,this._startAt=N.to(this.target,0,e.startAt);if(e.immediateRender){this._startAt=null;if(this._time===0&&n!==0)return}}else if(e.runBackwards&&e.immediateRender&&n!==0){if(this._time===0){e.overwrite=e.delay=0,e.runBackwards=!1,this._startAt=N.to(this.target,0,e),e.overwrite=this._overwrite,e.runBackwards=!0,e.delay=this._delay;return}this._startAt&&(this._startAt.render(-1,!0),this._startAt=null)}r?r instanceof m?this._ease=e.easeParams instanceof Array?r.config.apply(r,e.easeParams):r:this._ease=typeof r=="function"?new m(r,e.easeParams):g[r]||N.defaultEase:this._ease=N.defaultEase,this._easeType=this._ease._type,this._easePower=this._ease._power,this._firstPT=null;if(this._targets){i=this._targets.length;while(--i>-1)this._initProps(this._targets[i],this._propLookup[i]={},this._siblings[i],t?t[i]:null)&&(s=!0)}else s=this._initProps(this.target,this._propLookup,this._siblings,t);s&&N._onPluginEvent("_onInitAllProps",this),t&&(this._firstPT||typeof this.target!="function"&&this._enabled(!1,!1));if(e.runBackwards){o=this._firstPT;while(o)o.s+=o.c,o.c=-o.c,o=o._next}this._onUpdate=e.onUpdate,this._initted=!0},u._initProps=function(e,t,n,r){var i,s,o,u,a,f,l;if(e==null)return!1;this.vars.css||e.style&&e.nodeType&&A.css&&this.vars.autoCSS!==!1&&L(this.vars,e);for(i in this.vars){if(_[i]){if(i==="onStartParams"||i==="onUpdateParams"||i==="onCompleteParams"||i==="onReverseCompleteParams"||i==="onRepeatParams")if(a=this.vars[i]){s=a.length;while(--s>-1)a[s]==="{self}"&&(a=this.vars[i]=a.concat(),a[s]=this)}}else if(A[i]&&(u=new A[i])._onInitTween(e,this.vars[i],this)){this._firstPT=f={_next:this._firstPT,t:u,p:"setRatio",s:0,c:1,f:!0,n:i,pg:!0,pr:u._priority},s=u._overwriteProps.length;while(--s>-1)t[u._overwriteProps[s]]=this._firstPT;if(u._priority||u._onInitAllProps)o=!0;if(u._onDisable||u._onEnable)this._notifyPluginsOfEnabled=!0}else this._firstPT=t[i]=f={_next:this._firstPT,t:e,p:i,f:typeof e[i]=="function",n:i,pg:!1,pr:0},f.s=f.f?e[i.indexOf("set")||typeof e["get"+i.substr(3)]!="function"?i:"get"+i.substr(3)]():parseFloat(e[i]),l=this.vars[i],f.c=typeof l=="string"&&l.charAt(1)==="="?parseInt(l.charAt(0)+"1",10)*Number(l.substr(2)):Number(l)-f.s||0;f&&f._next&&(f._next._prev=f)}return r&&this._kill(r,e)?this._initProps(e,t,n,r):this._overwrite>1&&this._firstPT&&n.length>1&&j(e,this,t,this._overwrite,n)?(this._kill(t,e),this._initProps(e,t,n,r)):o},u.render=function(e,t,n){var r=this._time,i,s,o;if(e>=this._duration)this._totalTime=this._time=this._duration,this.ratio=this._ease._calcEnd?this._ease.getRatio(1):1,this._reversed||(i=!0,s="onComplete"),this._duration===0&&((e===0||this._rawPrevTime<0)&&this._rawPrevTime!==e&&(n=!0),this._rawPrevTime=e);else if(e<=0){this._totalTime=this._time=0,this.ratio=this._ease._calcEnd?this._ease.getRatio(0):0;if(r!==0||this._duration===0&&this._rawPrevTime>0)s="onReverseComplete",i=this._reversed;e<0?(this._active=!1,this._duration===0&&(this._rawPrevTime>=0&&(n=!0),this._rawPrevTime=e)):this._initted||(n=!0)}else{this._totalTime=this._time=e;if(this._easeType){var u=e/this._duration,a=this._easeType,f=this._easePower;if(a===1||a===3&&u>=.5)u=1-u;a===3&&(u*=2),f===1?u*=u:f===2?u*=u*u:f===3?u*=u*u*u:f===4&&(u*=u*u*u*u),a===1?this.ratio=1-u:a===2?this.ratio=u:e/this._duration<.5?this.ratio=u/2:this.ratio=1-u/2}else this.ratio=this._ease.getRatio(e/this._duration)}if(this._time===r&&!n)return;if(!this._initted){this._init();if(!this._initted)return;this._time&&!i?this.ratio=this._ease.getRatio(this._time/this._duration):i&&this._ease._calcEnd&&(this.ratio=this._ease.getRatio(this._time===0?0:1))}this._active||this._paused||(this._active=!0),r===0&&(this._startAt&&this._startAt.render(e,t,n),this.vars.onStart&&(this._time!==0||this._duration===0)&&(t||this.vars.onStart.apply(this.vars.onStartScope||this,this.vars.onStartParams||v))),o=this._firstPT;while(o)o.f?o.t[o.p](o.c*this.ratio+o.s):o.t[o.p]=o.c*this.ratio+o.s,o=o._next;this._onUpdate&&(e<0&&this._startAt&&this._startAt.render(e,t,n),t||this._onUpdate.apply(this.vars.onUpdateScope||this,this.vars.onUpdateParams||v)),s&&(this._gc||(e<0&&this._startAt&&(this._onUpdate||this._startAt.render(e,t,n)),i&&(this._timeline.autoRemoveChildren&&this._enabled(!1,!1),this._active=!1),t||this.vars[s]&&this.vars[s].apply(this.vars[s+"Scope"]||this,this.vars[s+"Params"]||v)))},u._kill=function(e,t){e==="all"&&(e=null);if(e==null)if(t==null||t===this.target)return this._enabled(!1,!1);t=typeof t!="string"?t||this._targets||this.target:N.selector(t)||t;var n,r,i,s,o,u,a,f;if((t instanceof Array||C(t))&&typeof t[0]!="number"){n=t.length;while(--n>-1)this._kill(e,t[n])&&(u=!0)}else{if(this._targets){n=this._targets.length;while(--n>-1)if(t===this._targets[n]){o=this._propLookup[n]||{},this._overwrittenProps=this._overwrittenProps||[],r=this._overwrittenProps[n]=e?this._overwrittenProps[n]||{}:"all";break}}else{if(t!==this.target)return!1;o=this._propLookup,r=this._overwrittenProps=e?this._overwrittenProps||{}:"all"}if(o){a=e||o,f=e!==r&&r!=="all"&&e!==o&&(e==null||e._tempKill!==!0);for(i in a){if(s=o[i]){s.pg&&s.t._kill(a)&&(u=!0);if(!s.pg||s.t._overwriteProps.length===0)s._prev?s._prev._next=s._next:s===this._firstPT&&(this._firstPT=s._next),s._next&&(s._next._prev=s._prev),s._next=s._prev=null;delete o[i]}f&&(r[i]=1)}this._firstPT||this._enabled(!1,!1)}}return u},u.invalidate=function(){return this._notifyPluginsOfEnabled&&N._onPluginEvent("_onDisable",this),this._firstPT=null,this._overwrittenProps=null,this._onUpdate=null,this._startAt=null,this._initted=this._active=this._notifyPluginsOfEnabled=!1,this._propLookup=this._targets?{}:[],this},u._enabled=function(e,t){f||a.wake();if(e&&this._gc){var n=this._targets,r;if(n){r=n.length;while(--r>-1)this._siblings[r]=B(n[r],this,!0)}else this._siblings=B(this.target,this,!0)}return x.prototype._enabled.call(this,e,t),this._notifyPluginsOfEnabled&&this._firstPT?N._onPluginEvent(e?"_onEnable":"_onDisable",this):!1},N.to=function(e,t,n){return new N(e,t,n)},N.from=function(e,t,n){return n.runBackwards=!0,n.immediateRender=n.immediateRender!=0,new N(e,t,n)},N.fromTo=function(e,t,n,r){return r.startAt=n,r.immediateRender=r.immediateRender!=0&&n.immediateRender!=0,new N(e,t,r)},N.delayedCall=function(e,t,n,r,i){return new N(t,0,{delay:e,onComplete:t,onCompleteParams:n,onCompleteScope:r,onReverseComplete:t,onReverseCompleteParams:n,onReverseCompleteScope:r,immediateRender:!1,useFrames:i,overwrite:0})},N.set=function(e,t){return new N(e,0,t)},N.killTweensOf=N.killDelayedCallsTo=function(e,t){var n=N.getTweensOf(e),r=n.length;while(--r>-1)n[r]._kill(t,e)},N.getTweensOf=function(e){if(e==null)return;e=typeof e!="string"?e:N.selector(e)||e;var t,n,r,i;if((e instanceof Array||C(e))&&typeof e[0]!="number"){t=e.length,n=[];while(--t>-1)n=n.concat(N.getTweensOf(e[t]));t=n.length;while(--t>-1){i=n[t],r=t;while(--r>-1)i===n[r]&&n.splice(t,1)}}else{n=B(e).concat(),t=n.length;while(--t>-1)n[t]._gc&&n.splice(t,1)}return n};var I=p("plugins.TweenPlugin",function(e,t){this._overwriteProps=(e||"").split(","),this._propName=this._overwriteProps[0],this._priority=t||0,this._super=I.prototype},!0);u=I.prototype,I.version="1.9.1",I.API=2,u._firstPT=null,u._addTween=function(e,t,n,r,i,s){var o,u;r!=null&&(o=typeof r=="number"||r.charAt(1)!=="="?Number(r)-n:parseInt(r.charAt(0)+"1",10)*Number(r.substr(2)))&&(this._firstPT=u={_next:this._firstPT,t:e,p:t,s:n,c:o,f:typeof e[t]=="function",n:i||t,r:s},u._next&&(u._next._prev=u))},u.setRatio=function(e){var t=this._firstPT,n=1e-6,r;while(t)r=t.c*e+t.s,t.r?r=r+(r>0?.5:-0.5)>>0:r<n&&r>-n&&(r=0),t.f?t.t[t.p](r):t.t[t.p]=r,t=t._next},u._kill=function(e){var t=this._overwriteProps,n=this._firstPT,r;if(e[this._propName]!=null)this._overwriteProps=[];else{r=t.length;while(--r>-1)e[t[r]]!=null&&t.splice(r,1)}while(n)e[n.n]!=null&&(n._next&&(n._next._prev=n._prev),n._prev?(n._prev._next=n._next,n._prev=null):this._firstPT===n&&(this._firstPT=n._next)),n=n._next;return!1},u._roundProps=function(e,t){var n=this._firstPT;while(n){if(e[this._propName]||n.n!=null&&e[n.n.split(this._propName+"_").join("")])n.r=t;n=n._next}},N._onPluginEvent=function(e,t){var n=t._firstPT,r,i,s,o,u;if(e==="_onInitAllProps"){while(n){u=n._next,i=s;while(i&&i.pr>n.pr)i=i._next;(n._prev=i?i._prev:o)?n._prev._next=n:s=n,(n._next=i)?i._prev=n:o=n,n=u}n=t._firstPT=s}while(n)n.pg&&typeof n.t[e]=="function"&&n.t[e]()&&(r=!0),n=n._next;return r},I.activate=function(e){var t=e.length;while(--t>-1)e[t].API===I.API&&(A[(new e[t])._propName]=e[t]);return!0},h.plugin=function(e){if(!e||!e.propName||!e.init||!e.API)throw"illegal plugin definition.";var t=e.propName,n=e.priority||0,r=e.overwriteProps,i={init:"_onInitTween",set:"setRatio",kill:"_kill",round:"_roundProps",initAll:"_onInitAllProps"},s=p("plugins."+t.charAt(0).toUpperCase()+t.substr(1)+"Plugin",function(){I.call(this,t,n),this._overwriteProps=r||[]},e.global===!0),o=s.prototype=new I(t),u;o.constructor=s,s.API=e.API;for(u in i)typeof e[u]=="function"&&(o[i[u]]=e[u]);return s.version=e.version,I.activate([s]),s},s=e._gsQueue;if(s){for(o=0;o<s.length;o++)s[o]();for(u in l)l[u].func||e.console.log("GSAP encountered missing dependency: com.greensock."+u)}f=!1}(window),define("greensock/TweenMax",function(){}),define("text",["module"],function(e){var t,n,r,i,s=["Msxml2.XMLHTTP","Microsoft.XMLHTTP","Msxml2.XMLHTTP.4.0"],o=/^\s*<\?xml(\s)+version=[\'\"](\d)*.(\d)*[\'\"](\s)*\?>/im,u=/<body[^>]*>\s*([\s\S]+)\s*<\/body>/im,a=typeof location!="undefined"&&location.href,f=a&&location.protocol&&location.protocol.replace(/\:/,""),l=a&&location.hostname,c=a&&(location.port||undefined),h=[],p=e.config&&e.config()||{};t={version:"2.0.5+",strip:function(e){if(e){e=e.replace(o,"");var t=e.match(u);t&&(e=t[1])}else e="";return e},jsEscape:function(e){return e.replace(/(['\\])/g,"\\$1").replace(/[\f]/g,"\\f").replace(/[\b]/g,"\\b").replace(/[\n]/g,"\\n").replace(/[\t]/g,"\\t").replace(/[\r]/g,"\\r").replace(/[\u2028]/g,"\\u2028").replace(/[\u2029]/g,"\\u2029")},createXhr:p.createXhr||function(){var e,t,n;if(typeof XMLHttpRequest!="undefined")return new XMLHttpRequest;if(typeof ActiveXObject!="undefined")for(t=0;t<3;t+=1){n=s[t];try{e=new ActiveXObject(n)}catch(r){}if(e){s=[n];break}}return e},parseName:function(e){var t,n,r,i=!1,s=e.indexOf("."),o=e.indexOf("./")===0||e.indexOf("../")===0;return s!==-1&&(!o||s>1)?(t=e.substring(0,s),n=e.substring(s+1,e.length)):t=e,r=n||t,s=r.indexOf("!"),s!==-1&&(i=r.substring(s+1)==="strip",r=r.substring(0,s),n?n=r:t=r),{moduleName:t,ext:n,strip:i}},xdRegExp:/^((\w+)\:)?\/\/([^\/\\]+)/,useXhr:function(e,n,r,i){var s,o,u,a=t.xdRegExp.exec(e);return a?(s=a[2],o=a[3],o=o.split(":"),u=o[1],o=o[0],(!s||s===n)&&(!o||o.toLowerCase()===r.toLowerCase())&&(!u&&!o||u===i)):!0},finishLoad:function(e,n,r,i){r=n?t.strip(r):r,p.isBuild&&(h[e]=r),i(r)},load:function(e,n,r,i){if(i.isBuild&&!i.inlineText){r();return}p.isBuild=i.isBuild;var s=t.parseName(e),o=s.moduleName+(s.ext?"."+s.ext:""),u=n.toUrl(o),h=p.useXhr||t.useXhr;!a||h(u,f,l,c)?t.get(u,function(n){t.finishLoad(e,s.strip,n,r)},function(e){r.error&&r.error(e)}):n([o],function(e){t.finishLoad(s.moduleName+"."+s.ext,s.strip,e,r)})},write:function(e,n,r,i){if(h.hasOwnProperty(n)){var s=t.jsEscape(h[n]);r.asModule(e+"!"+n,"define(function () { return '"+s+"';});\n")}},writeFile:function(e,n,r,i,s){var o=t.parseName(n),u=o.ext?"."+o.ext:"",a=o.moduleName+u,f=r.toUrl(o.moduleName+u)+".js";t.load(a,r,function(n){var r=function(e){return i(f,e)};r.asModule=function(e,t){return i.asModule(e,f,t)},t.write(e,a,r,s)},s)}};if(p.env==="node"||!p.env&&typeof process!="undefined"&&process.versions&&!!process.versions.node)n=require.nodeRequire("fs"),t.get=function(e,t){var r=n.readFileSync(e,"utf8");r.indexOf("")===0&&(r=r.substring(1)),t(r)};else if(p.env==="xhr"||!p.env&&t.createXhr())t.get=function(e,n,r,i){var s=t.createXhr(),o;s.open("GET",e,!0);if(i)for(o in i)i.hasOwnProperty(o)&&s.setRequestHeader(o.toLowerCase(),i[o]);p.onXhr&&p.onXhr(s,e),s.onreadystatechange=function(t){var i,o;s.readyState===4&&(i=s.status,i>399&&i<600?(o=new Error(e+" HTTP status: "+i),o.xhr=s,r(o)):n(s.responseText))},s.send(null)};else if(p.env==="rhino"||!p.env&&typeof Packages!="undefined"&&typeof java!="undefined")t.get=function(e,t){var n,r,i="utf-8",s=new java.io.File(e),o=java.lang.System.getProperty("line.separator"),u=new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(s),i)),a="";try{n=new java.lang.StringBuffer,r=u.readLine(),r&&r.length()&&r.charAt(0)===65279&&(r=r.substring(1)),n.append(r);while((r=u.readLine())!==null)n.append(o),n.append(r);a=String(n.toString())}finally{u.close()}t(a)};else if(p.env==="xpconnect"||!p.env&&typeof Components!="undefined"&&Components.classes&&Components.interfaces)r=Components.classes,i=Components.interfaces,Components.utils["import"]("resource://gre/modules/FileUtils.jsm"),t.get=function(e,t){var n,s,o={},u=new FileUtils.File(e);try{n=r["@mozilla.org/network/file-input-stream;1"].createInstance(i.nsIFileInputStream),n.init(u,1,0,!1),s=r["@mozilla.org/intl/converter-input-stream;1"].createInstance(i.nsIConverterInputStream),s.init(n,"utf-8",n.available(),i.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER),s.readString(n.available(),o),s.close(),n.close(),t(o.value)}catch(a){throw new Error((u&&u.path||"")+": "+a)}};return t}),define("text!interaction_view/template/animateitem_view.js",[],function(){return'<div class="iView dynamic hide <%=isMasterOverlay?"masterhide":""%>" data-type="<%=iType%>" id="<%=id%>" style="position: absolute; width: 1px; height: 1px; backgroud-repeat:no-repeat;background-postion:center;">\n <%if(iType=="RichText"||iType=="Region"){%>\n <div class="iText nanoscrollbar Element" style="position:absolute;left: -<%=iCommon[iPageDirection].iWidth/2%>px; top: -<%=iCommon[iPageDirection].iHeight/2%>px;background-color:transparent;width:<%=iCommon[iPageDirection].iWidth%>px;height:<%=iCommon[iPageDirection].iHeight%>px;">\n <%=iDetail.iText%>\n </div> \n <%}%>\n <%if(iType==\'Image\'){%>\n <div class="iImage Element" style="position:absolute;left: -<%=iCommon[iPageDirection].iWidth/2%>px; top: -<%=iCommon[iPageDirection].iHeight/2%>px;width:<%=iCommon[iPageDirection].iWidth%>px;height:<%=iCommon[iPageDirection].iHeight%>px;">\n <%if(iDetail.iImg&&iDetail.iImg[0]){%>\n <%if(_g.getUrlParameterByName("-playmode")=="1"){%>\n <img class="Context" src="<%=iDetail.iImg[0].thumbnail%>" style="width:100%;height:100%;position:absolute;">\n <%}else{ %>\n <img class="Context" src="<%=iDetail.iImg[0].picture%>" style="width:100%;height:100%;position:absolute;">\n <%}%>\n <%}%>\n </div>\n <%}%>\n <%if(iType==\'Link\'){%>\n <div class="iLink Element" style="position:absolute;left: -<%=iCommon[iPageDirection].iWidth/2%>px; top: -<%=iCommon[iPageDirection].iHeight/2%>px;width:<%=iCommon[iPageDirection].iWidth%>px;height:<%=iCommon[iPageDirection].iHeight%>px;"></div>\n <%}%>\n <%if(iType==\'Slide\'){%>\n <div class="iSlide Element" style="overflow:hidden;position:absolute;left: -<%=iCommon[iPageDirection].iWidth/2%>px; top: -<%=iCommon[iPageDirection].iHeight/2%>px;background-color:transparent;width:<%=iCommon[iPageDirection].iWidth%>px;height:<%=iCommon[iPageDirection].iHeight%>px;">\n <div class="slidecontent" style="position:absolute;width:100%;height:100%;text-align:center;line-height:<%=iCommon[iPageDirection].iHeight%>px;">\n <%if(iDetail.iImg){%>\n <%_.each(iDetail.iImg,function(i){%>\n <%if(_g.getUrlParameterByName("-playmode")=="1"){%>\n <img data-index="<%=iDetail.iImg.indexOf(i)%>" class="Context" src="<%=i.thumbnail%>" style="width:100%;height:100%;position:absolute;margin:auto;display:inline;verticle-align:middle;">\n <%}else{ %>\n <img data-index="<%=iDetail.iImg.indexOf(i)%>" class="Context" src="<%=i.picture%>" style="width:100%;height:100%;position:absolute;margin:auto;display:inline;verticle-align:middle;">\n <%}%> \n <%})%>\n <%}%>\n </div>\n </div>\n <%}%>\n <%if(iType==\'CycleImage\'){%>\n <div class="iCycleImage Element" style="overflow:hidden;position:absolute;left: -<%=iCommon[iPageDirection].iWidth/2%>px; top: -<%=iCommon[iPageDirection].iHeight/2%>px;background-color:transparent;width:<%=iCommon[iPageDirection].iWidth%>px;height:<%=iCommon[iPageDirection].iHeight%>px;">\n <div class="slidecontent" style="position:absolute;width:100%;height:100%;line-height:<%=iCommon[iPageDirection].iHeight%>px;">\n <%if(iDetail.iImg){%>\n <%_.each(iDetail.iImg,function(i){%>\n <%if(_g.getUrlParameterByName("-playmode")=="1"){%>\n <img data-index="<%=iDetail.iImg.indexOf(i)%>" class="Context" src="<%=i.thumbnail%>" style="width:100%;height:100%;position:absolute;margin:auto;display:inline;verticle-align:middle;">\n <%}else{ %>\n <img data-index="<%=iDetail.iImg.indexOf(i)%>" class="Context" src="<%=i.picture%>" style="width:100%;height:100%;position:absolute;margin:auto;display:inline;verticle-align:middle;">\n <%}%>\n <%})%>\n <%}%>\n </div>\n </div>\n <%}%>\n <%if(iType==\'Video\'){%>\n <div class="iVideo Element" style="position:absolute;left: -<%=iCommon[iPageDirection].iWidth/2%>px; top: -<%=iCommon[iPageDirection].iHeight/2%>px;background-color:transparent;width:<%=iCommon[iPageDirection].iWidth%>px;height:<%=iCommon[iPageDirection].iHeight%>px;">\n <%if(iDetail.iFile&&iDetail.iFile[0]){%>\n <%if(typeof cbt_data=="undefined"){ %>\n <video id="Video_<%=id%>" style="position:absolute;" src="<%=iDetail.iFile[0].file||iDetail.iFile[0].content%>_origin.mp4" poster="<%=iDetail.iFile[0].picture%>" width="<%=iCommon[iPageDirection].iWidth%>" height="<%=iCommon[iPageDirection].iHeight%>">\n </video>\n <% }else{ %>\n <video id="Video_<%=id%>" style="position:absolute;" src="<%=iDetail.iFile[0].file||iDetail.iFile[0].content%>" poster="<%=iDetail.iFile[0].picture%>" width="<%=iCommon[iPageDirection].iWidth%>" height="<%=iCommon[iPageDirection].iHeight%>">\n </video> \n <% } %>\n <%}%>\n </div>\n <%}%>\n <%if(iType==\'Button\'){%>\n <div class="iButton Element" style="position:absolute;left: -<%=iCommon[iPageDirection].iWidth/2%>px; top: -<%=iCommon[iPageDirection].iHeight/2%>px;background-color:transparent;width:<%=iCommon[iPageDirection].iWidth%>px;height:<%=iCommon[iPageDirection].iHeight%>px;">\n <%if(iDetail.iconNormal&&iDetail.iconNormal[0]){%>\n <img class="Context iconNormal" src="<%=iDetail.iconNormal[0].picture%>" style="width:100%;height:100%;">\n <%}%>\n <%if(iDetail.iconActive&&iDetail.iconActive[0]){%>\n <img class="Context iconActive" src="<%=iDetail.iconActive[0].picture%>" style="width:100%;height:100%;display:none;">\n <%}%>\n </div>\n <%}%>\n <%if(iType=="Map"){%>\n <div class="iMap nanoscrollbar Element" style="position:absolute;left: -<%=iCommon[iPageDirection].iWidth/2%>px; top: -<%=iCommon[iPageDirection].iHeight/2%>px;background-color:transparent;width:<%=iCommon[iPageDirection].iWidth%>px;height:<%=iCommon[iPageDirection].iHeight%>px;">\n <%=iDetail.iText%>\n </div> \n <%}%>\n <%if(iType=="Pay"){%>\n <div class="iPay nanoscrollbar Element" style="position:absolute;left: -<%=iCommon[iPageDirection].iWidth/2%>px; top: -<%=iCommon[iPageDirection].iHeight/2%>px;background-color:transparent;width:<%=iCommon[iPageDirection].iWidth%>px;height:<%=iCommon[iPageDirection].iHeight%>px;">\n <%=iDetail.iText%>\n </div> \n <%}%>\n <%if(iType=="LayerRef"||iType=="LayerSlide"){%>\n <div class="iLayerRef Element" style="position:absolute;left: -<%=iCommon[iPageDirection].iWidth/2%>px; top: -<%=iCommon[iPageDirection].iHeight/2%>px;background-color:transparent;width:<%=iCommon[iPageDirection].iWidth%>px;height:<%=iCommon[iPageDirection].iHeight%>px;">\n <div class="layer-mask" style="position:absolute;width:100%;height:100%;overflow:hidden;">\n <%if(iDetail.layer_ids&&iDetail.layer_ids.length>0){%>\n <div class="layer-content" style="position:absolute;left:<%=iDetail.x%>px;top:<%=iDetail.y%>px;width:100%;height:100%;">\n <% _.each(iDetail.layer_ids,function(layerid){ %>\n <% if(interaction_view.ilayerlist.get(layerid)){ %>\n <div class="layer-item" data-index="<%=iDetail.layer_ids.indexOf(layerid)%>" data-id="<%=layerid%>" style="position:absolute;opacity:0;width:<%=interaction_view.ilayerlist.get(layerid).toJSON().layer_width%>px;height:<%=interaction_view.ilayerlist.get(layerid).toJSON().layer_height%>px;left:0px;right:0px;">\n <div href="" class="layer-bg" style="position:absolute;width:100%;height:100%;text-align:center;line-height:<%=interaction_view.ilayerlist.get(layerid).toJSON().layer_height%>px;background-color:<%=interaction_view.ilayerlist.get(layerid).toJSON().bg_color%>;opacity:<%=interaction_view.ilayerlist.get(layerid).toJSON().bg_opacity%>">\n <% if(interaction_view.ilayerlist.get(layerid).get("picture")){ %>\n <img src="<%=interaction_view.ilayerlist.get(layerid).get("picture")%>" style="<%=(interaction_view.ilayerlist.get(layerid).toJSON().layer_width>=interaction_view.ilayerlist.get(layerid).toJSON().layer_height)?"width:auto;height:100%;":"width:100%;height:auto;"%>margin:auto">\n <% } %>\n </div> \n </div>\n <% } %>\n <% }) %> \n </div>\n <% } %>\n </div> \n </div> \n <%}%>\n</div>\n'}),define("text!interaction_view/template/message.js",[],function(){return'<div class="status <%=type%>">\n<p><%=msg%></p>\n<a href="#" class="close">Close</a>\n</div>'}),define("interaction_view/model/base",["jquery","backbone","greensock/TweenMax","text!interaction_view/template/animateitem_view.js","text!interaction_view/template/message.js"],function(){var AnimateElementTemplate=require("text!interaction_view/template/animateitem_view.js"),MessageTemplate=require("text!interaction_view/template/message.js");window.interaction_view={model:{Base:Backbone.Model.extend({defaults:{iType:"iBasetype",iLock:!0,iVisibility:!0,iCommon:null,iDetail:null,iOptions:{iParent:null,iParentModel:null,iDraggable:!0,iResizable:!0,template:null,iParentdiv:".interaction-view",iAutoindex:!1,iSync:!1,iKeyscontrol:!0},iPage:null,iParentModel:null,iDraggable:!0,iResizable:!0,template:null,iParentdiv:".interaction-view",iAutoindex:!1,iSync:!1,iZindex:"-1",iAutofocus:!1,iKeyscontrol:!0,iUrl:null,callback:null,iBackground:"",iResources:null,iResourcesType:null,iResourcesProperties:null},options:{createwait:!0},initialize:function(){this.options=this.get("iOptions");if(!this.id){this.beforecreate();var e=this;this.get("iAutoindex")?(this.set("id",this.get("iType")+"_"+this.cid+(new Date).getTime()),this.setcollection(),this.setmodel()):(this.options.createwait&&jqwait_simple(),this.savemodel(function(t){e.set("id",t.ID.toString()),e.setcollection(),e.setmodel()}))}else this.setcollection(),this.setmodel()},beforecreate:function(){},savemodel:function(callback){this.save({},{wait:!0,success:function(model,response){returned=eval(response),returned.Status=="Success"?(jqwait_simple_close(),callback&&callback(returned)):model_error({method:"create",status:returned.Status,msg:returned.Message,model:model})},error:function(){model_error({method:"create",status:"ServerError",msg:"server error or server is not available now,please try again!",model:model})}})},setmodel:function(){this.page=interaction_view.ipagelist.getPage(this.get("pageid"))||interaction_view.imasterlist.get(this.get("pageid")),this.setlist(),this.setview(),this.setsyncmodel()},setlist:function(){},setresourcesmodel:function(){},validate:function(e){},setsyncmodel:function(){},setcollection:function(){},setview:function(){},url:function(){},sync:function(e,t,n){}})},collection:{Base:Backbone.Collection.extend({iSync:!1,initialize:function(){this.setonadd(),this.setonremove()},setonadd:function(){},setonremove:function(){},url:"",sync:function(e,t,n){},parse:function(e){},resetViewStatus:function(){this.each(function(e){e.iview.resetStatus()})}}),list:Backbone.Collection.extend({iSync:!0,url:"",setonadd:function(){this.on("add",function(e){})},setonremove:function(){},sync:function(e,t,n){e=="read"&&(n.url=context_url+"/overlayinit.json"),Backbone.emulateHTTP=!0,Backbone.emulateJSON=!0,Backbone.sync(e,t,n)},parse:function(e){},resetViewStatus:function(){this.each(function(e){e.iview.resetStatus()})}})},view:{Base:Backbone.View.extend({initialize:function(e){_.bindAll(this),this.model.bind("destroy",this.destroy),this.model.bind("change",this.change),this.initstart()},initstart:function(){this.preload(),this.renderDynamicElement(),this.render()},events:{},options:{},change:function(e){},renderStaticElement:function(){},renderDynamicElement:function(){var e=this.model.get("pageid");this.model.set("isMasterOverlay",!1);if(this.model.get("pagetype")=="LayerRef"){var t=this.model.get("parentpageid"),n=this.model.get("layerid"),r=interaction_view.ipagelist.getPage(t)||interaction_view.imasterlist.get(t);this.model.page=r.iOverlaylist.get(e).layer[n];var i=r.iOverlaylist.get(e);this.container=i.iview.$el.find(".layer-content").children(".layer-item[data-id="+n+"]")}else this.model.get("pagetype")=="master"?(this.container=$('.Presentation[id="'+interaction_view.currentPage+'"]').find(".interaction-view"),this.model.set("isMasterOverlay",!0)):this.model.get("pageid")?this.container=$('.Presentation[id="'+this.model.get("pageid")+'"]').find(".interaction-view"):this.container=$(".interaction-view");this.container.append(_.template(AnimateElementTemplate,this.model.toJSON())),this.setElement(this.container.find('div.iView.dynamic[id="'+this.model.id+'"]'));var s=this.getcommon();this.x=s.iStartx+s.iWidth/2,this.y=s.iStarty+s.iHeight/2,TweenMax.to(this.$el[0],0,{x:s.iStartx+s.iWidth/2,y:s.iStarty+s.iHeight/2}),this.model.get("pagetype")=="master"&&this.$el.addClass("master masterhide"),_.include(["CycleImage","Slide","Button"],this.model.get("iType"))&&this.setRatiofixxed()},preload:function(){},afterpreload:function(){this.setZindex(),this.setElementDisplay(),this.setOtherDisplay(),this.copyelstyle=this.$el.attr("style"),this.copyelementstyle=this.$el.children(".Element").attr("style"),this.preloaded=!0},setRatiofixxed:function(){var e=this,t=this.getdetail();if(!t.ratiofixxed||!t.iImg||t.iImg.length==0)return;var n=this.getcommon();_.each(t.iImg,function(r){var i=_g.ui.centerImage({containment:e.$el.find(".slidecontent"),Item:e.$el.find(".slidecontent").children()[t.iImg.indexOf(r)],parentWidth:n.iWidth,parentHeight:n.iHeight,width:r.width,height:r.height,setParent:!1});console.log(i),i.width<n.iWidth&&(e.$el.find(".slidecontent").children("[data-index="+t.iImg.indexOf(r)+"]").css("margin-left",(n.iWidth-i.width)/2+"px"),e.$el.find(".slidecontent").children("[data-index="+t.iImg.indexOf(r)+"]").css("margin-right",(n.iWidth-i.width)/2+"px")),i.height<n.iHeight&&(e.$el.find(".slidecontent").children("[data-index="+t.iImg.indexOf(r)+"]").css("margin-top",(n.iHeight-i.height)/2+"px"),e.$el.find(".slidecontent").children("[data-index="+t.iImg.indexOf(r)+"]").css("margin-bottom",(n.iHeight-i.height)/2+"px"))})},setElementDisplay:function(){this.$el.length>0,this.$el.children(".Element").length>0&&TweenMax.to(this.$el.children(".Element")[0],0,{scale:1});var e=this.model.toJSON().iDetail.iHidden||!1,t=this.model.page.iAnimationlist.where({overlay_id:this.model.id});if(t&&t[0]&&_.include([101,102,103],t[0].toJSON().iType)){var n=-9999,r=-9999;t[0]._animation&&t[0]._animation.css&&(n=t[0]._animation.css.x,r=t[0]._animation.css.y);if(t[0].toJSON().iType==101){e&&this.$el.addClass("hide");var i=this.getcommon().iWidth,s=this.getcommon().iHeight;TweenMax.to(this.$el[0],0,{x:n,y:r})}t[0].toJSON().iType==102&&(e&&this.$el.addClass("hide"),TweenMax.to(this.$el.children(".Element")[0],0,{scale:0})),t[0].toJSON().iType==103&&(e&&this.$el.addClass("hide"),TweenMax.to(this.$el[0],0,{opacity:0}))}else e?this.$el.addClass("hide"):this.$el.removeClass("hide");this.Clone=this.$el.clone()},setOtherDisplay:function(){},setZindex:function(){if(this.model.get("iType")=="Audio")return!1;var e=this.model.page.iOverlaylist.indexOf(this.model);this.model.get("pagetype")=="master"&&(e+=1e3),this.$el&&this.$el.css("z-index",e)},render:function(){var e=this.model.toJSON(),t=interaction.template.element(this.model.toJSON()),n=interaction.template.element(this.model.toJSON());return $(this.model.get("iParentdiv")).append(n),this.setElement(div_find(this.model.id)),this.updatebackground(),this.infoel=$("#info_attributes").children(".setting-body"),this},renderCentrolPos:function(e){document.getElementById(this.model.id).style.left=e.x-100+"px",document.getElementById(this.model.id).style.top=e.x-100+"px"},destroy:function(e,t){},updateposition:function(){var e=this.getcommon();e&&(this.$el.css("left",e.iStartx+"px"),this.$el.css("top",e.iStarty+"px"),this.$el.width(e.iWidth),this.$el.height(e.iHeight))},updateel:function(){this.model.get("iTemplate")&&this.$el.html(this.model.get("iTemplate")(this.model.toJSON()))},getcommon:function(){var e=null,t=this.model.toJSON();return this.model.get("iCommon")&&(e=t.iCommon[iPageDirection]),e},getdetail:function(){var e=this.model.toJSON();return e.iDetail},getCentralPos:function(){var e={},t=this.getcommon();return e.x=t.iStartx+t.iWidth/2,e.y=t.iStarty+t.iHeight/2,e},getCommonByCentralPos:function(e){var t=this.getcommon();return t.iStartx=e.x-t.iWidth/2,t.iStarty=e.y-t.iHight/2,t},setcommon:function(e){var t=this.model.toJSON(),n=t.iCommon;!_.isNaN(e.iStartx)&&!_.isNaN(e.iStarty)&&!_.isNaN(e.iWidth)&&!_.isNaN(e.iHeight)&&(n[iPageDirection]=e),this.model.set("iCommon",n)},setdetail:function(e){var t=this.model.toJSON(),n=t.iDetail;_.each(_.keys(e),function(t){n[t]=e[t]}),this.model.set("iDetail",n),this.updateinfo(),this.updatebackground(),this.updateresources()},settext:function(){var e=tinyMCE.getInstanceById("tEditor_"+this.model.id).getBody().innerHTML;this.setdetail({iText:e}),tinyMCE.getInstanceById("tEditor_"+this.model.id)&&(tinyMCE.execCommand("mceFocus",!1,"tEditor_"+this.model.id),tinyMCE.execCommand("mceRemoveControl",!1,"tEditor_"+this.model.id))},setCentralPos:function(e){var t=this.getcommon();t.iStartx=e.x-t.iWidth/2,t.iStarty=e.y-t.iHight/2,this.setcommon(t)},showdiv:function(){this.$el.removeClass("hide"),this.model.set("iVisibility",!0)},hidediv:function(){this.$el.addClass("hide"),this.model.set("iVisibility",!1)},resetStatus:function(){this.$el.attr("style",this.copyelstyle),this.$el.children(".Element").attr("style",this.copyelementstyle),this.setElementDisplay(),this.resetOtherStatus&&this.resetOtherStatus()},sendToPreload:function(e){var t={parentpageid:this.model.get("parentpageid"),overlay_id:this.model.id,elementtype:this.model.get("iType"),pageid:this.model.get("pageid"),pagetype:this.model.get("pagetype"),layerid:this.model.get("layerid")};t.file=e.file;var n=new interaction_view.model.Preload(t)},playTimeline:function(){console.log("begin to play timeline"),this.autoplay?this.timeline&&this.timeline.play():(this.autoplay=!0,this.slideel.children().show(),this.timeline.kill(),this.timeline=new TimelineMax({paused:!0,repeat:this.repeat,onComplete:this.setRewind()}),this.setTimeline(),this.timeline.play())},pauseTimeline:function(){this.timeline&&this.timeline.pause()},stopTimeline:function(){this.autoplay=!1,this.timeline.kill(),this.timeline=new TimelineMax({paused:!0,repeat:this.repeat}),this.setTimeline(),this.timeline.pause(1e-5)},setRewind:function(){var e=this,t=this.getdetail(),n=this.delay,r=function(){setTimeout(function(){e.timeline.pause(1e-5)},n*1e3)},i=t.iRepeat?-1:0,s=t.iRewind;return!i&&s?r:null},setLoopSwitch:function(){var e=this,t=0,n=this.delay;this.autoplay||(n=2);for(i=0;i<this.slidelength;i++){if(i==this.slidelength-1&&!this.repeat)return;var r=this.slideel.children('[data-index="'+i+'"]');this.timeline.add(TweenMax.to(r,1e-5,{css:{opacity:1}}),t),this.timeline.add(TweenMax.to(r,1e-5,{css:{opacity:0},onUpdateParams:[i+1<this.slidelength?i+1:0],onUpdate:this.onTimelineUpdate}),t+n);var s=this.slideel.children('[data-index="'+(i+1<this.slidelength?i+1:0)+'"]');this.timeline.add(TweenMax.to(s,1e-5,{css:{opacity:0}}),t),this.timeline.add(TweenMax.to(s,1e-5,{css:{opacity:1}}),t+n),t+=n+2e-5}},setNone:function(){var e=this,t=0,n=this.delay;this.autoplay||(n=.5);for(i=0;i<this.slidelength;i++){if(i==this.slidelength-1&&!this.repeat)return;var r=this.slideel.children('[data-index="'+i+'"]');this.timeline.add(TweenMax.to(r,1e-5,{css:{opacity:1}}),t),this.timeline.add(TweenMax.to(r,1e-5,{css:{opacity:0},onUpdateParams:[i+1<this.slidelength?i+1:0],onUpdate:this.onTimelineUpdate}),t+n);var s=this.slideel.children('[data-index="'+(i+1<this.slidelength?i+1:0)+'"]');this.timeline.add(TweenMax.to(s,1e-5,{css:{opacity:0}}),t),this.timeline.add(TweenMax.to(s,1e-5,{css:{opacity:1}}),t+n),t+=n+2e-5}},setFade:function(){var e=this,t=0,n=this.delay,r,s;this.autoplay||(n=0);for(i=0;i<this.slidelength;i++){i==0&&(r=this.slideel.children('[data-index="'+i+'"]'),this.timeline.add(TweenMax.to(r,0,{css:{opacity:1},onCompleteParams:[0],onComplete:e.onChangeSlideTo}),t),t+=n);if(i==this.slidelength-1){if(!this.repeat)break;r=this.slideel.children('[data-index="'+i+'"]'),this.timeline.add(TweenMax.to(r,1e-5,{css:{opacity:1}}),t),this.timeline.add(TweenMax.fromTo(r,.5,{opacity:1,ease:"Linear.easeNone"},{opacity:0,onUpdateParams:[i+1<this.slidelength?i+1:0],onUpdate:this.onTimelineUpdate}),t+1e-5),this.timeline.add(TweenMax.to(r,1e-5,{css:{opacity:0}}),t+.50001),s=this.slideel.children('[data-index="'+(i+1<this.slidelength?i+1:0)+'"]'),this.timeline.add(TweenMax.to(s,1e-5,{css:{opacity:1}}),t),this.timeline.add(TweenMax.fromTo(s,.5,{opacity:1},{opacity:1,ease:"Linear.easeNone"}),t+1e-5),this.timeline.add(TweenMax.to(s,1e-5,{css:{opacity:1},onCompleteParams:[i+1<this.slidelength?i+1:0],onComplete:e.onChangeSlideTo}),t+.50001),t+=n+.50002}else r=this.slideel.children('[data-index="'+i+'"]'),this.timeline.add(TweenMax.to(r,1e-5,{css:{opacity:1}}),t),this.timeline.add(TweenMax.fromTo(r,.5,{opacity:1,ease:"Linear.easeNone"},{opacity:1,onUpdateParams:[i+1<this.slidelength?i+1:0],onUpdate:this.onTimelineUpdate}),t+1e-5),this.timeline.add(TweenMax.to(r,1e-5,{css:{opacity:0}}),t+.50001),s=this.slideel.children('[data-index="'+(i+1<this.slidelength?i+1:0)+'"]'),this.timeline.add(TweenMax.to(s,1e-5,{css:{opacity:0}}),t),this.timeline.add(TweenMax.fromTo(s,.5,{opacity:0},{opacity:1,ease:"Linear.easeNone"}),t+1e-5),this.timeline.add(TweenMax.to(s,1e-5,{css:{opacity:1},onCompleteParams:[i+1<this.slidelength?i+1:0],onComplete:e.onChangeSlideTo}),t+.50001),t+=n+.50002}},setSlip:function(){var e=this,t=0,n=this.delay,r,s;this.autoplay||(n=0);for(i=0;i<this.slidelength;i++){if(i==this.slidelength-1&&!this.repeat)break;var o=this.getParamsForSlide(i).param,u=this.getParamsForSlide(i+1<this.slidelength?i+1:0).param1;o.onUpdateParams=[i+1<this.slidelength?i+1:0],o.onUpdate=this.onTimelineUpdate,i==0&&(r=this.slideel.children('[data-index="'+i+'"]'),this.timeline.add(TweenMax.to(r,0,{css:{opacity:1},onCompleteParams:[0],onComplete:e.onChangeSlideTo}),t),t+=n),r=this.slideel.children('[data-index="'+i+'"]'),this.timeline.add(TweenMax.to(r,1e-5,{css:{opacity:1}}),t),this.timeline.add(TweenMax.fromTo(r,.5,{left:"0px",top:"0px",ease:"Linear.easeNone"},_.clone(o)),t+1e-5),this.timeline.add(TweenMax.to(r,1e-5,{css:{opacity:0}}),t+.50001),s=this.slideel.children('[data-index="'+(i+1<this.slidelength?i+1:0)+'"]'),this.timeline.add(TweenMax.to(s,1e-5,{css:{opacity:1}}),t),this.timeline.add(TweenMax.fromTo(s,.5,_.clone(u),{top:"0px",left:"0px",ease:"Linear.easeNone"}),t+1e-5),this.timeline.add(TweenMax.to(s,1e-5,{css:{opacity:1},onCompleteParams:[i+1<this.slidelength?i+1:0],onComplete:e.onChangeSlideTo}),t+.50001),t+=n+.50002}},onBindingChangeTo:function(e){interaction_view.events.onBingChangeTo({type:e.type,page_id:this.model.get("pageid"),id:this.model.id,delta:e.delta,deltarate:e.deltarate,cdirection:e.cdirection})},onTimelineUpdate:function(e){var t=this.timeline.time();interaction_view.events.onBingChangeTo({type:0,page_id:this.model.get("pageid"),id:this.model.id,delta:-1,deltarate:t/this.timeline.duration(),cdirection:null})},onChangeSlideTo:function(e){this.currentIndex=e,this.model.trigger("slideTo",e)},onExecuteBinding:function(e){if(this.model.get("iType")=="LayerRef"){this.onExecuteBindingForLayerRef(e);return}var t=this;if(this.slideel&&this.slidelength>1&&this.timeline){var n=this.timeline.duration();this.repeat?singletime=n/this.slidelength:singletime=n/(this.slidelength-1);if(e.type==0){t.setSlideDisplayAll(),i=e.deltarate*n;var r=parseInt(i/singletime,10);t.timeline.seek(i),t.slideChangePatch(e.delta,r),t.onChangeSlideTo(r)}else{var i=t.timeline.time();console.log("stop at delta"+e.delta),t.model.get("iType")!="CycleImage"&&(i=parseInt(i/singletime,10)*singletime,e.delta<0&&i<n&&(i+=singletime)),i==0&&(i=1e-5),t.timeline.seek(i);var r=parseInt(i/singletime,10);r>t.slidelength-1&&(r=0),t.setSlideDisplay(r),t.onChangeSlideTo(r)}}},setSlideDisplay:function(e){this.autoplay||(this.slideel.children('[data-index="'+e+'"]').show().css("display","block"),this.slideel.children('[data-index="'+e+'"]').siblings().hide())},setSlideDisplayAll:function(){this.slideel.children().show()},setElementTo:function(e){if(Number(e)==NaN||this.currentIndex==Number(e))return;e=Number(e);var t=this.getdetail(),n=t.iRepeat,r=null,i;if(!this.slidelength||e>=this.slidelength)return;var s=this.timeline.duration();n?i=s/this.slidelength:i=s/(this.slidelength-1),console.log(this.timeline.time());if(e=="first")r=1e-5;else if(e=="last")r=(this.slidelength-1)*i;else if(e=="prev"){if(!n&&this.currentIndex==0)return!1;r=this.timeline.time()-i>=0?parseInt(this.timeline.time()/i-1,10)*i:i*(this.slidelength-1)}else if(e=="next"){if(!n&&this.currentIndex==this.slidelength-1)return!1;console.log("singletime is "+i),console.log("duration is "+s),console.log("time now is "+this.timeline.time()),r==1e-5&&(r=0),r=this.timeline.time()+i<s?parseInt(this.timeline.time()/i+1,10)*i:0}else{if(!(Number(e)>=0&&Number(e)<this.slidelength))return!1;r=i*parseInt(e,10)}console.log(r),r==0&&(r=1e-5),e=parseInt(r/i,10),e>this.slidelength-1&&(e=0),this.timeline.seek(r),this.setSlideDisplay(e),this.onChangeSlideTo(e)},slideChangePatch:function(e,t){var n=this;if(e>0)for(i=n.currentIndex;i>t;i--)i<0&&(i=n.slidelength-1),i!=n.currentIndex&&n.onChangeSlideTo(i);if(e<0)for(i=n.currentIndex;i<t;i++)i>n.slidelength-1&&(i=0),i!=n.currentIndex&&n.onChangeSlideTo(i)},control:function(){var e=_g.hasTouch,t=e?"touchstart":"mousedown",n=e?"touchmove":"mousemove",r=e?"touchend":"mouseup";eCancel=e?"touchcancel":"mouseleave";var i=this,s=this.getdetail(),o=0,u=0,a,f,l,c=0,h,p=!1,d=null,v=null,m=null,g=this.$el.children(".Element").width(),y=s.iSlidetype?Number(s.iSlidetype):0,b=this.timeline.duration(),w=y=="横向"||Number(y)==0?0:1;this.repeat?a=b/this.slidelength:a=b/(this.slidelength-1);var E=this.repeat,S=function(e){h=0,o=i.timeline.time(),p=!0,m=i.slideel.children(":visible").first().index(),console.log("control start")},x=function(e,t){i.setSlideDisplayAll(),e>b&&(E?e-=b:e=b),e<0&&(E?e=b+e:e=1e-5);var n=e/b;i.onBindingChangeTo({type:0,delta:t,deltarate:n,cdirection:w});if(i.model.get("iType")=="CycleImage"){var r=parseInt(e/a);r>i.slidelength-1&&(r=0),i.slideChangePatch(h,r),i.onChangeSlideTo(r)}i.timeline.seek(e)},T=function(e){o=i.timeline.time(),i.model.get("iType")!="CycleImage"&&(o=parseInt(o/a,10)*a,e<0&&o<b&&(o+=a)),o==0&&(o=1e-5),i.timeline.seek(o);var t=parseInt(o/a,10);t>i.slidelength-1&&(t=0),i.setSlideDisplay(t),i.onChangeSlideTo(t),i.onBindingChangeTo({type:1,delta:e})};this.$el.children(".Element").on(t,function(e){return i.testControl(e.target)?(e=_g.hasTouch?e.originalEvent.touches[0]:e,u=0,d=f=e.pageX,v=l=e.pageY,S(),!1):!1}),this.$el.children(".Element").on(n,function(e){e=_g.hasTouch?e.originalEvent.touches[0]:e;if(p&&d){h=y=="横向"||Number(y)==0?e.pageX-d:e.pageY-v,c=y=="横向"||Number(y)==0?e.pageX-f:e.pageY-l,f=e.pageX,l=e.pageY,i.setSlideDisplayAll();if(h==0)return;i.model.get("iType")=="CycleImage"?u=o-h/g*b:u=o-h/g*a,x(u,c)}return!1}),this.$el.children(".Element").on(r,function(e){if(p)return i.testControl(e.target)?(h!=0?T(h):(i.setSlideDisplay(m),$(e.currentTarget).trigger("click")),p=!1,console.log("control stop"),!1):!1}),this.$el.children(".Element").on(eCancel,function(e){if(p)return i.testControl(e.target)?(h!=0?T(h):i.setSlideDisplay(m),p=!1,console.log("control cancel"),!1):!1}),this.$el.children(".Element").on("wheelstart",function(e,t){u=0,d=f=0,v=l=0,h=0,o=i.timeline.time(),m=i.slideel.children(":visible").first().index(),console.log("control start")}),this.$el.children(".Element").on("wheelmove",function(e,t){var n=Math.max(-1,Math.min(1,t.wheelDeltaX||0)),r=Math.max(-1,Math.min(1,t.wheelDeltaY||-t.detail));console.log(r),f+=n/Math.abs(n)*20,l+=r/Math.abs(r)*20,console.log(l),h=y=="横向"||Number(y)==0?n:r,c=y=="横向"||Number(y)==0?n:r;var s=y=="横向"||Number(y)==0?f:l;s>1e3&&(s=999),s<-1e3&&(s=-999),i.model.get("iType")=="CycleImage"?u=o-s/1e3*b:u=o-s/1e3*a,x(u,c)}),this.$el.children(".Element").on("wheelend",function(e,t){var n=y=="横向"||Number(y)==0?f:l;T(n),f=l=0})},getParamsForFade:function(e){param.opacity=1,param1.opacity=0},getParamsForSlide:function(e){var t=this.getdetail(),n=t.iSlidetype?Number(t.iSlidetype):0,r=this.slideel.children('[data-index="'+e+'"]');if(this.model.get("iType")=="Slide"||this.model.get("iType")=="CycleImage")r=this.slideel;var i={ease:"Linear.easeNone"},s={ease:"Linear.easeNone"};return n=="横向"||Number(n)==0?(i.opacity=1,i.left="-"+r.css("width"),s.left=r.css("width"),s.opacity=1):(i.opacity=1,i.top="-"+r.css("height"),s.top=r.css("height"),s.opacity=1),{param:i,param1:s}},getSlideDuration:function(){var e=this.getdetail(),t;return this.slidelength==0?0:(this.model.get("iType")!="CycleImage"?t=(this.delay+.50002)*this.slidelength:t=(this.delay+2e-5)*this.slidelength,t)}})}},window.iOverlaylist=new interaction_view.collection.Base,interaction_view.iOverlaylist=new interaction_view.collection.list,interaction_view.currentPage=null}),define("interaction_view/ui/animation",["jquery","backbone"],function(){window.animation=function(e){this.defaults={countTime:0,currentFrame:0,path:null,raster:null,animation:null},this.options=e,this.options=$.extend(!0,{},this.defaults,typeof e=="object"&&e),this.page=this.options.collection.page,this.init()},window.animation.prototype={init:function(){_.bindAll(this),this.setparam()},cssTovalue:function(e){var t=e;return t=Number(e.split("px")[0]),t},EaseTypes:{0:"Linear.easeNone",1:"Power0.easeIn",2:"Power0.easeInOut",3:"Power0.easeOut",4:"Power1.easeIn",5:"Power1.easeInOut",6:"Power1.easeOut",7:"Power2.easeIn",8:"Power2.easeInOut",9:"Power2.easeOut",10:"Power3.easeIn",11:"Power3.easeInOut",12:"Power3.easeOut",13:"Power4.easeIn",14:"Power4.easeInOut",15:"Power4.easeOut",16:"Quad.easeIn",17:"Quad.easeInOut",18:"Quad.easeOut",19:"Cubic.easeIn",20:"Cubic.easeInOut",21:"Cubic.easeOut",22:"Quart.easeIn",23:"Quart.easeInOut",24:"Quart.easeOut",25:"Quint.easeIn",26:"Quint.easeInOut",27:"Quint.easeOut",28:"Strong.easeIn",29:"Strong.easeInOut",30:"Strong.easeOut",31:"Back.easeIn",32:"Back.easeInOut",33:"Back.easeOut",34:"Bounce.easeIn",35:"Bounce.easeInOut",36:"Bounce.easeOut",37:"Circ.easeIn",38:"Circ.easeInOut",39:"Circ.easeOut",40:"Elastic.easeIn",41:"Elastic.easeInOut",42:"Elastic.easeOut",43:"Expo.easeIn",44:"Expo.easeInOut",45:"Expo.easeOut",46:"Sine.easeIn",47:"Sine.easeInOut",48:"Sine.easeOut",49:"SlowMo.ease"},getTypeName:function(e){switch(e){case 100:return"出现动画";case 101:return"飞入";case 102:return"放大";case 103:return"渐现";case 200:return"消失动画";case 201:return"飞出";case 202:return"缩小";case 203:return"渐隐";case 300:return"运动路径";case 301:return"直线运动";case 302:return"曲线运动";case 400:return"强调动画";case 401:return"放大缩小";case 402:return"透明";case 403:return"旋转";case 500:return"媒体动画";case 501:return"播放";case 502:return"暂停";case 503:return"结束"}},play:function(){var e=this.page.iOverlaylist.get(this.options.animation.overlay_id);this.overlay_type=e.get("iType"),this.overlay_type=="Audio"?this.playmedia(this.options.animation.iType):_.include([501,502,503],this.options.animation.iType)?(console.info(this.options.animation.iType),this.playmedia(this.options.animation.iType)):_.include([101,102,103],this.options.animation.iType)?(console.info(this.param),this.tween=TweenMax.from(this.obj,this.options.animation.iTiming.duration,this.param)):this.tween=TweenMax.to(this.obj,this.options.animation.iTiming.duration,this.param)},playmedia:function(e){var t=this.page.iOverlaylist.get(this.options.animation.overlay_id);e==501&&t.loaded&&(t.get("iType")=="Audio"&&t.media&&console.log(t.media.getDuration()),t.get("iType")=="Video"&&t.iview.$el.removeClass("hide"),t.media.play()),e==502&&t.loaded&&t.media.pause(),e==503&&t.loaded&&(model.media.setCurrentTime(0),model.media.pause()),this.options.collection.onComplete(this.options.animation.id)},setpathparam:function(e){var t=this,n;this.pathoriginalpoint={},this.obj=this.page.iOverlaylist.get(this.options.animation.overlay_id).iview.$el[0];var r=this.options.animation.iDetail.autoRotate||!1;if(r){var i=this.page.iOverlaylist.get(this.options.animation.overlay_id).iview.$el.find(".Element").first()[0];this.param.onStart=function(){}}e==302&&(n=[],_.each(this.options.animation.iDetail.path,function(e){if(e.handleIn){var t={};t.x=e.handleIn.x+e.point.x,t.y=e.handleIn.y+e.point.y,n.push(t)}n.push({x:e.point.x,y:e.point.y});if(e.handleOut){var r={};r.x=e.handleOut.x+e.point.x,r.y=e.handleOut.y+e.point.y,n.push(r)}}),this.param.bezier={values:n,type:"cubic",autoRotate:r});if(e==301){n=[];var s;for(s in this.options.animation.iDetail.path){if(s!=0){var o=this.options.animation.iDetail.path[s-1],u=this.options.animation.iDetail.path[s],a={x:(o.point.x+u.point.x)/2,y:(o.point.y+u.point.y)/2};n.push(a)}n.push({x:this.options.animation.iDetail.path[s].point.x,y:this.options.animation.iDetail.path[s].point.y})}this.param.bezier={values:n,type:"quadratic",autoRotate:r}}},setappearparam:function(e){this.fromparam={},this.fromparam.onStart=this.showelement,this.fromparam.immediateRender=!1,this.toparam={},this.toparam.onComplete=this.param.onComplete,this.toparam.delay=this.param.delay,this.toparam.repeat=this.param.repeat,this.toparam.ease=this.param.ease;var t,n,r;if(e==101){t=this.options.animation.iDetail.direction||0;var i=this.page.iOverlaylist.get(this.options.animation.overlay_id).iview.x,s=this.page.iOverlaylist.get(this.options.animation.overlay_id).iview.y,o=this.page.iOverlaylist.get(this.options.animation.overlay_id).iview.$el.find(".Element").first().width(),u=this.page.iOverlaylist.get(this.options.animation.overlay_id).iview.$el.find(".Element").first().height();n={};switch(t){case 0:n.y="-"+u,n.x=i;break;case 1:n.x=interaction_view.size.x+o,n.y=s;break;case 2:n.y=interaction_view.size.y+u,n.x=i;break;case 3:n.x="-"+o,n.y=s}this.param.css=n,this.fromparam.css={x:Number(n.x),y:Number(n.y)},this.toparam.css={x:Number(i),y:Number(s)},this.obj=this.page.iOverlaylist.get(this.options.animation.overlay_id).iview.$el[0]}if(e==102){t=this.options.animation.iDetail.direction||0,r={},n={};var a=this.page.iOverlaylist.get(this.options.animation.overlay_id);r.scale=0,this.param.css=r,this.fromparam.css={scale:0},this.toparam.css={scale:1},this.obj=this.page.iOverlaylist.get(this.options.animation.overlay_id).iview.$el.find(".Element").first()[0]}e==103&&(t=this.options.animation.iDetail.direction||0,r={},this.param.css={opacity:0},this.fromparam.css={opacity:0},this.toparam.css={opacity:1},this.obj=this.page.iOverlaylist.get(this.options.animation.overlay_id).iview.$el[0])},setdisappearparam:function(e){var t={};if(e==201){var n=this.options.animation.iDetail.direction||0;this.obj=this.page.iOverlaylist.get(this.options.animation.overlay_id).iview.$el[0];var r=this.page.iOverlaylist.get(this.options.animation.overlay_id).iview.$el.find(".Element").first().width()*2,i=this.page.iOverlaylist.get(this.options.animation.overlay_id).iview.$el.find(".Element").first().height()*2;switch(n){case 0:t.y="-"+i;break;case 1:t.x=interaction_view.size.x+r;break;case 2:t.y=interaction_view.size.y+i;break;case 3:t.x="-"+r}this.param.css=t}if(e==202){var s=this.page.iOverlaylist.get(this.options.animation.overlay_id);t.scale=0,this.param.css=t,this.obj=this.page.iOverlaylist.get(this.options.animation.overlay_id).iview.$el.find(".Element").first()[0]}e==203&&(this.param.css={opacity:0},this.obj=this.page.iOverlaylist.get(this.options.animation.overlay_id).iview.$el[0]),this.param.onComplete=this.hideelement},setstrongparam:function(e){if(e==401){var t=this.page.iOverlaylist.get(this.options.animation.overlay_id),n={};this.obj=this.page.iOverlaylist.get(this.options.animation.overlay_id).iview.$el.find(".Element").first()[0],n.scale=this.options.animation.iDetail.scale||2,this.param.css=n}if(e==402){this.obj=this.page.iOverlaylist.get(this.options.animation.overlay_id).iview.$el[0];var r=this.options.animation.iDetail.opacity||0;this.param.css={opacity:r}}if(e==403){this.obj=this.page.iOverlaylist.get(this.options.animation.overlay_id).iview.$el[0];var i=this.options.animation.iDetail.rotation||180,s=this.options.animation.iDetail.axial||0,o="_cw",u="+";i<0&&(o="_ccw"),i<0&&(u="-");var n={};s==0&&(n.rotation=u+"="+Math.abs(i)+o),s==1&&(n.rotationX=u+"="+Math.abs(i)+o),s==2&&(n.rotationY=u+"="+Math.abs(i)+o),this.param.css=n}},setparam:function(){var e=this;this.param={},this.param.data=this.options.animation;var t=this.page.iOverlaylist.get(this.options.animation.overlay_id);this.param.onComplete=this.stop,this.param.onCompleteParams=["{self}"],this.param.ease=this.EaseTypes[this.options.animation.iTiming.ease||0];var n=this.options.animation.iTiming.repeat||0;n==0||n==-1?this.param.repeat=n:n==-2?this.param.repeat=-1:this.param.repeat=n;switch(this.options.animation.iType){case 100:return"出现动画";case 101:this.setappearparam(101);break;case 102:this.setappearparam(102);break;case 103:this.setappearparam(103);break;case 200:return"消失动画";case 201:this.setdisappearparam(201);break;case 202:this.setdisappearparam(202);break;case 203:this.setdisappearparam(203);break;case 300:return"运动路径";case 301:this.setpathparam(301);break;case 302:this.setpathparam(302);break;case 400:return"强调动画";case 401:this.setstrongparam(401);break;case 402:this.setstrongparam(402);break;case 403:this.setstrongparam(403);break;case 500:return"媒体动画";case 501:this.setmedia(501);break;case 502:this.setmedia(502);break;case 503:this.setmedia(503)}},setmedia:function(e){},pathstop:function(e){var t=this.options.animation.iTiming.rewind||!1;t&&this.options.animation.iTiming.repeat!=-1&&this.options.animation.iTiming.repeat!=-2&&this.options.animation.iDetail.path&&this.options.animation.iDetail.path[0]&&e.pause(0)},animationstop:function(e){var t=this.options.animation.iTiming.rewind||!1;t&&this.options.animation.iTiming.repeat!=-1&&this.options.animation.iTiming.repeat!=-2&&e.pause(0)},stop:function(e){this.animationstop(e),this.options.collection.onComplete(this.options.animation.id)},forcestop:function(e){var t=this.options.animation.iTiming.rewind||!1;t?e.pause(0):e.pause(this.options.animation.iTiming.duration),this.options.collection.onComplete(this.options.animation.id)},addclickcontrol:function(){this.options.collection.addclickstop(this.options.animation.id)},showelement:function(){console.log("on start show"),this.page.iOverlaylist.get(this.options.animation.overlay_id).iview.$el.removeClass("hide")},hideelement:function(){this.page.iOverlaylist.get(this.options.animation.overlay_id).iview.$el.addClass("hide")}}}),define("interaction_view/model/action",["interaction_view/model/base","interaction_view/ui/animation"],function(){interaction_view.model.Action=interaction_view.model.Base.extend({defaults:{page_id:null,ref_id:null,index:null,layer_id:null,overlay_id:null},setcollection:function(){},setview:function(e){this.pageid=this.get("pageid"),this.parentpageid=this.get("parentpageid");if(this.get("pagetype")=="LayerRef"){var t=this.get("parentpageid"),n=this.get("layerid"),r=interaction_view.ipagelist.getPage(t)||interaction_view.imasterlist.get(t);this.parentpage=r,this.page=r.iOverlaylist.get(this.pageid).layer[n]}else this.page=interaction_view.ipagelist.getPage(this.pageid)||interaction_view.imasterlist.get(this.pageid);this.actionpatch(),this.iview=new interaction_view.view.Action({model:this})},setsyncmodel:function(){},actionpatch:function(){var e=this,t=this.get("iDetail");this.get("pagetype")=="LayerRef"&&(this.get("layer_id")||this.set("layer_id",this.get("layerid"))),t.results[0].iAction!=5&&t.results[0].iAction<7&&(t.results[0].iAction==6&&typeof t.results[0].values=="string"&&(t.results[0].values=[{id:t.results[0].values,page_id:e.pageid}]),t.results[0].values=_.map(t.results[0].values,function(t){return typeof t!="object"?{id:t,page_id:e.pageid}:t})),this.set("iDetail",t)}}),interaction_view.collection.Action=interaction_view.collection.Base.extend({initialize:function(){this.setonadd(),this.setonremove()},model:interaction_view.model.Action,setonadd:function(){this.on("add",function(e){})},onSingleComplete:function(){},onUpdate:function(){},onTotalComplete:function(){},resetStatus:function(){this.each(function(e){e.iview.resetStatus()})}}),interaction_view.view.Action=interaction_view.view.Base.extend({initstart:function(){},getAnimationPage:function(e,t){return interaction_view.ipagelist.getPage(e)||interaction_view.imasterlist.get(e)?interaction_view.ipagelist.getPage(e)||interaction_view.imasterlist.get(e):this.model.page},renderanimations:function(){var e=this,t=this.model.toJSON();this.timeline=new TimelineMax({paused:!0}),this.timeline.addLabel("Start"),this.TotalDuration=0;var n=this.values;n&&(_.each(n,function(t){var r=t.page_id,i=e.getAnimationPage(r),s=i.iAnimationlist.get(t.id);if(!s)return;var o=s.toJSON(),u=s._animation.obj,a=$.extend(!0,{},s._animation.param),f=s.toJSON().iTiming.duration||0,l=s.toJSON().iTiming.repeat||0,c=o.iTiming.delay||0;e.TotalDuration+=c,f=f;var h=_.pluck(n,"id").indexOf(s.id);if(o.iTiming.start==0)e.timeline.addLabel(s+"_start",e.TotalDuration),e.timeline.call(i.iAnimationlist.AddClickTween,[e],this,e.TotalDuration-c);else if(o.iTiming.start==2)if(h!=0){var p=e.timeline.getLabelTime(n[h-1].id+"_start");e.timeline.addLabel(s.id+"_start",p+c),e.TotalDuration=e.timeline.getLabelTime(s.id+"_start")}else e.timeline.addLabel(s.id+"_start",e.TotalDuration);else e.timeline.addLabel(s.id+"_start",e.TotalDuration);if(_.include([501,502,503],s.get("iType"))){var d=i.iAnimationlist.getMediaTime(s);s.get("iType")==502||s.get("iType")==503?f=0:f=d,e.timeline.call(i.iAnimationlist.AddMediaTween,[s],this,e.TotalDuration)}else o.iTiming.repeat!=0?e.timeline.call(i.iAnimationlist.AddRepeatTween,[s],this,e.TotalDuration):_.include([101,102,103],s.get("iType"))?(console.log(s._animation),e.timeline.add(TweenMax.fromTo(u,f,s._animation.fromparam,s._animation.toparam),e.TotalDuration)):e.timeline.add(TweenMax.to(u,f,s._animation.param),e.TotalDuration);console.log("this time is :"+e.TotalDuration),e.TotalDuration+=f,e.timeline.addLabel(s.id+"_end",e.TotalDuration)}),e.timeline.play(0))},onComplete:function(){},events:{},renderDynamicElement:function(){},getClassification:function(){if(!this.ref_id){if(_.isNumber(this.index)&&this.overlaymodel)return 4;if(!_.isNumber(this.index)&&this.overlaymodel)return 1;if(!this.overlaymodel){if(this.overlay_id==this.model.page.id)return 2;if(interaction_view.ilayerlist.get(this.overlay_id))return 3}}if(this.ref_id&&this.model.get("pagetype")=="LayerRef"&&this.model.pageid==this.ref_id&&this.model.parentpageid==this.page_id){if(_.isNumber(this.index)&&this.overlaymodel)return 4;if(!_.isNumber(this.index)&&this.overlaymodel)return 1;if(!this.overlaymodel){if(this.overlay_id==this.model.page.id)return 2;if(interaction_view.ilayerlist.get(this.overlay_id))return 3}}return 0},render:function(){this.iType=this.model.toJSON().iType,this.overlay_id=this.model.toJSON().overlay_id,this.page_id=this.model.toJSON().page_id,this.ref_id=this.model.toJSON().ref_id,this.index=this.model.toJSON().index;var e=this.model.toJSON().iDetail;if(!e||!e.results)return;var t=this;this.actiontype=e.results[0].iAction,this.values=e.results[0].values,this.overlaymodel=this.model.page.iOverlaylist.get(this.overlay_id);var n=this.getClassification();if(!n)return;switch(n){case 1:this.renderforoverlay();break;case 2:this.renderforpage();break;case 3:this.renderforlayer();break;case 4:this.renderforslideindex()}},renderforoverlay:function(){var e=this;this.TotalDuration=0,this.overlaymodel.iview.$el.css("cursor","pointer"),this.overlaymodel.iview.$el.addClass("hasaction");var t=this.overlaymodel.iview.$el;_.include(["Slide","LayerSlide","CycleImage"],this.overlaymodel.get("iType"))&&(t=t.children(".Element")),this.iType==1&&(t=this.overlaymodel.iview.$el.find("img.iconNormal")),this.iType==2&&(t=this.overlaymodel.iview.$el.find("img.iconActive"));if(!t)return;t.on("click",function(t){if(_.include(["Slide","LayerSlide","CycleImage"],e.overlaymodel.get("iType"))&&!$(t.target).is(t.currentTarget))return!1;e.executeAction(e)})},renderforlayer:function(){var e=this,t=this.model.get("layerid"),n=this.model.parentpage.iOverlaylist.get(this.model.get("pageid")).toJSON().iDetail.layer_ids.indexOf(t);if(n==-1)return!1;this.iType==0&&this.model.parentpage&&this.model.parentpage.iOverlaylist.get(this.model.get("pageid")).iview.$el.children(".Element").on("click",function(t){if(!$(t.target).is(t.currentTarget)&&$(t.currentTarget).find(".layer-content").first().children().length>1)return!1;e.model.parentpage.iOverlaylist.get(e.model.get("pageid")).iview.currentIndex==n&&e.testControlforLayer(t)&&e.executeAction(e)}),this.iType==3&&interaction_view.events.pageStartEvents.push({type:"page",page_id:e.model.pageid,layer_id:this.model.get("layerid"),func:function(){e.executeAction(e)}}),this.iType==4&&this.model.parentpage&&this.model.parentpage.iOverlaylist.get(this.model.get("pageid")).iview.$el.children(".Element").on("dblclick",function(t){if($(t.target).closest(".layer-item").index()!=e.model.parentpage.iOverlaylist.get(e.model.get("pageid")).iview.currentIndex)return;e.model.parentpage.iOverlaylist.get(e.model.get("pageid")).iview.currentIndex==n&&e.testControlforLayer(t)&&e.executeAction(e)})},renderforpage:function(){var e=this;this.iType==0&&interaction_view.events.pageClickEvents.push({type:e.model.page.id==interaction_view.imasterlist.at(0).id?"master":"page",page_id:e.model.page.id,func:function(){e.executeAction(e)}}),this.iType==3&&interaction_view.events.pageStartEvents.push({type:"page",page_id:e.model.page.id,func:function(){e.executeAction(e)}}),this.iType==4&&interaction_view.events.pageDblClickEvents.push({type:e.model.page.id==interaction_view.imasterlist.at(0).id?"master":"page",page_id:e.model.page.id,func:function(){e.executeAction(e)}})},renderforslideindex:function(){this.overlaymodel.get("iType")!="CycleImage"&&this.overlaymodel.get("iType")!="Slide";if(!(this.overlaymodel.iview.slideel&&this.overlaymodel.iview.slideel.children().length>0&&this.overlaymodel.iview.slideel.children('[data-index="'+this.index+'"]').length>0))return!1;var e=this;this.iType==0&&(this.overlaymodel.iview.slideel.children('[data-index="'+this.index+'"]').addClass("hasaction"),this.overlaymodel.iview.slideel.children('[data-index="'+this.index+'"]').on("click",function(t){console.log(t.target),e.overlaymodel.iview.currentIndex==e.index&&e.executeAction(e)})),this.iType==5&&interaction_view.events.elementChangeToEvents.push({type:"slide",page_id:e.model.pageid,overlay_id:this.overlaymodel.id,index:this.index,func:function(){e.executeAction(e)}}),this.iType==4&&this.overlaymodel.iview.slideel.children('[data-index="'+this.index+'"]').on("dblclick",function(t){e.executeAction(e)})},executeAction:function(e){if(typeof Reveal!="undefined"&&Reveal&&Reveal.isOverview()&&e.iType!=3)return!1;e.actiontype==0&&e.renderanimations(),e.actiontype==1&&e.rendershow(),e.actiontype==2&&e.renderhide(),e.actiontype==6&&e.setElementTo(),e.actiontype==5&&(interaction_view.foredit?global.message("warning","请使用playAll模式预览该功能"):e.renderpage()),e.actiontype==7&&(interaction_view.foredit?global.message("warning","请使用playAll模式预览该功能"):e.renderoverview()),e.actiontype==8&&(interaction_view.foredit?global.message("warning","请使用playAll模式预览该功能"):e.rendershare()),e.actiontype==10&&(interaction_view.foredit?global.message("warning","请使用playAll模式预览该功能"):e.renderurl())},rendershare:function(){interaction_view.presentate.share_overlay.toggle()},renderoverview:function(){Reveal.toggleOverview(!0)},renderclick:function(){},rendershow:function(){var e=this,t=this.values;t&&_.each(t,function(t){var n=t.page_id,r=e.getAnimationPage(n),i=r.iOverlaylist.get(t.id);i&&i.iview&&i.iview.$el&&i.iview.$el.removeClass("hide")})},renderhide:function(){var e=this,t=this.values;t&&_.each(t,function(t){var n=t.page_id,r=e.getAnimationPage(n),i=r.iOverlaylist.get(t.id);i&&i.iview&&i.iview.$el&&i.iview.$el.addClass("hide")})},renderpage:function(){var e=this.model.toJSON().iDetail,t=this.values,n=null,r=null,i=e.results[0].iActionDetail?e.results[0].iActionDetail.transition?e.results[0].iActionDetail.transition:0:0;if(i==0||i)if(t!="first"&&t!="last"&&t!="prev"&&t!="next"){var s=interaction_view.ipagelist.getPage(t);console.log(i),s&&(i<4?interaction_view.ipagelist.getPage(t).iview.$el.attr("data-transition","linear"):i<8?interaction_view.ipagelist.getPage(t).iview.$el.attr("data-transition","page"):i==8?interaction_view.ipagelist.getPage(t).iview.$el.attr("data-transition","fade"):interaction_view.ipagelist.getPage(t).iview.$el.removeAttr("data-transition"))}var o=interaction_view.ipagelist.length;switch(t){case"first":Reveal.slide(0);break;case"last":Reveal.slide(o-1);break;case"prev":Reveal.prev();break;case"next":Reveal.next();break;default:if(interaction_view.ipagelist.getPage(t)){var u=interaction_view.ipagelist.getPage(t);interaction_view.doc.toJSON().play_mode==0?(n=interaction_view.ipagelist.indexOf(u),Reveal.slide(n)):(n=u.collection.parent.collection.indexOf(u.collection.parent),r=u.collection.indexOf(u),Reveal.slide(n,r))}}},renderurl:function(){if(this.values.length==0||_.isEmpty(this.values[0].url))return;var e=this.values[0].url;e.indexOf("://")==-1&&(e="http://"+e),window.open(e,"_blank")},setElementTo:function(){var e=this,t=this.model.toJSON().iDetail,n=this.values[0].id,r=this.values[0].page_id,i=e.getAnimationPage(r),s=t.results[0].iActionDetail?t.results[0].iActionDetail.index:null;if(n&&s){var o=i.iOverlaylist.get(n);o&&o.iview&&o.iview.setElementTo(s)}this.overlaymodel&&this.overlaymodel.toJSON().iType=="Button"&&(this.overlaymodel.iview.groupcontrol=!0,this.syncbuttons(i,this.model.toJSON().overlay_id,this.values[0]))},syncbuttons:function(e,t,n){var r=this,i=_.filter(this.model.page.iActionlist.toJSON(),function(e){return r.model.page.iOverlaylist.get(e.overlay_id)&&r.model.page.iOverlaylist.get(e.overlay_id).get("iType")=="Button"&&e.iDetail.results[0].iAction==6});_.each(i,function(e){if(e.overlay_id!=t){var i=r.model.page.iOverlaylist.get(e.overlay_id);i&&i.toJSON().iDetail.isSwitch&&e.iDetail.results&&e.iDetail.results[0].values[0].id==n.id&&e.iDetail.results[0].values[0].page_id==n.page_id&&i.iview.resetButtonStatus()}})},resetStatus:function(){this.overlaymodel.iview.$el.off("click")},testControlforLayer:function(e){var t=$(e.target).closest(".iView");if($(e.target).closest(".iView").hasClass("hasaction"))return!1;if(t){var n=t.attr("data-type");if(n=="Slide"||n=="CycleImage")if(t.attr("data-iSlipable"))return!1}return!0}}),interaction_view.iActionlist=new interaction_view.collection.Action}),define("interaction_view/model/animation_view",["interaction_view/model/base","interaction_view/ui/animation"],function(){interaction_view.model.Animation=interaction_view.model.Base.extend({defaults:{},setcollection:function(){},setview:function(e){this.iview=new interaction_view.view.Animation({model:this})},setsyncmodel:function(){}}),interaction_view.collection.Animation=interaction_view.collection.Base.extend({initialize:function(){this.setonadd(),this.setonremove()},model:interaction_view.model.Animation,setonadd:function(){this.on("add",function(e){})},setParams:function(e){this.repeatTweens=[];if(this.length==0)return;var t=this;if(this.pagetype=="LayerRef"){var n=this.layerid,r=interaction_view.ipagelist.getPage(this.parentpageid)||interaction_view.imasterlist.get(this.arentpageid);this.page=r.iOverlaylist.get(this.pageid).layer[n]}else this.page=interaction_view.ipagelist.getPage(this.pageid)||interaction_view.imasterlist.get(this.pageid);this.each(function(e){e.tween=null;var n=e.toJSON();if(!t.page.iOverlaylist.get(n.overlay_id))return;e._animation=new animation({collection:t,animation:e.toJSON()})})},setPlay:function(e){if(this.length==0)return;var t=this,n=function(){};this.timeline=new TimelineMax({paused:!0,onStart:n}),this.timeline.addLabel("Start"),this.TotalDuration=0,this.each(function(e){var n=e.toJSON();if(!t.page.iOverlaylist.get(n.overlay_id))return;if(n.iTiming.waitaction&&!interaction_view.SinglePreview)return;var r=e._animation.obj,i=$.extend(!0,{},e._animation.param),s=e.toJSON().iTiming.duration||0,o=e.toJSON().iTiming.delay||0;t.TotalDuration+=o,s=s;var u=t.indexOf(e);if(n.iTiming.start==0)t.timeline.addLabel(e.id+"_start",t.TotalDuration),t.timeline.call(t.AddClickTween,[t],this,t.TotalDuration-o);else if(n.iTiming.start==2)if(u!=0){var a=t.timeline.getLabelTime(t.at(u-1).id+"_start");t.timeline.addLabel(e.id+"_start",a+o),t.TotalDuration=t.timeline.getLabelTime(e.id+"_start")}else t.timeline.addLabel(e.id+"_start",t.TotalDuration);else t.timeline.addLabel(e.id+"_start",t.TotalDuration);if(_.include([501,502,503],e.get("iType"))){var f=t.getMediaTime(e);e.get("iType")==502||e.get("iType")==503?s=0:s=f,t.timeline.call(t.AddMediaTween,[e],this,t.TotalDuration)}else n.iTiming.repeat!=0?t.timeline.call(t.AddRepeatTween,[e],this,t.TotalDuration):_.include([101,102,103],e.get("iType"))?t.timeline.add(e.tween=TweenMax.fromTo(r,s,e._animation.fromparam,e._animation.toparam),t.TotalDuration):t.timeline.add(e.tween=TweenMax.to(r,s,i),t.TotalDuration);t.TotalDuration+=s,t.timeline.addLabel(e.id+"_end",t.TotalDuration)})},play:function(){if(this.length==0)return;this.setPlay(),this.timeline.play(0)},playMain:function(){if(this.length==0)return;this.setParams(),this.setPlay(),this.timeline.play(0),this.afterTimeLineCreated&&this.afterTimeLineCreated()},AddClickTween:function(e){if(interaction_view.SinglePreview)return;e.timeline.pause(),$(".interaction-view").css("cursor","pointer"),interaction_view.events.pageClickEvents.push({type:"waitaction",page_id:e.page?e.page.id:null,func:function(){$(".interaction-view").css("cursor","auto"),e.timeline.resume()}})},AddRepeatTween:function(e){var t=e._animation.obj,n=$.extend(!0,{},e._animation.param),r=e.toJSON().iTiming.duration||0,i=e.toJSON().iTiming.repeat||0;_.include([101,102,103],e.get("iType"))?e.tween=TweenMax.fromTo(t,r,e._animation.fromparam,e._animation.toparam):e.tween=TweenMax.to(t,r,n),i==-2&&$(".interaction-view").one("click",function(){e._animation.forcestop(e.tween)}),e.collection.repeatTweens.push(e.tween)},AddMediaTween:function(e){var t=e.collection.page;if(interaction_view.SinglePreview){var n=t.iAnimationlist.timeline.getLabelTime(interaction_view.PreviewItemId+"_start"),r=t.iAnimationlist.timeline.getLabelTime(e.id+"_start");if(n>r)return}var i=t.iOverlaylist.get(e.get("overlay_id")),s=e.get("iType");s==501&&(i.get("iType")=="Audio"||i.get("iType")=="Video"?i.loaded&&(i.get("iType")=="Audio"&&(console.log(i.media),i.media.play()),i.get("iType")=="Video"&&(i.iview.$el.removeClass("hide"),i.hided=!1,setTimeout(function(){i.media.play()},100))):i.iview.playTimeline()),s==502&&(i.get("iType")=="Audio"||i.get("iType")=="Video"?i.loaded&&i.media.pause():i.iview.pauseTimeline());if(s==503)if(i.get("iType")=="Audio"||i.get("iType")=="Video"){if(i.loaded){i.media.setCurrentTime(0),i.media.pause();if(i.get("iType")=="Video"){var o=i.get("iDetail").iAutohide;o==null&&(o=!0),o&&i.iview.$el.addClass("hide")}}}else i.iview.stopTimeline();t.iAnimationlist.onComplete(e.id)},getMediaTime:function(e){var t=0,n=this.page.iOverlaylist.get(e.toJSON().overlay_id);return n.media?(n.get("iType")=="Audio"&&(t=n.media.duration),n.get("iType")=="Video"&&(t=n.media.duration)):_.include(["CycleImage","Slide","LayerSlide"],n.get("iType"))&&(t=n.iview.getSlideDuration()),t},onSingleComplete:function(){},onUpdate:function(){},onTotalComplete:function(){},onComplete:function(e){},resetAnimationStatus:function(){_.each(this.repeatTweens,function(e){e.kill()}),this.repeatTweens=[],this.timeline&&this.timeline.pause(0)}}),interaction_view.view.Animation=interaction_view.view.Base.extend({events:{},renderDynamicElement:function(){},render:function(e){}}),interaction_view.iAnimationlist=new interaction_view.collection.Animation}),define("interaction_view/model/audio",["interaction_view/model/base"],function(){interaction_view.model.Audio=interaction_view.model.Base.extend({defaults:{iType:"Audio",iLock:!0,iVisibility:!0,iCommon:{portait:{iStartx:400,iStarty:200,iWidth:200,iHeight:200},landscape:{iStartx:400,iStarty:200,iWidth:200,iHeight:200}},iDetail:{iAdapt:!1,iFullview:!1,iImg:null,iAnimation:[]},iParent:"",iChild:"",iOptions:{createfocus:!0},iParentModel:null,iDraggable:!0,iResizable:!0,iTemplate:null,iParentdiv:".interaction-view",iAutoindex:!1,iSync:!1,iZindex:"-1",iUrl:null,iAutofocus:!1,iKeyscontrol:!0,callback:null,iBackground:"rgba(62,189,255,0.5)",iResourcesProperties:[{id:"iImg",type:"single"}],iAnimationProperties:[{id:"iAnimation",type:"object"}]},setcollection:function(){iOverlaylist.get(this.id)||iOverlaylist.add(this)},setview:function(e){this.iview=new interaction_view.view.Audio({model:this})},setsyncmodel:function(){}}),interaction_view.view.Audio=interaction_view.view.Base.extend({events:{},renderDynamicElement:function(){},render:function(e){},preload:function(){var e=this.getdetail();this.model.played=!1,this.model.time=0;if(e.iFile&&e.iFile[0]){var t=e.iFile[0].file||e.iFile[0].content;this.sendToPreload({file:t})}},afterpreload:function(){this.preloaded=!0},resetStatus:function(){this.model.media&&(this.model.media.setCurrentTime(0),this.model.media.pause())}})}),define("interaction_view/model/chapter",["interaction_view/model/base"],function(){interaction_view.model.Chapter=interaction_view.model.Base.extend({defaults:{},setcollection:function(){},setmodel:function(){this.setview()},setview:function(e){this.icollection=new interaction_view.collection.Chapter,this.iview=new interaction_view.view.Chapter({model:this})},setsyncmodel:function(){}}),interaction_view.collection.Chapter=interaction_view.collection.Base.extend({initialize:function(){},model:interaction_view.model.Chapter}),interaction_view.view.Chapter=interaction_view.view.Base.extend({initstart:function(){},events:{},renderDynamicElement:function(){},render:function(e){}}),interaction_view.iChapter=new interaction_view.model.Chapter({id:"chapter"})}),function(){var e={uuid:function(){function e(){return Math.floor((1+Math.random())*65536).toString(16).substring(1)}return e()+e()+e()+e()+e()+e()+e()+e()},getUrlParameterByName:function(e){e=e.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]");var t=new RegExp("[\\?&]"+e+"=([^&#]*)"),n=t.exec(location.search);return n==null?null:decodeURIComponent(n[1].replace(/\+/g," "))},parseTemplate:function(e){var t=null;return typeof e=="function"&&(t=e),typeof e=="string"&&(t=_.template(e)),t},browserSupport:function(e){var t=!1,n={msie:1,chrome:1,mozilla:1,safari:1,opera:1,success:null,fail:null};e=e?$.extend(!0,{},n,e):$.extend(!0,{},n);var r=parseInt($.browser.version,10);return $.browser.msie&&e.msie==1||$.browser.chrome&&e.chrome==1||$.browser.mozilla&&e.mozilla==1||$.browser.safari&&e.safrai==1&&$.browser.opera&&e.opera==1?t=!0:$.browser.msie&&e.msie==0||$.browser.chrome&&e.chrome==0||$.browser.mozilla&&e.mozilla==0||$.browser.safari&&e.safrai==0&&$.browser.opera&&e.opera==0?t=!1:($.browser.msie&&(t=r>=e.msie),$.browser.chrome&&(t=r>=e.chrome),$.browser.mozilla&&(t=r>=e.mozilla),$.browser.opera&&(t=r>=e.opera),$.browser.safari&&(t=r>=e.safari)),t?e.success&&e.success():e.fail&&e.fail(),t},array:{move2first:function(e,t){var n=[];n.push(t);for(i=0;i<e.length;i++)e[i]!=t&&n.push(e[i]);return n},move2last:function(e,t){var n=[];for(i=0;i<e.length;i++)e[i]!=t&&n.push(e[i]);return n.push(t),n},randomPick:function(e){return e[Math.floor(Math.random()*e.length)]},maptree:function(e){var t={treesource:null,mapdata:null,idAttribute:"id"};e=e?$.extend(!0,{},t,e):$.extend(!0,{},t);if(!e.treesource||!e.mapdata)return[];var n=[];return _.each(e.treesource,function(t){t.children&&(t.children=_g.array.maptree({treesource:t.children,mapdata:e.mapdata,idAttribute:e.idAttribute}));var r=_.find(e.mapdata,function(n){return n[e.idAttribute]==t[e.idAttribute]});r&&(t=$.extend(!0,t,r)),n.push(t)}),n}},object:{jsonparse:function(e){if(!e)return null;try{return a=JSON.parse(e),a}catch(t){return e}},equal:function(e,t){}},string:{randomGenerate:function(e){e=e?e:10;var t="",n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";for(var r=0;r<e;r++)t+=n.charAt(Math.floor(Math.random()*n.length));return t},getUrlExt:function(e){return e.match(/(.[^.]+|)$/)[0]}},"boolean":{randomPick:function(){return!!Math.round(Math.random()*1)}},number:{random:function(e,t){return typeof e=="undefined"&&(e=0),typeof t=="undefined"&&(t=100),Math.random()*(t-e)+e},randomInt:function(e,t){return typeof e=="undefined"&&(e=0),typeof t=="undefined"&&(t=100),Math.floor(Math.random()*(t-e+1))+e}},hasTouch:function(){try{return document.createEvent("TouchEvent"),!0}catch(e){return!1}}()};typeof require=="undefined"?(window._g||(window._g={}),window._g=$.extend(!0,{},window._g,e),e=undefined):define("_g/base",["jquery","backbone"],function(){return window._g||(window._g={}),window._g=$.extend(!0,{},window._g,e),e=undefined,window._g})}(window),define("interaction_view/model/cycleimage",["interaction_view/model/base","interaction_view/ui/animation","_g/base"],function(){interaction_view.model.CycleImage=interaction_view.model.Base.extend({defaults:{iType:"CycleImage",iLock:!0,iVisibility:!0,iCommon:{portait:{iStartx:400,iStarty:200,iWidth:200,iHeight:200},landscape:{iStartx:400,iStarty:200,iWidth:200,iHeight:200}},iDetail:{},iParent:"",iChild:"",iOptions:{createfocus:!0},iParentModel:null,iDraggable:!0,iResizable:!0,iTemplate:null,iParentdiv:".interaction-view",iAutoindex:!1,iSync:!1,iZindex:"-1",iUrl:null,iAutofocus:!1,iKeyscontrol:!0,callback:null,iBackground:"rgba(62,189,255,0.5)",iResourcesProperties:[{id:"iImg",type:"single"}],iAnimationProperties:[{id:"iAnimation",type:"object"}]},setcollection:function(){iOverlaylist.get(this.id)||iOverlaylist.add(this)},setview:function(e){this.iview=new interaction_view.view.CycleImage({model:this})},setsyncmodel:function(){}}),interaction_view.view.CycleImage=interaction_view.view.Base.extend({events:{},render:function(e){var t=this,n=this.getdetail();this.currentSlideIndex=null,this.model.on("slideTo",function(e){if(t.currentSlideIndex!=null&&t.currentSlideIndex==e)return!1;t.preloaded&&(interaction_view.events.onChangeTo(t.model.get("pageid"),t.model.id,e),t.currentSlideIndex=e)})},preload:function(){var e=this;this.preloaded=!1;var t,n=this.getdetail();this.checkImglist=_.pluck(n.iImg,"picture"),n.iImg&&_.each(n.iImg,function(n){_g.getUrlParameterByName("-playmode")=="1"?t=n.thumbnail:t=n.picture,e.sendToPreload({file:t})})},checkImgload:function(e){return this.checkImglist=_.reject(this.checkImglist,function(t){return t==e}),this.checkImglist.length==0?!0:!1},afterpreload:function(e){if(e&&this.preloaded)return;e&&(this.preloaded=this.checkImgload(e)),this.preloaded&&(this.playAnimation(),this.setZindex(),this.setElementDisplay(),this.copyelstyle=this.$el.attr("style"),this.copyelementstyle=this.$el.children(".iElement").attr("style"))},playAnimation:function(){var e=this,t=0,n=this.getdetail(),r=n.iSlidetype;r==null&&(r=0),this.delay=Number(n.iInterval)||.01,this.autoplay=n.iAutoplay;var i=n.iRepeat?-1:0;this.slideel=e.$el.children(".Element").find(".slidecontent").first(),this.slidelength=n.iImg.length,this.repeat=i,this.iRewind=n.iRewind,this.slipable=n.iSlipable,this.timeline=new TimelineMax({paused:!0,repeat:i,onComplete:this.setRewind()}),this.setTimeline(),this.autoplay?this.timeline.play(0):this.setSlideDisplay(0),this.onChangeSlideTo(0),this.slipable&&(this.control(),this.autoplay||this.$el.attr("data-iSlipable",!0))},setTimeline:function(){this.setLoopSwitch(),this.slideel.children().first().css({opacity:1,left:0,top:0}).nextAll().css("opacity",0)},testControl:function(){return!0},resetOtherStatus:function(){if(!this.slideel)return;this.slideel.children().first().css({opacity:1,left:0,top:0});var e=this.getdetail();this.autoplay=e.iAutoplay,this.currentIndex=0,this.timeline&&(this.timeline.pause(1e-5),this.autoplay?this.timeline.play(0):this.setSlideDisplay(0))}})}),define("interaction_view/model/image",["interaction_view/model/base"],function(){interaction_view.model.Image=interaction_view.model.Base.extend({defaults:{iType:"Image",iLock:!0,iVisibility:!0,iCommon:{portait:{iStartx:400,iStarty:200,iWidth:200,iHeight:200},landscape:{iStartx:400,iStarty:200,iWidth:200,iHeight:200}},iDetail:{iAdapt:!1,iFullview:!1,iImg:null,iAnimation:[]},iParent:"",iChild:"",iOptions:{createfocus:!0},iParentModel:null,iDraggable:!0,iResizable:!0,iTemplate:null,iParentdiv:".interaction-view",iAutoindex:!1,iSync:!1,iZindex:"-1",iUrl:null,iAutofocus:!1,iKeyscontrol:!0,callback:null},setcollection:function(){iOverlaylist.get(this.id)||iOverlaylist.add(this)},setview:function(e){this.iview=new interaction_view.view.Image({model:this})},setsyncmodel:function(){}}),interaction_view.view.Image=interaction_view.view.Base.extend({events:{},render:function(e){},preload:function(){var e=this.getdetail(),t;e.iImg&&e.iImg[0]&&(_g.getUrlParameterByName("-playmode")=="1"?t=e.iImg[0].thumbnail:t=e.iImg[0].picture,this.sendToPreload({file:t}))}})}),function(){var e={log:function(e){console.log(e)},serverError:function(){$(document).trigger("serverError")}};typeof require=="undefined"?(window._g||(window._g={}),window._g.error=e):define("_g/error",["_g/base"],function(){return window._g.error=e,window._g.error})}(window),function(){var e={buttonGroupT:['<div class="_g_btn_group <%=opts.className||""%>">',"</div>"].join(""),buttonT:' <button class="btn _g_btn _g_btn_confirm <%=opts.className||""%>" type="button" data-name="<%=opts.name%>"><%=opts.name%></button>',buttonGroupList:[],scale:function(e,t){$(e).css("zoom",t).css("-moz-transform","scale("+t+")").css("-o-transform","scale("+t+")")},center:function(e){var t={containment:null,Item:null};typeof e=="string"?e={containments:null,Item:e}:e=e?$.extend({},t,e):t;if(!e.Item)return!1;$(e.Item).css({left:"50%",top:"50%","margin-top":function(){return-($(this).height()/2)},"margin-left":function(){return-($(this).width()/2)}})},centerImage:function(e){var t={containment:null,Item:null,parentWidth:null,parentHeight:null,width:null,height:null,setParent:!0};e=e?$.extend({},t,e):t;if(!e.Item||!e.containment)return!1;var n=0,r=0;return e.setParent&&$(e.containment).css({"line-height":e.parentHeight+"px","text-align":"center"}),e.width/e.height>=e.parentWidth/e.parentHeight?($(e.Item).css({width:"100%",height:"auto","verticle-align":"middle"}),r=e.parentWidth,height=e.parentWidth/(e.width/e.height)):($(e.Item).css({width:"auto",height:"100%","verticle-align":"middle"}),height=e.parentHeight,r=e.parentHeight*(e.width/e.height)),{width:r,height:height}},opacity:function(e,t){},addShade:function(e){var t={name:"_g_shadow",zindex:99999,color:"#000000",opacity:.8,containment:"body"};e=e?$.extend({},t,e):t,$(containment).append('<div id="'+e.name+'" style="z-index:'+e.zindex+";background:"+e.color+";opacity:"+e.opacity+';"></div>')},addButtonGroup:function(e){var t={containment:null,position:0,name:"_g_button"+_g.uuid(),className:null,confirmButton:{name:"确认",enable:!0,className:"btn-small btn-primary",onClick:null},cancelButton:{name:"取消",enable:!0,className:"btn-small",onClick:null},remove:function(){e.$el&&e.$el.remove()},getButton:function(t){return e.$el.find('[data-name="'+t+'"]')},addButton:function(t){var n={name:null,className:null,onClick:null};t=t?$.extend(!0,{},n,t):n;if(!t.name)return!1;e.$el.append(_.template(_g.ui.buttonT,{opts:t})),t.onClick&&e.getButton(t.name).on("click",function(){t.onClick()})},removeButton:function(t){if(!t)return;e.$el.find('[data-name="'+t+'"]').remove()}};return e=e?$.extend(!0,{},t,e):$.extend(!0,{},t),e.containment?(e.position==0?($(e.containment).append(_.template(_g.ui.buttonGroupT,{opts:e})),e.$el=$(e.containment).children("._g_btn_group")):($(_.template(_g.ui.buttonGroupT,{opts:e})).insertAfter($(e.containment)),e.$el=$(e.containment).next("._g_btn_group")),e.confirmButton.enable&&e.addButton(e.confirmButton),e.cancelButton.enable&&e.addButton(e.cancelButton),e):!1},contenteditable:function(e){var t={eventType:0,mutiple:0,element:null,callback:null,type:0,enableControl:!1};e=e?$.extend(!0,{},t,e):$.extend(!0,{},t),e.onKeyDown=function(t,n){var r=t.keyCode?t.keyCode:t.which;r==13&&e.mutiple==0&&(e.enableClose=!0,e.$this.blur(),$(document).off("keydown",e.onKeyDown),e.result())},e.result=function(){if(e.$this.data("before")!==e.$this.html()){e.$this.data("before",e.$this.html());var t=e.type==0?e.$this.text():e.$this.html();e.callback&&e.callback(t)}},e.enableEdit=!1;if(!e.element)return!1;e.element&&(e.$this=$(e.element),e.$this.addClass("_g_contenteditable"),e.eventType==0&&$(e.element).attr("contenteditable","true"),e.eventType==1&&($(e.element).attr("contenteditable","false"),$(e.element).on("dblclick",function(){$(this).attr("contenteditable","true"),$(this).focus()})),$(e.element).on("focus",function(){return e.focus?!1:(e.focus=!0,e.$this.data("before",e.$this.html()),$(document).on("keydown",e.onKeyDown),e.enableControl&&(e.buttonGroup=_g.ui.addButtonGroup({containment:e.$this,position:1,confirmButton:{onClick:function(){e.enableClose=!0,e.$this.blur()}},cancelButton:{onClick:function(){e.enableClose=!0,e.$this.html(e.$this.data("before")),e.$this.blur()}}})),e.$this)}).on("blur",function(t){if(e.enableControl){if(!e.enableClose)return e.$this.focus(),!1;e.enableClose=!1,e.buttonGroup.remove()}return e.focus=!1,$(document).off("keydown",e.onKeyDown),e.eventType==1&&$(e.element).attr("contenteditable","false"),e.result(),!1}))},sortByIds:function(e){var t={containment:null,item:"li",ids:null};e=e?$.extend({},t,e):t;if(!e.containment||!e.ids)return;_.each(e.ids,function(t){if($(e.containment).children(e.item+'[id="'+t+'"]').length>0){var n=$(e.containment).children(e.item+'[id="'+t+'"]').detach();$(e.containment).append(n)}})},findById:function(e){var t={containment:null,id:null};return e=e?$.extend({},t,e):t,!e.containment||!e.id?[]:$(e.containment).find('[id="'+e.id+'"],[data-id="'+e.id+'"]').first()},moveTo:function(e){var t={containment:null,sourceId:null,targetId:null,wrap:null,wrapClass:null,position:0};e=e?$.extend({},t,e):t;if(!e.containment)return!1;var n=_g.ui.findById({containment:e.containment,id:e.sourceId}),r=_g.ui.findById({containment:e.containment,id:e.targetId});e.wrap&&(r.has(e.wrap).length==0?(r.append(document.createElement(e.wrap)),r=r.children(e.wrap),e.wrapClass&&r.addClass(e.wrapClass)):r=r.children(e.wrap));var i=n.detach();e.position==0?r.prepend(i):r.append(i)},getTreeIds:function(e){var t={containment:null,item:null,idAttribute:"id",wrap:"ul"};e=e?$.extend({},t,e):t;var n=[];if(!e.containment||!e.item)return!1;if(e.wrap&&!$(e.containment).is(e.wrap)){if(!($(e.containment).children("ul").length>0))return[];e.containment=$(e.containment).children("ul")}return $(e.containment).children(e.item).each(function(){var t={};t.id=$(this).attr(e.idAttribute),t.children=_g.ui.getTreeIds({containment:$(this),item:e.item,idAttribute:e.idAttribute,wrap:e.wrap}),n.push(t)}),n},dialog:function(e){var t={className:null}},createDomMask:function(e){var t={containment:null,item:null,x:null,y:null,height:null,width:null,moveTo:function(t){e.offsetX=0-t.x,e.offsetY=0-t.y,$(e.item).css("left",e.offsetX),$(e.item).css("top",e.offsetY)},resize:function(t){$(e.containment).width(t.w),$(e.containment).height(t.h)}};return e=e?$.extend({},t,e):t,!e.containment||!e.item?!1:($(e.containment).css("overflow","hidden"),e.moveTo({x:e.x,y:e.y}),e.resize({w:e.width,h:e.height}),e)},clearSelection:function(){if(document.selection&&document.selection.empty)document.selection.empty();else if(window.getSelection){var e=window.getSelection();e.removeAllRanges()}}};typeof require=="undefined"?(window._g||(window._g={}),window._g.ui=e):define("_g/ui",["jquery","_g/base","_g/error"],function(){return window._g.ui=e,window._g.ui})}(window),function(){var e={getValueByType:function(e,t){t=t?t.toLowerCase():t;switch(t){case"number":return Number(e);case"boolean":if(e=="false")return!1;if(e=="true")return!0;return Boolean(e);case"string":return String(e);case"object":return _g.object.jsonparse(e);default:return e}},bindFormChange:function(e){var t={containment:null,$item:null,callback:null};e=e?$.extend(!0,{},t,e):t;if(!e.containment)return!1;var n=e.$item?e.$item:"input,textarea,select";$(e.containment).find(n).on("change",function(){e.callback&&e.callback($(this),e)})},serializeValue:function(e){var t={containment:null,typeAttr:"data-type",attrAttr:"data-attr",allowEmpty:!0};e=e?$.extend({},t,e):t;if(!e.containment)return!1;var n=e.containment,r={},i=function(t,n){if(t.attr("disabled")=="disabled")return;var i=t.attr("name")||$(this).attr("id"),s=t.attr(e.typeAttr),o=t.attr(e.attrAttr);if(!i)return;o?(r[o]||(r[o]={}),r[o][i]=n):r[i]=n};return $(n).find('input[type="text"],input[type="hidden"],textarea').each(function(){var t=$(this).attr("name")||$(this).attr("id"),n=$(this).attr(e.typeAttr),r=$(this).attr(e.attrAttr),s=_g.util.getValueByType($(this).val(),n);i($(this),s)}),$(n).find('input[type="checkbox"]').each(function(){var t=$(this).attr("name")||$(this).attr("id"),n=$(this).attr(e.typeAttr),s=$(this).attr(e.attrAttr),o=s?r[s][t]?r[s][t]:[]:r[t]?r[t]:[];$(this).attr("checked")=="checked"?n=="boolean"?o=!0:o.push(_g.util.getValueByType($(this).val(),n)):$(this).attr("data-type")=="boolean"&&(o=!1),i($(this),o)}),$(n).find('input[type="radio"]:checked').each(function(){var t=$(this).attr("name")||$(this).attr("id"),n=$(this).attr(e.typeAttr),r=$(this).attr(e.attrAttr),s=_g.util.getValueByType($(this).val(),n);i($(this),s)}),$(n).find("select").each(function(){var t=$(this).attr("name")||$(this).attr("id"),n=$(this).attr(e.typeAttr),s=$(this).attr(e.attrAttr),o=Boolean($(this).attr("data-mutiple")),u;o?(u=s?r[s][t]?r[s][t]:[]:r[t]?r[t]:[],u.push($(this).val())):u=_g.util.getValueByType($(this).val(),n),i($(this),u)}),r},disableLink:function(e){var t={containment:null,linkitem:"a",enabled:!0};return e=e?$.extend(!0,{},t,e):t,e.containment?(e.func=function(){return!1},e.enable=function(){$(e.containment).find(e.linkitem).each(function(){$(this).on("click",e.func),e.enabled=!0})},e.disable=function(){$(e.containment).find(e.linkitem).each(function(){$(this).off("click",e.func),e.enabled=!1})},e.enable(),e):!1},domExist:function(e){return typeof e=="string"&&(e=$(e)),jQuery.contains(document.documentElement,e[0])}};typeof require=="undefined"?(window._g||(window._g={}),window._g.util=e,e=undefined):define("_g/util",["jquery","_g/base"],function(){return window._g.util=e,e=undefined,window._g.util})}(window),function(){var _g_mvc={_loadTemplate:function(e,t){},_CollectionforSaveAll:function(){var e=Backbone.Model.extend({initialize:function(){this.set("id","GlobalSave")},sync:function(e,t,n){var r=this.data;this.attributes=r;if(e=="create")return;e=="update"&&(n.url=this.url);if(e=="delete")return;if(e=="read")return;Backbone.emulateHTTP=!0,Backbone.emulateJSON=!0,Backbone.sync(e,t,n)}});return new e},createModel:function(opts){var defaults={defaults:{},autoIndex:!0,autoUpdate:!0,enableSync:!0,createUrl:null,updateUrl:null,removeUrl:null,fetchUrl:null,staticFetchUrl:null,staticRemoveUrl:null,staticCreateUrl:null,staticUpdateUrl:null,debug:!1,bindRemove:!0,bindChange:null,callback:null,initView:null,initialize:function(){this.iViewlist=[],this.iCollectionlist=[];if(!this.get("id")){this.set("isNew",!0);if(this.autoIndex){var prefix=this.get("type")||this.get("iType")||"M";this.set("id",prefix+"_"+_g.uuid()),this.preset()}else this.save({},{wait:!0,success:function(model,response){var returned=eval(response);(returned.Status=="Success"||returned.code==200)&&model.set("id",returned.ID.toString()),model.preset()}})}else this.preset()},sync:function(e,t,n){var r,i=typeof _gDebug!="undefined"&&_gDebug||this.debug;if(!this.enableSync)return!1;if(e=="create"){r=i?this.staticCreateUrl?this.staticCreateUrl:this.createUrl:this.createUrl;if(!r)return;n.url=r}if(e=="update"||e=="patch"){r=i?this.staticUpdateUrl?this.staticUpdateUrl:this.updateUrl:this.updateUrl;if(!r)return;n.url=r}if(e=="delete"){r=i?this.staticRemoveUrl?this.staticRemoveUrl:this.removeUrl:this.removeUrl;if(!r)return;n.url=r}if(e=="read"){r=i?this.staticFetchUrl?this.staticFetchUrl:this.fetchUrl:this.fetchUrl;if(!r)return;n.url=r}n.url=typeof n.url=="string"?n.url:n.url(t.attributes),Backbone.emulateHTTP=!0,Backbone.emulateJSON=!0,Backbone.sync(e,t,n)},addView:function(e,t){typeof t=="function"&&(this[e]=new t({model:this}));if(typeof t=="object"){var n=_g.mvc.createView(t);this[e]=new n({model:this})}this[e]&&this.iViewlist.push(this[e])},addCollection:function(e,t){typeof t=="function"&&(this[e]=new t);if(typeof view=="object"){var n=_g.mvc.createCollection(t);this[e]=new n}this[e]&&this.iCollectionlist.push(this[e])},preset:function(){this.callback&&this.callback(this);var e=this;this.autoUpdate&&this.on("change",function(){e.updateAllViews()}),this.bindRemove&&this.on("destroy",function(){e.removeAllViews()}),this.bindchange&&this.bindchange(),this.initView&&this.addView("iview",this.initView)},updateAllViews:function(){_.each(this.iViewlist,function(e){e.$el&&e.update()})},removeView:function(e){this[e]&&(this[e].$el.remove(),this.iViewlist=_.reject(this.iViewlist,function(t){return t==this[e]}),this[e]=null)},removeAllViews:function(){_.each(this.iViewlist,function(e){e.$el&&e.$el.remove()})}};opts=opts?$.extend(!0,{},defaults,opts):defaults;var Model=Backbone.Model.extend(opts);return Model},createView:function(e){var t={template:null,className:null,containment:null,wrap:null,wrapClassName:null,autoRender:!0,position:1,parseData:null,callback:null,bindChange:null,parseTemplate:null,initialize:function(){_.bindAll(this),this.autoRender&&this.render(),this.callback&&this.callback(this)},createEl:function(){var e=this.model.toJSON(),t;this.parseData&&(e=this.parseData()),this.parseTemplate?t=this.parseTemplate(this.template):t=_g.parseTemplate(this.template);var n=t(e);return n},render:function(e){var t=this;if(!this.model||!this.template||!this.containment)return!1;var n=$(this.containment);this.wrap&&!$(this.containment).is(this.wrap)&&($(this.containment).children(this.wrap).length==0&&$(this.containment).append(document.createElement(this.wrap)),n=$(this.containment).children(this.wrap),this.containment&&this.wrapClassName&&n.addClass(this.wrapClassName));var r=this.createEl();this.position==1?n.append(r):n.prepend(r);var i=_g.ui.findById({containment:n,id:t.model.id});return i.length>0&&(this.setElement(i),this.className&&this.$el.addClass(this.className)),this},update:function(e){if(!this.model||!this.template||!this.containment)return!1;if(!_g.util.domExist(this.$el))this.render();else{var t=this.createEl();this.$el.replaceWith(t);var n=_g.ui.findById({containment:this.containment,id:this.model.id});n.length>0&&(this.setElement(n),this.className&&this.$el.addClass(this.className))}e&&e(this),this.afterUpdate&&this.afterUpdate(this)},events:{}};e=e?$.extend(!0,{},t,e):t;var n=Backbone.View.extend(e);return n},createCollection:function(e){var t={enableSync:!1,fetchUrl:null,staticFetchUrl:null,saveUrl:null,staticSaveUrl:null,debug:!1,bindRemove:!1,bindReset:!0,bindAdd:null,callback:null,initialize:function(){var e=this;this.bindRemove&&this.on("remove",function(t){typeof e.bindRemove=="function"?e.bindRemove(t):t.removeAllViews()}),this.bindReset&&this.on("reset",function(t,n){typeof e.bindReset=="function"?e.bindReset(t,n):_.each(n.previousModels,function(e){e.removeAllViews()})}),this.bindAdd&&this.on("add",function(t){e.bindAdd()}),this.callback&&this.callback(this)},sortByIds:function(e){var t=this;this.reset(_.map(e,function(e){return t.get(e)}),{silent:!0})},sync:function(e,t,n){var r=typeof _gDebug!="undefined"&&_gDebug||this.debug;if(!this.enableSync)return!1;if(e=="read"){var i=r?this.staticFetchUrl?this.staticFetchUrl:this.fetchUrl:this.fetchUrl;if(!i)return;n.url=i}if(!n.url)return!1;n.url=typeof n.url=="string"?n.url:n.url(t.toJSON()),Backbone.emulateHTTP=!0,Backbone.emulateJSON=!0,Backbone.sync(e,t,n)},saveAll:function(e){var t=typeof _gDebug!="undefined"&&_gDebug||this.debug,n=t?this.staticSaveUrl?this.staticSaveUrl:this.saveUrl:this.saveUrl;if(!n)return!1;var r=_g.mvc._CollectionforSaveAll();r.data=this.toJSON(),r.url=n,r.save({},{wait:!0,success:function(t,n){e&&e(n)},error:function(){}})},refreshView:function(e){var t={containment:null};e=e?$.extend({},t,e):t,this.length>0&&(_.each(this.at(0).iViewlist,function(t){containment=e.containment||t.containment,containment&&(t.wrap&&!$(containment).is(t.wrap)?$(containment).children(t.wrap).empty():$(containment).empty())}),this.each(function(t){e.containment&&(t.iview.containment=e.containment),t.iview.update()}))}};e=e?$.extend(!0,{},t,e):t;var n=Backbone.Collection.extend(e);return n},createTreeByData:function(e){var t={collection:null,data:null,treeLevel:0,parent:null},n=e.parent,r;e=e?$.extend(!0,{},t,e):t,e.parent=n;if(!e.collection||!e.data)return null;var i=$.extend(!0,{},e.data);if(typeof e.collection=="function")r=new e.collection;else{var s=_g.mvc.createCollection(e.collection);r=new s}return r.parent=n,r.refreshTreeView=function(e){this.refreshView(e),this.each(function(e){e.icollection.refreshTreeView({containment:e.iview.$el})})},r.getModels=function(){var e=_g.mvc.getTreeModels(r);return e},r.getModelsJSON=function(){var e=r.getModels();return e=_.map(e,function(e){return e.toJSON()}),e},r.getModel=function(e){return _g.mvc.getTreeModel(r,e)},r.on("add",function(t){t.treeLevel=e.treeLevel,t.icollection=_g.mvc.createTreeByData({collection:e.collection,data:[],treeLevel:e.treeLevel+1}),r.parent&&(r.View=typeof r.View=="object"?$.extend(!0,{},r.View,{containment:r.parent.iview.$el}):r.View.extend({containment:r.parent.iview.$el})),t.addView("iview",r.View),_g.ui.sortByIds({containment:t.iview.wrap?t.iview.$el.parent(t.iview.wrap):t.iview.$el.parent(),ids:r.pluck("id")}),t.icollection.parent=t,t.icollection.View=r.View}),r.saveAll=function(e){var t=typeof _gDebug!="undefined"&&_gDebug||this.debug,n=t?this.staticSaveUrl?this.staticSaveUrl:this.saveUrl:this.saveUrl;if(!n)return!1;var r=_g.mvc._CollectionforSaveAll();r.data=_g.mvc.getTreeData(this),r.url=n,r.save({},{wait:!0,success:function(t,n){e&&e(n)},error:function(){}})},_.each(i,function(t){var n;t.children?n=$.extend(!0,{},t.children):n=[],delete t.children,r.add(t,{silent:!0});var i=r.at(r.length-1);i.treeLevel=e.treeLevel,n&&(i.icollection=_g.mvc.createTreeByData({collection:e.collection,data:n,treeLevel:e.treeLevel+1,parent:i}))}),r},createTreeView:function(e){var t={collection:null,view:null,containment:null,wrap:null,wrapClassName:null,template:null,className:null,parseTemplate:null,update:function(e){if(!this.model||!this.template||!this.containment)return!1;if(!_g.util.domExist(this.$el))this.render();else{var t=this.createEl(),n=null;this.wrap&&(n=this.$el.children(this.wrap).detach()),this.$el.replaceWith(t);var r=_g.ui.findById({containment:this.containment,id:this.model.id});r.length>0&&(this.setElement(r),this.className&&this.$el.addClass(this.className),n&&this.$el.append(n))}e&&e(this),this.afterUpdate&&this.afterUpdate(this)}},n=e.collection;e=e?$.extend(!0,{},t,e):t;var r={};e.collection=n;if(!e.collection||!e.view)return!1;e.containment&&(r.containment=e.containment),e.wrap&&(r.wrap=e.wrap),e.template&&(r.template=e.template),e.parseTemplate&&(r.parseTemplate=e.parseTemplate),e.parseData&&(r.parseData=e.parseData),e.callback&&(r.callback=e.callback),e.wrapClassName&&(r.wrapClassName=e.wrapClassName),e.className&&(r.className=e.className),r.update=e.update;var i=typeof e.view=="function"?e.view.extend(r):$.extend(!0,e.view,r);e.collection.View=i,e.collection.each(function(t){t.addView("iview",i);if(t.icollection){typeof e.containment!="string"&&(e.containment=e.containment.selector);var n=e.containment+(e.wrap?" >"+e.wrap:"")+' >[id="'+t.id+'"]';_g.mvc.createTreeView({collection:t.icollection,view:e.view,containment:n,wrap:e.wrap||null,template:e.template||null})}})},sortTreeByIds:function(e){var t=function(n,r,s){return n?(n.reset([],{silent:e.silent}),_.each(r,function(r){r.children=r.children||[];var o=i.get(r.id);o.treeLevel=s,o.icollection=t(o.icollection,r.children,s+1),n.add(o,{silent:e.silent}),o.collection=n}),n):null},n={collection:null,ids:null,treeLevel:0,silent:!0},r=e.collection;e=e?$.extend(!0,{},n,e):n,e.collection=r;if(!e.collection||!e.ids)return!1;var i=new Backbone.Collection;i.add(_g.mvc.getTreeModels(e.collection));var s=t(e.collection,e.ids,e.treeLevel);return s},getTreeModels:function(e){var t=[];return e.each(function(e){t.push(e);if(e.icollection){var n=_g.mvc.getTreeModels(e.icollection);_.each(n,function(e){t.push(e)})}}),t},getTreeModel:function(e,t){if(!e||!t)return!1;var n=_g.mvc.getTreeModels(e);return _.find(n,function(e){return e.id==t})},getTreeData:function(e){var t=[];return e.each(function(e){var n=$.extend(!0,{},e.toJSON());e.icollection&&(n.children=_g.mvc.getTreeData(e.icollection)),t.push(n)}),t}};typeof require=="undefined"?(window._g||(window._g={}),window._g.mvc=_g_mvc,_g_mvc=undefined):define("_g/mvc",["jquery","backbone","_g/base","_g/ui","_g/util"],function(){return window._g.mvc=_g_mvc,_g_mvc=undefined,window._g.mvc})}(window),define("text!interaction_view/template/page.js",[],function(){return'<section class="Presentation" id="<%=id%>">\n <div class="animationbk" style="text-align:center;position:absolute;width:100%;height:100%;background-color:<%=bg_color%>;opacity:<%=bg_opacity%>">\n <% if(typeof picture!="undefined"&&picture){ %>\n <img src="<%=picture%>" style="vertical-align: middle;<%=(width/height>=interaction_view.size.x/interaction_view.size.y)?"width:100%;":""%> <%=(width/height<interaction_view.size.x/interaction_view.size.y)?"height:100%;":""%>">\n <% } %>\n </div>\n <div class="interaction-area typo">\n <div class="interaction-view"></div>\n </div>\n</section>'}),define("text!interaction_view/template/pagegroup.js",[],function(){return'<section class="group" id="<%=id%>" data-transition="zoom" data-transition-speed="fast"></section>'}),define("interaction_view/view/page",["_g/mvc","text!interaction_view/template/page.js","text!interaction_view/template/pagegroup.js"],function(){var e={template:require("text!interaction_view/template/page.js"),className:null,containment:"div.slides",wrap:null,wrapClassName:null,autoRender:!0,position:1,parseData:null,callback:function(){this.model.get("type")!="page_group"&&(this.overlays=$.extend(!0,{},this.model.get("overlays")),this.animations=$.extend(!0,{},this.model.get("animations")),this.actions=$.extend(!0,{},this.model.get("actions")))},bindChange:null,parseTemplate:function(){var e=this.model.get("type");return e=="page_group"?_g.parseTemplate(require("text!interaction_view/template/pagegroup.js")):_g.parseTemplate(require("text!interaction_view/template/page.js"))},afterload:function(){var e=this;e.animations=_.map(e.animations,function(t){return t.pageid=e.model.id,t}),e.model.iAnimationlist.reset(e.animations),overlays=_.filter(e.overlays,function(t){return t.pageid=e.model.id,interaction_view.model[t.iType]}),overlays=_.map(overlays,function(e){return new interaction_view.model[e.iType](e)}),e.model.iOverlaylist.reset(overlays),e.model.iOverlaylist.each(function(e){e.iview.setZindex()}),e.actions=_.map(e.actions,function(t){return t.pageid=e.model.id,t}),e.model.iActionlist.reset(e.actions),e.startLoad()},startLoad:function(){var e=this;this.model.ipreloadlist.length==0?interaction_view.finishPagePreload(this.model.id):this.model.ipreloadlist.preload()},afterpreload:function(){this.model.iOverlaylist.each(function(e){e.iview.preloaded||e.iview.afterpreload()}),this.model.iActionlist.each(function(e){e.iview.render()})}};return e}),define("interaction_view/model/page",["_g/mvc","interaction_view/view/page"],function(){var e={defaults:{iType:"Page",position:0,description:"",title:"untitled",picture:null,preview:'<img src="/staticfs/admin-epub360/img/thumb.png">',thumbnail:null,width:null,height:null,bg_color:"#FFFFFF",bg_opacity:1,show_master:!0},autoIndex:!0,callback:function(){this.get("type")!="page_group"&&(this.iOverlaylist=new interaction_view.collection.list,this.iAnimationlist=new interaction_view.collection.Animation,this.iActionlist=new interaction_view.collection.Action,this.ipreloadlist=new interaction_view.collection.Preload,this.ipreloadlist.pageid=this.iOverlaylist.pageid=this.iAnimationlist.pageid=this.iActionlist.pageid=this.id)},overlays:[],actions:[],animations:[]};return _g.mvc.createModel(e)}),define("interaction_view/collection/page",["_g/mvc","interaction_view/model/page"],function(){var e={enableSync:!1,model:require("interaction_view/model/page"),getPages:function(){var e=_g.mvc.getTreeModels(interaction_view.ipagelist);return e=_.reject(e,function(e){return e.toJSON().type=="page_group"}),e},getPagesJSON:function(){var e=_g.mvc.getTreeModels(interaction_view.ipagelist);return e=_.reject(e,function(e){return e.toJSON().type=="page_group"}),e=_.map(e,function(e){return e.toJSON()}),e},getPage:function(e){return _g.mvc.getTreeModel(interaction_view.ipagelist,e)}};return _g.mvc.createCollection(e)}),define("interaction_view/model/layer",["interaction_view/model/page"],function(){var e=require("interaction_view/model/page"),t=e.extend({defaults:{iType:"Layer",position:0,description:"",title:"untitled",picture:null,preview:'<img src="/staticfs/admin-epub360/img/thumb.png">',thumbnail:null,width:null,height:null,layer_width:1024,layer_height:768,bg_color:"#FFFFFF",bg_opacity:1},callback:function(){this.actions=this.get("actions"),this.animations=this.get("animations"),this.overlays=this.get("overlays")}});return t}),define("interaction_view/collection/layer",["interaction_view/collection/page","interaction_view/model/layer"],function(){var e=require("interaction_view/collection/page"),t=e.extend({model:require("interaction_view/model/layer")});return t}),define("interaction_view/model/master",["interaction_view/model/page"],function(){var e=require("interaction_view/model/page"),t=e.extend({defaults:{iType:"Master",position:0,description:"",title:"untitled",picture:null,preview:'<img src="/staticfs/admin-epub360/img/thumb.png">',thumbnail:null,width:null,height:null,bg_color:"#FFFFFF",bg_opacity:1},callback:function(){this.iOverlaylist=new interaction_view.collection.list,this.iAnimationlist=new interaction_view.collection.Animation,this.iActionlist=new interaction_view.collection.Action,this.ipreloadlist=new interaction_view.collection.Preload,this.ipreloadlist.pageid=this.iOverlaylist.pageid=this.iAnimationlist.pageid=this.iActionlist.pageid=this.id}});return t}),define("interaction_view/view/master",["interaction_view/view/page"],function(){var e=require("interaction_view/view/page"),t=$.extend({},e,{template:null,className:null,containment:null,wrap:null,wrapClassName:null,autoRender:!1,position:1,parseData:null,afterload:function(){var e=this,t=this.model;if(!t)return;e.animations=_.map(e.animations,function(t){return t.pageid=e.model.id,t.pagetype="master",t}),e.model.iAnimationlist.reset(e.animations),overlays=_.filter(e.overlays,function(t){return t.pageid=e.model.id,t.pagetype="master",interaction_view.model[t.iType]}),overlays=_.map(overlays,function(e){return new interaction_view.model[e.iType](e)}),e.model.iOverlaylist.reset(overlays),e.model.iOverlaylist.each(function(e){e.iview.setZindex()}),e.actions=_.map(e.actions,function(t){return t.pageid=e.model.id,t.pagetype="master",t}),e.model.iActionlist.reset(e.actions),e.startLoad()}});return t}),define("interaction_view/collection/master",["interaction_view/collection/page","interaction_view/model/master","interaction_view/view/master"],function(){var e=require("interaction_view/collection/page"),t=e.extend({model:require("interaction_view/model/master")});return t}),define("interaction_view/model/doc",["_g/mvc","interaction_view/collection/page","interaction_view/view/page","interaction_view/collection/layer","interaction_view/collection/master"],function(){var e={defaults:{id:"doc",play_mode:0},autoUpdate:!1,fetchUrl:context_url+"index.json",staticFetchUrl:"/staticfs/common/js/interaction_view/data/index.json",parse:function(e){var t=this;console.log("fetch data:"+e);if(e.code==200){if(e.data){interaction_view.size={x:e.data.width||1024,y:e.data.height||768};if(typeof adjust_screen!="undefined"){var n=get_window_size();window.screenScale=n.x/n.y>interaction_view.size.x/interaction_view.size.y?n.y/interaction_view.size.y:n.x/interaction_view.size.x,adjust_screen(),window.screenScale=null}return this.initMasters(e),this.initLayers(e),this.initPages(e),_.pick(e.data,"id","title","play_mode","width","height")}return{}}},parseOrgnization:function(e,t){var n=this,r=[];return _.each(e,function(e){if(e.type=="page_group"){var i=n.parseOrgnization(e.children,e.id);_.each(i,function(e){r.push(e)})}else e.children||(e.children=[]),e.children.unshift($.extend(!0,{},e)),e.children&&_.each(e.children,function(n){n.id==e.id&&(n.children=[]),n.group=t}),e.type="page_group",delete e.id,delete e.animations,delete e.overlays,delete e.actions,r.push(e)}),r},initMasters:function(e){var t=require("interaction_view/collection/master");e.data.masters||(e.data.masters=[]),interaction_view.imasterlist=_g.mvc.createTreeByData({collection:t,data:e.data.masters})},initLayers:function(e){var t=require("interaction_view/collection/layer");e.data.layers||(e.data.layers=[]),interaction_view.ilayerlist=_g.mvc.createTreeByData({collection:t,data:e.data.layers})},initPages:function(e){var t=this,n,r=require("interaction_view/collection/page");e.data.play_mode==0?n=e.data.chapter:(n=_g.array.maptree({treesource:e.data.organization.children,mapdata:e.data.chapter}),n=_.reject(n,function(e){return!e.children||e.children.length==0}),n=t.parseOrgnization(n)),interaction_view.ipagelist=_g.mvc.createTreeByData({collection:r,data:n}),_g.mvc.createTreeView({collection:interaction_view.ipagelist,view:require("interaction_view/view/page"),containment:"div.slides",wrap:null})},callback:function(){}};return _g.mvc.createModel(e)}),define("text!interaction_view/template/preload.js",[],function(){return'<img src="<%=file%>" width="1" height="1" id="<%=id%>"/>'});var mejs=mejs||{};mejs.version="2.13.1",mejs.meIndex=0,mejs.plugins={silverlight:[{version:[3,0],types:["video/mp4","video/m4v","video/mov","video/wmv","audio/wma","audio/m4a","audio/mp3","audio/wav","audio/mpeg"]}],flash:[{version:[9,0,124],types:["video/mp4","video/m4v","video/mov","video/flv","video/rtmp","video/x-flv","audio/flv","audio/x-flv","audio/mp3","audio/m4a","audio/mpeg","video/youtube","video/x-youtube"]}],youtube:[{version:null,types:["video/youtube","video/x-youtube","audio/youtube","audio/x-youtube"]}],vimeo:[{version:null,types:["video/vimeo","video/x-vimeo"]}]},mejs.Utility={encodeUrl:function(e){return encodeURIComponent(e)},escapeHTML:function(e){return e.toString().split("&").join("&amp;").split("<").join("&lt;").split('"').join("&quot;")},absolutizeUrl:function(e){var t=document.createElement("div");return t.innerHTML='<a href="'+this.escapeHTML(e)+'">x</a>',t.firstChild.href},getScriptPath:function(e){for(var t=0,n,r="",i="",s,o,u=document.getElementsByTagName("script"),a=u.length,f=e.length;t<a;t++){s=u[t].src,n=s.lastIndexOf("/"),n>-1?(o=s.substring(n+1),s=s.substring(0,n+1)):(o=s,s="");for(n=0;n<f;n++){i=e[n],i=o.indexOf(i);if(i>-1){r=s;break}}if(r!=="")break}return r},secondsToTimeCode:function(e,t,n,r){typeof n=="undefined"?n=!1:typeof r=="undefined"&&(r=25);var i=Math.floor(e/3600)%24,s=Math.floor(e/60)%60,o=Math.floor(e%60);return e=Math.floor((e%1*r).toFixed(3)),(t||i>0?(i<10?"0"+i:i)+":":"")+(s<10?"0"+s:s)+":"+(o<10?"0"+o:o)+(n?":"+(e<10?"0"+e:e):"")},timeCodeToSeconds:function(e,t,n,r){typeof n=="undefined"?n=!1:typeof r=="undefined"&&(r=25),e=e.split(":"),t=parseInt(e[0],10);var i=parseInt(e[1],10),s=parseInt(e[2],10),o=0,u=0;return n&&(o=parseInt(e[3])/r),u=t*3600+i*60+s+o},convertSMPTEtoSeconds:function(e){if(typeof e!="string")return!1;e=e.replace(",",".");var t=0,n=e.indexOf(".")!=-1?e.split(".")[1].length:0,r=1;e=e.split(":").reverse();for(var i=0;i<e.length;i++)r=1,i>0&&(r=Math.pow(60,i)),t+=Number(e[i])*r;return Number(t.toFixed(n))},removeSwf:function(e){var t=document.getElementById(e);t&&/object|embed/i.test(t.nodeName)&&(mejs.MediaFeatures.isIE?(t.style.display="none",function(){t.readyState==4?mejs.Utility.removeObjectInIE(e):setTimeout(arguments.callee,10)}()):t.parentNode.removeChild(t))},removeObjectInIE:function(e){if(e=document.getElementById(e)){for(var t in e)typeof e[t]=="function"&&(e[t]=null);e.parentNode.removeChild(e)}}},mejs.PluginDetector={hasPluginVersion:function(e,t){var n=this.plugins[e];return t[1]=t[1]||0,t[2]=t[2]||0,n[0]>t[0]||n[0]==t[0]&&n[1]>t[1]||n[0]==t[0]&&n[1]==t[1]&&n[2]>=t[2]?!0:!1},nav:window.navigator,ua:window.navigator.userAgent.toLowerCase(),plugins:[],addPlugin:function(e,t,n,r,i){this.plugins[e]=this.detectPlugin(t,n,r,i)},detectPlugin:function(e,t,n,r){var i=[0,0,0],s;if(typeof this.nav.plugins!="undefined"&&typeof this.nav.plugins[e]=="object"){if((n=this.nav.plugins[e].description)&&(typeof this.nav.mimeTypes=="undefined"||!this.nav.mimeTypes[t]||!!this.nav.mimeTypes[t].enabledPlugin)){i=n.replace(e,"").replace(/^\s+/,"").replace(/\sr/gi,".").split(".");for(e=0;e<i.length;e++)i[e]=parseInt(i[e].match(/\d+/),10)}}else if(typeof window.ActiveXObject!="undefined")try{if(s=new ActiveXObject(n))i=r(s)}catch(o){}return i}},mejs.PluginDetector.addPlugin("flash","Shockwave Flash","application/x-shockwave-flash","ShockwaveFlash.ShockwaveFlash",function(e){var t=[];if(e=e.GetVariable("$version"))e=e.split(" ")[1].split(","),t=[parseInt(e[0],10),parseInt(e[1],10),parseInt(e[2],10)];return t}),mejs.PluginDetector.addPlugin("silverlight","Silverlight Plug-In","application/x-silverlight-2","AgControl.AgControl",function(e){var t=[0,0,0,0],n=function(e,t,n,r){for(;e.isVersionSupported(t[0]+"."+t[1]+"."+t[2]+"."+t[3]);)t[n]+=r;t[n]-=r};return n(e,t,0,1),n(e,t,1,1),n(e,t,2,1e4),n(e,t,2,1e3),n(e,t,2,100),n(e,t,2,10),n(e,t,2,1),n(e,t,3,1),t}),mejs.MediaFeatures={init:function(){var e=this,t=document,n=mejs.PluginDetector.nav,r=mejs.PluginDetector.ua.toLowerCase(),i,s=["source","track","audio","video"];e.isiPad=r.match(/ipad/i)!==null,e.isiPhone=r.match(/iphone/i)!==null,e.isiOS=e.isiPhone||e.isiPad,e.isAndroid=r.match(/android/i)!==null,e.isBustedAndroid=r.match(/android 2\.[12]/)!==null,e.isBustedNativeHTTPS=location.protocol==="https:"&&(r.match(/android [12]\./)!==null||r.match(/macintosh.* version.* safari/)!==null),e.isIE=n.appName.toLowerCase().match(/trident/gi)!==null,e.isChrome=r.match(/chrome/gi)!==null,e.isFirefox=r.match(/firefox/gi)!==null,e.isWebkit=r.match(/webkit/gi)!==null,e.isGecko=r.match(/gecko/gi)!==null&&!e.isWebkit&&!e.isIE,e.isOpera=r.match(/opera/gi)!==null,e.hasTouch="ontouchstart"in window&&window.ontouchstart!=null,e.svg=!!document.createElementNS&&!!document.createElementNS("http://www.w3.org/2000/svg","svg").createSVGRect;for(n=0;n<s.length;n++)i=document.createElement(s[n]);e.supportsMediaTag=typeof i.canPlayType!="undefined"||e.isBustedAndroid;try{i.canPlayType("video/mp4")}catch(o){e.supportsMediaTag=!1}e.hasSemiNativeFullScreen=typeof i.webkitEnterFullscreen!="undefined",e.hasNativeFullscreen=typeof i.requestFullscreen!="undefined",e.hasWebkitNativeFullScreen=typeof i.webkitRequestFullScreen!="undefined",e.hasMozNativeFullScreen=typeof i.mozRequestFullScreen!="undefined",e.hasMsNativeFullScreen=typeof i.msRequestFullscreen!="undefined",e.hasTrueNativeFullScreen=e.hasWebkitNativeFullScreen||e.hasMozNativeFullScreen||e.hasMsNativeFullScreen,e.nativeFullScreenEnabled=e.hasTrueNativeFullScreen,e.hasMozNativeFullScreen?e.nativeFullScreenEnabled=document.mozFullScreenEnabled:e.hasMsNativeFullScreen&&(e.nativeFullScreenEnabled=document.msFullscreenEnabled),e.isChrome&&(e.hasSemiNativeFullScreen=!1),e.hasTrueNativeFullScreen&&(e.fullScreenEventName="",e.hasWebkitNativeFullScreen?e.fullScreenEventName="webkitfullscreenchange":e.hasMozNativeFullScreen?e.fullScreenEventName="mozfullscreenchange":e.hasMsNativeFullScreen&&(e.fullScreenEventName="MSFullscreenChange"),e.isFullScreen=function(){if(i.mozRequestFullScreen)return t.mozFullScreen;if(i.webkitRequestFullScreen)return t.webkitIsFullScreen;if(i.hasMsNativeFullScreen)return t.msFullscreenElement!==null},e.requestFullScreen=function(t){e.hasWebkitNativeFullScreen?t.webkitRequestFullScreen():e.hasMozNativeFullScreen?t.mozRequestFullScreen():e.hasMsNativeFullScreen&&t.msRequestFullscreen()},e.cancelFullScreen=function(){e.hasWebkitNativeFullScreen?document.webkitCancelFullScreen():e.hasMozNativeFullScreen?document.mozCancelFullScreen():e.hasMsNativeFullScreen&&document.msExitFullscreen()}),e.hasSemiNativeFullScreen&&r.match(/mac os x 10_5/i)&&(e.hasNativeFullScreen=!1,e.hasSemiNativeFullScreen=!1)}},mejs.MediaFeatures.init(),mejs.HtmlMediaElement={pluginType:"native",isFullScreen:!1,setCurrentTime:function(e){this.currentTime=e},setMuted:function(e){this.muted=e},setVolume:function(e){this.volume=e},stop:function(){this.pause()},setSrc:function(e){for(var t=this.getElementsByTagName("source");t.length>0;)this.removeChild(t[0]);if(typeof e=="string")this.src=e;else{var n;for(t=0;t<e.length;t++){n=e[t];if(this.canPlayType(n.type)){this.src=n.src;break}}}},setVideoSize:function(e,t){this.width=e,this.height=t}},mejs.PluginMediaElement=function(e,t,n){this.id=e,this.pluginType=t,this.src=n,this.events={},this.attributes={}},mejs.PluginMediaElement.prototype={pluginElement:null,pluginType:"",isFullScreen:!1,playbackRate:-1,defaultPlaybackRate:-1,seekable:[],played:[],paused:!0,ended:!1,seeking:!1,duration:0,error:null,tagName:"",muted:!1,volume:1,currentTime:0,play:function(){this.pluginApi!=null&&(this.pluginType=="youtube"?this.pluginApi.playVideo():this.pluginApi.playMedia(),this.paused=!1)},load:function(){this.pluginApi!=null&&(this.pluginType!="youtube"&&this.pluginApi.loadMedia(),this.paused=!1)},pause:function(){this.pluginApi!=null&&(this.pluginType=="youtube"?this.pluginApi.pauseVideo():this.pluginApi.pauseMedia(),this.paused=!0)},stop:function(){this.pluginApi!=null&&(this.pluginType=="youtube"?this.pluginApi.stopVideo():this.pluginApi.stopMedia(),this.paused=!0)},canPlayType:function(e){var t,n,r,i=mejs.plugins[this.pluginType];for(t=0;t<i.length;t++){r=i[t];if(mejs.PluginDetector.hasPluginVersion(this.pluginType,r.version))for(n=0;n<r.types.length;n++)if(e==r.types[n])return"probably"}return""},positionFullscreenButton:function(e,t,n){this.pluginApi!=null&&this.pluginApi.positionFullscreenButton&&this.pluginApi.positionFullscreenButton(Math.floor(e),Math.floor(t),n)},hideFullscreenButton:function(){this.pluginApi!=null&&this.pluginApi.hideFullscreenButton&&this.pluginApi.hideFullscreenButton()},setSrc:function(e){if(typeof e=="string")this.pluginApi.setSrc(mejs.Utility.absolutizeUrl(e)),this.src=mejs.Utility.absolutizeUrl(e);else{var t,n;for(t=0;t<e.length;t++){n=e[t];if(this.canPlayType(n.type)){this.pluginApi.setSrc(mejs.Utility.absolutizeUrl(n.src)),this.src=mejs.Utility.absolutizeUrl(e);break}}}},setCurrentTime:function(e){this.pluginApi!=null&&(this.pluginType=="youtube"?this.pluginApi.seekTo(e):this.pluginApi.setCurrentTime(e),this.currentTime=e)},setVolume:function(e){this.pluginApi!=null&&(this.pluginType=="youtube"?this.pluginApi.setVolume(e*100):this.pluginApi.setVolume(e),this.volume=e)},setMuted:function(e){this.pluginApi!=null&&(this.pluginType=="youtube"?(e?this.pluginApi.mute():this.pluginApi.unMute(),this.muted=e,this.dispatchEvent("volumechange")):this.pluginApi.setMuted(e),this.muted=e)},setVideoSize:function(e,t){this.pluginElement.style&&(this.pluginElement.style.width=e+"px",this.pluginElement.style.height=t+"px"),this.pluginApi!=null&&this.pluginApi.setVideoSize&&this.pluginApi.setVideoSize(e,t)},setFullscreen:function(e){this.pluginApi!=null&&this.pluginApi.setFullscreen&&this.pluginApi.setFullscreen(e)},enterFullScreen:function(){this.pluginApi!=null&&this.pluginApi.setFullscreen&&this.setFullscreen(!0)},exitFullScreen:function(){this.pluginApi!=null&&this.pluginApi.setFullscreen&&this.setFullscreen(!1)},addEventListener:function(e,t){this.events[e]=this.events[e]||[],this.events[e].push(t)},removeEventListener:function(e,t){if(!e)return this.events={},!0;var n=this.events[e];if(!n)return!0;if(!t)return this.events[e]=[],!0;for(i=0;i<n.length;i++)if(n[i]===t)return this.events[e].splice(i,1),!0;return!1},dispatchEvent:function(e){var t,n,r=this.events[e];if(r){n=Array.prototype.slice.call(arguments,1);for(t=0;t<r.length;t++)r[t].apply(null,n)}},hasAttribute:function(e){return e in this.attributes},removeAttribute:function(e){delete this.attributes[e]},getAttribute:function(e){return this.hasAttribute(e)?this.attributes[e]:""},setAttribute:function(e,t){this.attributes[e]=t},remove:function(){mejs.Utility.removeSwf(this.pluginElement.id),mejs.MediaPluginBridge.unregisterPluginElement(this.pluginElement.id)}},mejs.MediaPluginBridge={pluginMediaElements:{},htmlMediaElements:{},registerPluginElement:function(e,t,n){this.pluginMediaElements[e]=t,this.htmlMediaElements[e]=n},unregisterPluginElement:function(e){delete this.pluginMediaElements[e],delete this.htmlMediaElements[e]},initPlugin:function(e){var t=this.pluginMediaElements[e],n=this.htmlMediaElements[e];if(t){switch(t.pluginType){case"flash":t.pluginElement=t.pluginApi=document.getElementById(e);break;case"silverlight":t.pluginElement=document.getElementById(t.id),t.pluginApi=t.pluginElement.Content.MediaElementJS}t.pluginApi!=null&&t.success&&t.success(t,n)}},fireEvent:function(e,t,n){var r,i;if(e=this.pluginMediaElements[e]){t={type:t,target:e};for(r in n)e[r]=n[r],t[r]=n[r];i=n.bufferedTime||0,t.target.buffered=t.buffered={start:function(){return 0},end:function(){return i},length:1},e.dispatchEvent(t.type,t)}}},mejs.MediaElementDefaults={mode:"auto",plugins:["flash","silverlight","youtube","vimeo"],enablePluginDebug:!1,httpsBasicAuthSite:!1,type:"",pluginPath:mejs.Utility.getScriptPath(["mediaelement.js","mediaelement.min.js","mediaelement-and-player.js","mediaelement-and-player.min.js"]),flashName:"flashmediaelement.swf",flashStreamer:"",enablePluginSmoothing:!1,enablePseudoStreaming:!1,pseudoStreamingStartQueryParam:"start",silverlightName:"silverlightmediaelement.xap",defaultVideoWidth:480,defaultVideoHeight:270,pluginWidth:-1,pluginHeight:-1,pluginVars:[],timerRate:250,startVolume:.8,success:function(){},error:function(){}},mejs.MediaElement=function(e,t){return mejs.HtmlMediaElementShim.create(e,t)},mejs.HtmlMediaElementShim={create:function(e,t){var n=mejs.MediaElementDefaults,r=typeof e=="string"?document.getElementById(e):e,i=r.tagName.toLowerCase(),s=i==="audio"||i==="video",o=s?r.getAttribute("src"):r.getAttribute("href");i=r.getAttribute("poster");var u=r.getAttribute("autoplay"),a=r.getAttribute("preload"),f=r.getAttribute("controls"),l;for(l in t)n[l]=t[l];return o=typeof o=="undefined"||o===null||o==""?null:o,i=typeof i=="undefined"||i===null?"":i,a=typeof a=="undefined"||a===null||a==="false"?"none":a,u=typeof u!="undefined"&&u!==null&&u!=="false",f=typeof f!="undefined"&&f!==null&&f!=="false",l=this.determinePlayback(r,n,mejs.MediaFeatures.supportsMediaTag,s,o),l.url=l.url!==null?mejs.Utility.absolutizeUrl(l.url):"",l.method=="native"?(mejs.MediaFeatures.isBustedAndroid&&(r.src=l.url,r.addEventListener("click",function(){r.play()},!1)),this.updateNative(l,n,u,a)):l.method!==""?this.createPlugin(l,n,i,u,a,f):(this.createErrorMessage(l,n,i),this)},determinePlayback:function(e,t,n,r,i){var s=[],o,u,a,f={method:"",url:"",htmlMediaElement:e,isVideo:e.tagName.toLowerCase()!="audio"},l;if(typeof t.type!="undefined"&&t.type!=="")if(typeof t.type=="string")s.push({type:t.type,url:i});else for(o=0;o<t.type.length;o++)s.push({type:t.type[o],url:i});else if(i!==null)a=this.formatType(i,e.getAttribute("type")),s.push({type:a,url:i});else for(o=0;o<e.childNodes.length;o++)u=e.childNodes[o],u.nodeType==1&&u.tagName.toLowerCase()=="source"&&(i=u.getAttribute("src"),a=this.formatType(i,u.getAttribute("type")),u=u.getAttribute("media"),(!u||!window.matchMedia||window.matchMedia&&window.matchMedia(u).matches)&&s.push({type:a,url:i}));!r&&s.length>0&&s[0].url!==null&&this.getTypeFromFile(s[0].url).indexOf("audio")>-1&&(f.isVideo=!1),mejs.MediaFeatures.isBustedAndroid&&(e.canPlayType=function(e){return e.match(/video\/(mp4|m4v)/gi)!==null?"maybe":""});if(n&&(t.mode==="auto"||t.mode==="auto_plugin"||t.mode==="native")&&(!mejs.MediaFeatures.isBustedNativeHTTPS||t.httpsBasicAuthSite!==!0)){r||(o=document.createElement(f.isVideo?"video":"audio"),e.parentNode.insertBefore(o,e),e.style.display="none",f.htmlMediaElement=e=o);for(o=0;o<s.length;o++)if(e.canPlayType(s[o].type).replace(/no/,"")!==""||e.canPlayType(s[o].type.replace(/mp3/,"mpeg")).replace(/no/,"")!==""){f.method="native",f.url=s[o].url;break}if(f.method==="native"){f.url!==null&&(e.src=f.url);if(t.mode!=="auto_plugin")return f}}if(t.mode==="auto"||t.mode==="auto_plugin"||t.mode==="shim")for(o=0;o<s.length;o++){a=s[o].type;for(e=0;e<t.plugins.length;e++){i=t.plugins[e],u=mejs.plugins[i];for(n=0;n<u.length;n++){l=u[n];if(l.version==null||mejs.PluginDetector.hasPluginVersion(i,l.version))for(r=0;r<l.types.length;r++)if(a==l.types[r])return f.method=i,f.url=s[o].url,f}}}return t.mode==="auto_plugin"&&f.method==="native"?f:(f.method===""&&s.length>0&&(f.url=s[0].url),f)},formatType:function(e,t){return e&&!t?this.getTypeFromFile(e):t&&~t.indexOf(";")?t.substr(0,t.indexOf(";")):t},getTypeFromFile:function(e){return e=e.split("?")[0],e=e.substring(e.lastIndexOf(".")+1).toLowerCase(),(/(mp4|m4v|ogg|ogv|webm|webmv|flv|wmv|mpeg|mov)/gi.test(e)?"video":"audio")+"/"+this.getTypeFromExtension(e)},getTypeFromExtension:function(e){switch(e){case"mp4":case"m4v":return"mp4";case"webm":case"webma":case"webmv":return"webm";case"ogg":case"oga":case"ogv":return"ogg";default:return e}},createErrorMessage:function(e,t,n){var r=e.htmlMediaElement,i=document.createElement("div");i.className="me-cannotplay";try{i.style.width=r.width+"px",i.style.height=r.height+"px"}catch(s){}i.innerHTML=t.customError?t.customError:n!==""?'<a href="'+e.url+'"><img src="'+n+'" width="100%" height="100%" /></a>':'<a href="'+e.url+'"><span>'+mejs.i18n.t("Download File")+"</span></a>",r.parentNode.insertBefore(i,r),r.style.display="none",t.error(r)},createPlugin:function(e,t,n,r,i,s){n=e.htmlMediaElement;var o=1,u=1,a="me_"+e.method+"_"+mejs.meIndex++,f=new mejs.PluginMediaElement(a,e.method,e.url),l=document.createElement("div"),c;f.tagName=n.tagName;for(c=0;c<n.attributes.length;c++){var h=n.attributes[c];h.specified==1&&f.setAttribute(h.name,h.value)}for(c=n.parentNode;c!==null&&c.tagName.toLowerCase()!="body";){if(c.parentNode.tagName.toLowerCase()=="p"){c.parentNode.parentNode.insertBefore(c,c.parentNode);break}c=c.parentNode}e.isVideo?(o=t.pluginWidth>0?t.pluginWidth:t.videoWidth>0?t.videoWidth:n.getAttribute("width")!==null?n.getAttribute("width"):t.defaultVideoWidth,u=t.pluginHeight>0?t.pluginHeight:t.videoHeight>0?t.videoHeight:n.getAttribute("height")!==null?n.getAttribute("height"):t.defaultVideoHeight,o=mejs.Utility.encodeUrl(o),u=mejs.Utility.encodeUrl(u)):t.enablePluginDebug&&(o=320,u=240),f.success=t.success,mejs.MediaPluginBridge.registerPluginElement(a,f,n),l.className="me-plugin",l.id=a+"_container",e.isVideo?n.parentNode.insertBefore(l,n):document.body.insertBefore(l,document.body.childNodes[0]),r=["id="+a,"isvideo="+(e.isVideo?"true":"false"),"autoplay="+(r?"true":"false"),"preload="+i,"width="+o,"startvolume="+t.startVolume,"timerrate="+t.timerRate,"flashstreamer="+t.flashStreamer,"height="+u,"pseudostreamstart="+t.pseudoStreamingStartQueryParam],e.url!==null&&(e.method=="flash"?r.push("file="+mejs.Utility.encodeUrl(e.url)):r.push("file="+e.url)),t.enablePluginDebug&&r.push("debug=true"),t.enablePluginSmoothing&&r.push("smoothing=true"),t.enablePseudoStreaming&&r.push("pseudostreaming=true"),s&&r.push("controls=true"),t.pluginVars&&(r=r.concat(t.pluginVars));switch(e.method){case"silverlight":l.innerHTML='<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" id="'+a+'" name="'+a+'" width="'+o+'" height="'+u+'" class="mejs-shim"><param name="initParams" value="'+r.join(",")+'" /><param name="windowless" value="true" /><param name="background" value="black" /><param name="minRuntimeVersion" value="3.0.0.0" /><param name="autoUpgrade" value="true" /><param name="source" value="'+t.pluginPath+t.silverlightName+'" /></object>';break;case"flash":mejs.MediaFeatures.isIE?(e=document.createElement("div"),l.appendChild(e),e.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="//download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" id="'+a+'" width="'+o+'" height="'+u+'" class="mejs-shim"><param name="movie" value="'+t.pluginPath+t.flashName+"?x="+new Date+'" /><param name="flashvars" value="'+r.join("&amp;")+'" /><param name="quality" value="high" /><param name="bgcolor" value="#000000" /><param name="wmode" value="transparent" /><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="true" /></object>'):l.innerHTML='<embed id="'+a+'" name="'+a+'" play="true" loop="false" quality="high" bgcolor="#000000" wmode="transparent" allowScriptAccess="always" allowFullScreen="true" type="application/x-shockwave-flash" pluginspage="//www.macromedia.com/go/getflashplayer" src="'+t.pluginPath+t.flashName+'" flashvars="'+r.join("&")+'" width="'+o+'" height="'+u+'" class="mejs-shim"></embed>';break;case"youtube":t=e.url.substr(e.url.lastIndexOf("=")+1),youtubeSettings={container:l,containerId:l.id,pluginMediaElement:f,pluginId:a,videoId:t,height:u,width:o},mejs.PluginDetector.hasPluginVersion("flash",[10,0,0])?mejs.YouTubeApi.createFlash(youtubeSettings):mejs.YouTubeApi.enqueueIframe(youtubeSettings);break;case"vimeo":f.vimeoid=e.url.substr(e.url.lastIndexOf("/")+1),l.innerHTML='<iframe src="http://player.vimeo.com/video/'+f.vimeoid+'?portrait=0&byline=0&title=0" width="'+o+'" height="'+u+'" frameborder="0" class="mejs-shim"></iframe>'}return n.style.display="none",n.removeAttribute("autoplay"),f},updateNative:function(e,t){var n=e.htmlMediaElement,r;for(r in mejs.HtmlMediaElement)n[r]=mejs.HtmlMediaElement[r];return t.success(n,n),n}},mejs.YouTubeApi={isIframeStarted:!1,isIframeLoaded:!1,loadIframeApi:function(){if(!this.isIframeStarted){var e=document.createElement("script");e.src="//www.youtube.com/player_api";var t=document.getElementsByTagName("script")[0];t.parentNode.insertBefore(e,t),this.isIframeStarted=!0}},iframeQueue:[],enqueueIframe:function(e){this.isLoaded?this.createIframe(e):(this.loadIframeApi(),this.iframeQueue.push(e))},createIframe:function(e){var t=e.pluginMediaElement,n=new YT.Player(e.containerId,{height:e.height,width:e.width,videoId:e.videoId,playerVars:{controls:0},events:{onReady:function(){e.pluginMediaElement.pluginApi=n,mejs.MediaPluginBridge.initPlugin(e.pluginId),setInterval(function(){mejs.YouTubeApi.createEvent(n,t,"timeupdate")},250)},onStateChange:function(e){mejs.YouTubeApi.handleStateChange(e.data,n,t)}}})},createEvent:function(e,t,n){n={type:n,target:t};if(e&&e.getDuration){t.currentTime=n.currentTime=e.getCurrentTime(),t.duration=n.duration=e.getDuration(),n.paused=t.paused,n.ended=t.ended,n.muted=e.isMuted(),n.volume=e.getVolume()/100,n.bytesTotal=e.getVideoBytesTotal(),n.bufferedBytes=e.getVideoBytesLoaded();var r=n.bufferedBytes/n.bytesTotal*n.duration;n.target.buffered=n.buffered={start:function(){return 0},end:function(){return r},length:1}}t.dispatchEvent(n.type,n)},iFrameReady:function(){for(this.isIframeLoaded=this.isLoaded=!0;this.iframeQueue.length>0;)this.createIframe(this.iframeQueue.pop())},flashPlayers:{},createFlash:function(e){this.flashPlayers[e.pluginId]=e;var t,n="//www.youtube.com/apiplayer?enablejsapi=1&amp;playerapiid="+e.pluginId+"&amp;version=3&amp;autoplay=0&amp;controls=0&amp;modestbranding=1&loop=0";mejs.MediaFeatures.isIE?(t=document.createElement("div"),e.container.appendChild(t),t.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="//download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" id="'+e.pluginId+'" width="'+e.width+'" height="'+e.height+'" class="mejs-shim"><param name="movie" value="'+n+'" /><param name="wmode" value="transparent" /><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="true" /></object>'):e.container.innerHTML='<object type="application/x-shockwave-flash" id="'+e.pluginId+'" data="'+n+'" width="'+e.width+'" height="'+e.height+'" style="visibility: visible; " class="mejs-shim"><param name="allowScriptAccess" value="always"><param name="wmode" value="transparent"></object>'},flashReady:function(e){var t=this.flashPlayers[e],n=document.getElementById(e),r=t.pluginMediaElement;r.pluginApi=r.pluginElement=n,mejs.MediaPluginBridge.initPlugin(e),n.cueVideoById(t.videoId),e=t.containerId+"_callback",window[e]=function(e){mejs.YouTubeApi.handleStateChange(e,n,r)},n.addEventListener("onStateChange",e),setInterval(function(){mejs.YouTubeApi.createEvent(n,r,"timeupdate")},250)},handleStateChange:function(e,t,n){switch(e){case-1:n.paused=!0,n.ended=!0,mejs.YouTubeApi.createEvent(t,n,"loadedmetadata");break;case 0:n.paused=!1,n.ended=!0,mejs.YouTubeApi.createEvent(t,n,"ended");break;case 1:n.paused=!1,n.ended=!1,mejs.YouTubeApi.createEvent(t,n,"play"),mejs.YouTubeApi.createEvent(t,n,"playing");break;case 2:n.paused=!0,n.ended=!1,mejs.YouTubeApi.createEvent(t,n,"pause");break;case 3:mejs.YouTubeApi.createEvent(t,n,"progress")}}},window.mejs=mejs,window.MediaElement=mejs.MediaElement,function(e,t){var n={locale:{language:"",strings:{}},methods:{}};n.locale.getLanguage=function(){return n.locale.language||navigator.language},typeof mejsL10n!="undefined"&&(n.locale.language=mejsL10n.language),n.locale.INIT_LANGUAGE=n.locale.getLanguage(),n.methods.checkPlain=function(e){var t,n,r={"&":"&amp;",'"':"&quot;","<":"&lt;",">":"&gt;"};e=String(e);for(t in r)r.hasOwnProperty(t)&&(n=RegExp(t,"g"),e=e.replace(n,r[t]));return e},n.methods.formatString=function(e,t){for(var r in t){switch(r.charAt(0)){case"@":t[r]=n.methods.checkPlain(t[r]);break;case"!":break;default:t[r]='<em class="placeholder">'+n.methods.checkPlain(t[r])+"</em>"}e=e.replace(r,t[r])}return e},n.methods.t=function(e,t,r){return n.locale.strings&&n.locale.strings[r.context]&&n.locale.strings[r.context][e]&&(e=n.locale.strings[r.context][e]),t&&(e=n.methods.formatString(e,t)),e},n.t=function(e,t,r){if(typeof e=="string"&&e.length>0){var i=n.locale.getLanguage();return r=r||{context:i},n.methods.t(e,t,r)}throw{name:"InvalidArgumentException",message:"First argument is either not a string or empty."}},t.i18n=n}(document,mejs),function(e){typeof mejsL10n!="undefined"&&(e[mejsL10n.language]=mejsL10n.strings)}(mejs.i18n.locale.strings),function(e){e.de={Fullscreen:"Vollbild","Go Fullscreen":"Vollbild an","Turn off Fullscreen":"Vollbild aus",Close:"Schließen"}}(mejs.i18n.locale.strings),function(e){e.zh={Fullscreen:"全螢幕","Go Fullscreen":"全屏模式","Turn off Fullscreen":"退出全屏模式",Close:"關閉"}}(mejs.i18n.locale.strings),typeof jQuery!="undefined"?mejs.$=jQuery:typeof ender!="undefined"&&(mejs.$=ender),function(e){mejs.MepDefaults={poster:"",showPosterWhenEnded:!1,defaultVideoWidth:480,defaultVideoHeight:270,videoWidth:-1,videoHeight:-1,defaultAudioWidth:400,defaultAudioHeight:30,defaultSeekBackwardInterval:function(e){return e.duration*.05},defaultSeekForwardInterval:function(e){return e.duration*.05},audioWidth:-1,audioHeight:-1,startVolume:.8,loop:!1,autoRewind:!0,enableAutosize:!0,alwaysShowHours:!1,showTimecodeFrameCount:!1,framesPerSecond:25,autosizeProgress:!0,alwaysShowControls:!1,hideVideoControlsOnLoad:!1,clickToPlayPause:!0,iPadUseNativeControls:!1,iPhoneUseNativeControls:!1,AndroidUseNativeControls:!1,features:["playpause","current","progress","duration","tracks","volume","fullscreen"],isVideo:!0,enableKeyboard:!0,pauseOtherPlayers:!0,keyActions:[{keys:[32,179],action:function(e,t){t.paused||t.ended?t.play():t.pause()}},{keys:[38],action:function(e,t){t.setVolume(Math.min(t.volume+.1,1))}},{keys:[40],action:function(e,t){t.setVolume(Math.max(t.volume-.1,0))}},{keys:[37,227],action:function(e,t){if(!isNaN(t.duration)&&t.duration>0){e.isVideo&&(e.showControls(),e.startControlsTimer());var n=Math.max(t.currentTime-e.options.defaultSeekBackwardInterval(t),0);t.setCurrentTime(n)}}},{keys:[39,228],action:function(e,t){if(!isNaN(t.duration)&&t.duration>0){e.isVideo&&(e.showControls(),e.startControlsTimer());var n=Math.min(t.currentTime+e.options.defaultSeekForwardInterval(t),t.duration);t.setCurrentTime(n)}}},{keys:[70],action:function(e){typeof e.enterFullScreen!="undefined"&&(e.isFullScreen?e.exitFullScreen():e.enterFullScreen())}}]},mejs.mepIndex=0,mejs.players={},mejs.MediaElementPlayer=function(t,n){if(this instanceof mejs.MediaElementPlayer)return this.$media=this.$node=e(t),this.node=this.media=this.$media[0],typeof this.node.player!="undefined"?this.node.player:(this.node.player=this,typeof n=="undefined"&&(n=this.$node.data("mejsoptions")),this.options=e.extend({},mejs.MepDefaults,n),this.id="mep_"+mejs.mepIndex++,mejs.players[this.id]=this,this.init(),this);return new mejs.MediaElementPlayer(t,n)},mejs.MediaElementPlayer.prototype={hasFocus:!1,controlsAreVisible:!0,init:function(){var t=this,n=mejs.MediaFeatures,r=e.extend(!0,{},t.options,{success:function(e,n){t.meReady(e,n)},error:function(e){t.handleError(e)}}),i=t.media.tagName.toLowerCase();t.isDynamic=i!=="audio"&&i!=="video",t.isVideo=t.isDynamic?t.options.isVideo:i!=="audio"&&t.options.isVideo;if(n.isiPad&&t.options.iPadUseNativeControls||n.isiPhone&&t.options.iPhoneUseNativeControls)t.$media.attr("controls","controls"),n.isiPad&&t.media.getAttribute("autoplay")!==null&&(t.media.load(),t.media.play());else if(!n.isAndroid||!t.options.AndroidUseNativeControls)t.$media.removeAttr("controls"),t.container=e('<div id="'+t.id+'" class="mejs-container '+(mejs.MediaFeatures.svg?"svg":"no-svg")+'"><div class="mejs-inner"><div class="mejs-mediaelement"></div><div class="mejs-layers"></div><div class="mejs-controls"></div><div class="mejs-clear"></div></div></div>').addClass(t.$media[0].className).insertBefore(t.$media),t.container.addClass((n.isAndroid?"mejs-android ":"")+(n.isiOS?"mejs-ios ":"")+(n.isiPad?"mejs-ipad ":"")+(n.isiPhone?"mejs-iphone ":"")+(t.isVideo?"mejs-video ":"mejs-audio ")),n.isiOS?(n=t.$media.clone(),t.container.find(".mejs-mediaelement").append(n),t.$media.remove(),t.$node=t.$media=n,t.node=t.media=n[0]):t.container.find(".mejs-mediaelement").append(t.$media),t.controls=t.container.find(".mejs-controls"),t.layers=t.container.find(".mejs-layers"),n=t.isVideo?"video":"audio",i=n.substring(0,1).toUpperCase()+n.substring(1),t.width=t.options[n+"Width"]>0||t.options[n+"Width"].toString().indexOf("%")>-1?t.options[n+"Width"]:t.media.style.width!==""&&t.media.style.width!==null?t.media.style.width:t.media.getAttribute("width")!==null?t.$media.attr("width"):t.options["default"+i+"Width"],t.height=t.options[n+"Height"]>0||t.options[n+"Height"].toString().indexOf("%")>-1?t.options[n+"Height"]:t.media.style.height!==""&&t.media.style.height!==null?t.media.style.height:t.$media[0].getAttribute("height")!==null?t.$media.attr("height"):t.options["default"+i+"Height"],t.setPlayerSize(t.width,t.height),r.pluginWidth=t.width,r.pluginHeight=t.height;mejs.MediaElement(t.$media[0],r),typeof t.container!="undefined"&&t.controlsAreVisible&&t.container.trigger("controlsshown")},showControls:function(e){var t=this;e=typeof e=="undefined"||e,t.controlsAreVisible||(e?(t.controls.css("visibility","visible").stop(!0,!0).fadeIn(200,function(){t.controlsAreVisible=!0,t.container.trigger("controlsshown")}),t.container.find(".mejs-control").css("visibility","visible").stop(!0,!0).fadeIn(200,function(){t.controlsAreVisible=!0})):(t.controls.css("visibility","visible").css("display","block"),t.container.find(".mejs-control").css("visibility","visible").css("display","block"),t.controlsAreVisible=!0,t.container.trigger("controlsshown")),t.setControlsSize())},hideControls:function(t){var n=this;t=typeof t=="undefined"||t,!!n.controlsAreVisible&&!n.options.alwaysShowControls&&(t?(n.controls.stop(!0,!0).fadeOut(200,function(){e(this).css("visibility","hidden").css("display","block"),n.controlsAreVisible=!1,n.container.trigger("controlshidden")}),n.container.find(".mejs-control").stop(!0,!0).fadeOut(200,function(){e(this).css("visibility","hidden").css("display","block")})):(n.controls.css("visibility","hidden").css("display","block"),n.container.find(".mejs-control").css("visibility","hidden").css("display","block"),n.controlsAreVisible=!1,n.container.trigger("controlshidden")))},controlsTimer:null,startControlsTimer:function(e){var t=this;e=typeof e!="undefined"?e:1500,t.killControlsTimer("start"),t.controlsTimer=setTimeout(function(){t.hideControls(),t.killControlsTimer("hide")},e)},killControlsTimer:function(){this.controlsTimer!==null&&(clearTimeout(this.controlsTimer),delete this.controlsTimer,this.controlsTimer=null)},controlsEnabled:!0,disableControls:function(){this.killControlsTimer(),this.hideControls(!1),this.controlsEnabled=!1},enableControls:function(){this.showControls(!1),this.controlsEnabled=!0},meReady:function(e,t){var n=this,r=mejs.MediaFeatures,i=t.getAttribute("autoplay");i=typeof i!="undefined"&&i!==null&&i!=="false";var s;if(!n.created){n.created=!0,n.media=e,n.domNode=t;if((!r.isAndroid||!n.options.AndroidUseNativeControls)&&(!r.isiPad||!n.options.iPadUseNativeControls)&&(!r.isiPhone||!n.options.iPhoneUseNativeControls)){n.buildposter(n,n.controls,n.layers,n.media),n.buildkeyboard(n,n.controls,n.layers,n.media),n.buildoverlays(n,n.controls,n.layers,n.media),n.findTracks();for(s in n.options.features){r=n.options.features[s];if(n["build"+r])try{n["build"+r](n,n.controls,n.layers,n.media)}catch(o){}}n.container.trigger("controlsready"),n.setPlayerSize(n.width,n.height),n.setControlsSize(),n.isVideo&&(mejs.MediaFeatures.hasTouch?n.$media.bind("touchstart",function(){n.controlsAreVisible?n.hideControls(!1):n.controlsEnabled&&n.showControls(!1)}):(mejs.MediaElementPlayer.prototype.clickToPlayPauseCallback=function(){n.options.clickToPlayPause&&(n.media.paused?n.media.play():n.media.pause())},n.media.addEventListener("click",n.clickToPlayPauseCallback,!1),n.container.bind("mouseenter mouseover",function(){n.controlsEnabled&&(n.options.alwaysShowControls||(n.killControlsTimer("enter"),n.showControls(),n.startControlsTimer(2500)))}).bind("mousemove",function(){n.controlsEnabled&&(n.controlsAreVisible||n.showControls(),n.options.alwaysShowControls||n.startControlsTimer(2500))}).bind("mouseleave",function(){n.controlsEnabled&&!n.media.paused&&!n.options.alwaysShowControls&&n.startControlsTimer(1e3)})),n.options.hideVideoControlsOnLoad&&n.hideControls(!1),i&&!n.options.alwaysShowControls&&n.hideControls(),n.options.enableAutosize&&n.media.addEventListener("loadedmetadata",function(e){n.options.videoHeight<=0&&n.domNode.getAttribute("height")===null&&!isNaN(e.target.videoHeight)&&(n.setPlayerSize(e.target.videoWidth,e.target.videoHeight),n.setControlsSize(),n.media.setVideoSize(e.target.videoWidth,e.target.videoHeight))},!1)),e.addEventListener("play",function(){for(var e in mejs.players){var t=mejs.players[e];t.id!=n.id&&n.options.pauseOtherPlayers&&!t.paused&&!t.ended&&t.pause(),t.hasFocus=!1}n.hasFocus=!0},!1),n.media.addEventListener("ended",function(){if(n.options.autoRewind)try{n.media.setCurrentTime(0)}catch(e){}n.media.pause(),n.setProgressRail&&n.setProgressRail(),n.setCurrentRail&&n.setCurrentRail(),n.options.loop?n.media.play():!n.options.alwaysShowControls&&n.controlsEnabled&&n.showControls()},!1),n.media.addEventListener("loadedmetadata",function(){n.updateDuration&&n.updateDuration(),n.updateCurrent&&n.updateCurrent(),n.isFullScreen||(n.setPlayerSize(n.width,n.height),n.setControlsSize())},!1),setTimeout(function(){n.setPlayerSize(n.width,n.height),n.setControlsSize()},50),n.globalBind("resize",function(){n.isFullScreen||mejs.MediaFeatures.hasTrueNativeFullScreen&&document.webkitIsFullScreen||n.setPlayerSize(n.width,n.height),n.setControlsSize()}),n.media.pluginType=="youtube"&&n.container.find(".mejs-overlay-play").hide()}i&&e.pluginType=="native"&&(e.load(),e.play()),n.options.success&&(typeof n.options.success=="string"?window[n.options.success](n.media,n.domNode,n):n.options.success(n.media,n.domNode,n))}},handleError:function(e){this.controls.hide(),this.options.error&&this.options.error(e)},setPlayerSize:function(t,n){typeof t!="undefined"&&(this.width=t),typeof n!="undefined"&&(this.height=n);if(this.height.toString().indexOf("%")>0||this.$node.css("max-width")==="100%"||parseInt(this.$node.css("max-width").replace(/px/,""),10)/this.$node.offsetParent().width()===1||this.$node[0].currentStyle&&this.$node[0].currentStyle.maxWidth==="100%"){var r=this.isVideo?this.media.videoWidth&&this.media.videoWidth>0?this.media.videoWidth:this.options.defaultVideoWidth:this.options.defaultAudioWidth,i=this.isVideo?this.media.videoHeight&&this.media.videoHeight>0?this.media.videoHeight:this.options.defaultVideoHeight:this.options.defaultAudioHeight,s=this.container.parent().closest(":visible").width();r=this.isVideo||!this.options.autosizeProgress?parseInt(s*i/r,10):i,this.container.parent()[0].tagName.toLowerCase()==="body"&&(s=e(window).width(),r=e(window).height()),r!=0&&s!=0&&(this.container.width(s).height(r),this.$media.add(this.container.find(".mejs-shim")).width("100%").height("100%"),this.isVideo&&this.media.setVideoSize&&this.media.setVideoSize(s,r),this.layers.children(".mejs-layer").width("100%").height("100%"))}else this.container.width(this.width).height(this.height),this.layers.children(".mejs-layer").width(this.width).height(this.height);s=this.layers.find(".mejs-overlay-play"),r=s.find(".mejs-overlay-button"),s.height(this.container.height()-this.controls.height()),r.css("margin-top","-"+(r.height()/2-this.controls.height()/2).toString()+"px")},setControlsSize:function(){var t=0,n=0,r=this.controls.find(".mejs-time-rail"),i=this.controls.find(".mejs-time-total");this.controls.find(".mejs-time-current"),this.controls.find(".mejs-time-loaded");var s=r.siblings();this.options&&!this.options.autosizeProgress&&(n=parseInt(r.css("width")));if(n===0||!n)s.each(function(){var n=e(this);n.css("position")!="absolute"&&n.is(":visible")&&(t+=e(this).outerWidth(!0))}),n=this.controls.width()-t-(r.outerWidth(!0)-r.width());r.width(n),i.width(n-(i.outerWidth(!0)-i.width())),this.setProgressRail&&this.setProgressRail(),this.setCurrentRail&&this.setCurrentRail()},buildposter:function(t,n,r,i){var s=e('<div class="mejs-poster mejs-layer"></div>').appendTo(r);n=t.$media.attr("poster"),t.options.poster!==""&&(n=t.options.poster),n!==""&&n!=null?this.setPoster(n):s.hide(),i.addEventListener("play",function(){s.hide()},!1),t.options.showPosterWhenEnded&&t.options.autoRewind&&i.addEventListener("ended",function(){s.show()},!1)},setPoster:function(t){var n=this.container.find(".mejs-poster"),r=n.find("img");r.length==0&&(r=e('<img width="100%" height="100%" />').appendTo(n)),r.attr("src",t),n.css({"background-image":"url("+t+")"})},buildoverlays:function(t,n,r,i){var s=this;if(t.isVideo){var o=e('<div class="mejs-overlay mejs-layer"><div class="mejs-overlay-loading"><span></span></div></div>').hide().appendTo(r),u=e('<div class="mejs-overlay mejs-layer"><div class="mejs-overlay-error"></div></div>').hide().appendTo(r),a=e('<div class="mejs-overlay mejs-layer mejs-overlay-play"><div class="mejs-overlay-button"></div></div>').appendTo(r).click(function(){s.options.clickToPlayPause&&(i.paused?i.play():i.pause())});i.addEventListener("play",function(){a.hide(),o.hide(),n.find(".mejs-time-buffering").hide(),u.hide()},!1),i.addEventListener("playing",function(){a.hide(),o.hide(),n.find(".mejs-time-buffering").hide(),u.hide()},!1),i.addEventListener("seeking",function(){o.show(),n.find(".mejs-time-buffering").show()},!1),i.addEventListener("seeked",function(){o.hide(),n.find(".mejs-time-buffering").hide()},!1),i.addEventListener("pause",function(){mejs.MediaFeatures.isiPhone||a.show()},!1),i.addEventListener("waiting",function(){o.show(),n.find(".mejs-time-buffering").show()},!1),i.addEventListener("loadeddata",function(){o.show(),n.find(".mejs-time-buffering").show()},!1),i.addEventListener("canplay",function(){o.hide(),n.find(".mejs-time-buffering").hide()},!1),i.addEventListener("error",function(){o.hide(),n.find(".mejs-time-buffering").hide(),u.show(),u.find("mejs-overlay-error").html("Error loading this resource")},!1)}},buildkeyboard:function(t,n,r,i){this.globalBind("keydown",function(e){if(t.hasFocus&&t.options.enableKeyboard)for(var n=0,r=t.options.keyActions.length;n<r;n++)for(var s=t.options.keyActions[n],o=0,u=s.keys.length;o<u;o++)if(e.keyCode==s.keys[o])return e.preventDefault(),s.action(t,i,e.keyCode),!1;return!0}),this.globalBind("click",function(n){e(n.target).closest(".mejs-container").length==0&&(t.hasFocus=!1)})},findTracks:function(){var t=this,n=t.$media.find("track");t.tracks=[],n.each(function(n,r){r=e(r),t.tracks.push({srclang:r.attr("srclang")?r.attr("srclang").toLowerCase():"",src:r.attr("src"),kind:r.attr("kind"),label:r.attr("label")||"",entries:[],isLoaded:!1})})},changeSkin:function(e){this.container[0].className="mejs-container "+e,this.setPlayerSize(this.width,this.height),this.setControlsSize()},play:function(){this.media.play()},pause:function(){try{this.media.pause()}catch(e){}},load:function(){this.media.load()},setMuted:function(e){this.media.setMuted(e)},setCurrentTime:function(e){this.media.setCurrentTime(e)},getCurrentTime:function(){return this.media.currentTime},setVolume:function(e){this.media.setVolume(e)},getVolume:function(){return this.media.volume},setSrc:function(e){this.media.setSrc(e)},remove:function(){var e,t;for(e in this.options.features){t=this.options.features[e];if(this["clean"+t])try{this["clean"+t](this)}catch(n){}}this.isDynamic?this.$node.insertBefore(this.container):(this.$media.prop("controls",!0),this.$node.clone().show().insertBefore(this.container),this.$node.remove()),this.media.pluginType!=="native"&&this.media.remove(),delete mejs.players[this.id],this.container.remove(),this.globalUnbind(),delete this.node.player}},function(){function t(t,r){var i={d:[],w:[]};return e.each((t||"").split(" "),function(e,t){var s=t+"."+r;s.indexOf(".")===0?(i.d.push(s),i.w.push(s)):i[n.test(t)?"w":"d"].push(s)}),i.d=i.d.join(" "),i.w=i.w.join(" "),i}var n=/^((after|before)print|(before)?unload|hashchange|message|o(ff|n)line|page(hide|show)|popstate|resize|storage)\b/;mejs.MediaElementPlayer.prototype.globalBind=function(n,r,i){n=t(n,this.id),n.d&&e(document).bind(n.d,r,i),n.w&&e(window).bind(n.w,r,i)},mejs.MediaElementPlayer.prototype.globalUnbind=function(n,r){n=t(n,this.id),n.d&&e(document).unbind(n.d,r),n.w&&e(window).unbind(n.w,r)}}(),typeof jQuery!="undefined"&&(jQuery.fn.mediaelementplayer=function(e){return e===!1?this.each(function(){var e=jQuery(this).data("mediaelementplayer");e&&e.remove(),jQuery(this).removeData("mediaelementplayer")}):this.each(function(){jQuery(this).data("mediaelementplayer",new mejs.MediaElementPlayer(this,e))}),this}),e(document).ready(function(){e(".mejs-player").mediaelementplayer()}),window.MediaElementPlayer=mejs.MediaElementPlayer}(mejs.$),function(e){e.extend(mejs.MepDefaults,{playpauseText:mejs.i18n.t("Play/Pause")}),e.extend(MediaElementPlayer.prototype,{buildplaypause:function(t,n,r,i){var s=e('<div class="mejs-button mejs-playpause-button mejs-play" ><button type="button" aria-controls="'+this.id+'" title="'+this.options.playpauseText+'" aria-label="'+this.options.playpauseText+'"></button></div>').appendTo(n).click(function(e){return e.preventDefault(),i.paused?i.play():i.pause(),!1});i.addEventListener("play",function(){s.removeClass("mejs-play").addClass("mejs-pause")},!1),i.addEventListener("playing",function(){s.removeClass("mejs-play").addClass("mejs-pause")},!1),i.addEventListener("pause",function(){s.removeClass("mejs-pause").addClass("mejs-play")},!1),i.addEventListener("paused",function(){s.removeClass("mejs-pause").addClass("mejs-play")},!1)}})}(mejs.$),function(e){e.extend(mejs.MepDefaults,{stopText:"Stop"}),e.extend(MediaElementPlayer.prototype,{buildstop:function(t,n,r,i){e('<div class="mejs-button mejs-stop-button mejs-stop"><button type="button" aria-controls="'+this.id+'" title="'+this.options.stopText+'" aria-label="'+this.options.stopText+'"></button></div>').appendTo(n).click(function(){i.paused||i.pause(),i.currentTime>0&&(i.setCurrentTime(0),i.pause(),n.find(".mejs-time-current").width("0px"),n.find(".mejs-time-handle").css("left","0px"),n.find(".mejs-time-float-current").html(mejs.Utility.secondsToTimeCode(0)),n.find(".mejs-currenttime").html(mejs.Utility.secondsToTimeCode(0)),r.find(".mejs-poster").show())})}})}(mejs.$),function(e){e.extend(MediaElementPlayer.prototype,{buildprogress:function(t,n,r,i){e('<div class="mejs-time-rail"><span class="mejs-time-total"><span class="mejs-time-buffering"></span><span class="mejs-time-loaded"></span><span class="mejs-time-current"></span><span class="mejs-time-handle"></span><span class="mejs-time-float"><span class="mejs-time-float-current">00:00</span><span class="mejs-time-float-corner"></span></span></span></div>').appendTo(n),n.find(".mejs-time-buffering").hide();var s=this,o=n.find(".mejs-time-total");r=n.find(".mejs-time-loaded");var u=n.find(".mejs-time-current"),a=n.find(".mejs-time-handle"),l=n.find(".mejs-time-float"),c=n.find(".mejs-time-float-current"),h=function(e){e=e.pageX;var t=o.offset(),n=o.outerWidth(!0),r=0,s=r=0;i.duration&&(e<t.left?e=t.left:e>n+t.left&&(e=n+t.left),s=e-t.left,r=s/n,r=r<=.02?0:r*i.duration,p&&r!==i.currentTime&&i.setCurrentTime(r),mejs.MediaFeatures.hasTouch||(l.css("left",s),c.html(mejs.Utility.secondsToTimeCode(r)),l.show()))},p=!1;o.bind("mousedown",function(e){if(e.which===1)return p=!0,h(e),s.globalBind("mousemove.dur",function(e){h(e)}),s.globalBind("mouseup.dur",function(){p=!1,l.hide(),s.globalUnbind(".dur")}),!1}).bind("mouseenter",function(){s.globalBind("mousemove.dur",function(e){h(e)}),mejs.MediaFeatures.hasTouch||l.show()}).bind("mouseleave",function(){p||(s.globalUnbind(".dur"),l.hide())}),i.addEventListener("progress",function(e){t.setProgressRail(e),t.setCurrentRail(e)},!1),i.addEventListener("timeupdate",function(e){t.setProgressRail(e),t.setCurrentRail(e)},!1),s.loaded=r,s.total=o,s.current=u,s.handle=a},setProgressRail:function(e){var t=e!=undefined?e.target:this.media,n=null;t&&t.buffered&&t.buffered.length>0&&t.buffered.end&&t.duration?n=t.buffered.end(0)/t.duration:t&&t.bytesTotal!=undefined&&t.bytesTotal>0&&t.bufferedBytes!=undefined?n=t.bufferedBytes/t.bytesTotal:e&&e.lengthComputable&&e.total!=0&&(n=e.loaded/e.total),n!==null&&(n=Math.min(1,Math.max(0,n)),this.loaded&&this.total&&this.loaded.width(this.total.width()*n))},setCurrentRail:function(){if(this.media.currentTime!=undefined&&this.media.duration&&this.total&&this.handle){var e=Math.round(this.total.width()*this.media.currentTime/this.media.duration),t=e-Math.round(this.handle.outerWidth(!0)/2);this.current.width(e),this.handle.css("left",t)}}})}(mejs.$),function(e){e.extend(mejs.MepDefaults,{duration:-1,timeAndDurationSeparator:"<span> | </span>"}),e.extend(MediaElementPlayer.prototype,{buildcurrent:function(t,n,r,i){e('<div class="mejs-time"><span class="mejs-currenttime">'+(t.options.alwaysShowHours?"00:":"")+(t.options.showTimecodeFrameCount?"00:00:00":"00:00")+"</span></div>").appendTo(n),this.currenttime=this.controls.find(".mejs-currenttime"),i.addEventListener("timeupdate",function(){t.updateCurrent()},!1)},buildduration:function(t,n,r,i){n.children().last().find(".mejs-currenttime").length>0?e(this.options.timeAndDurationSeparator+'<span class="mejs-duration">'+(this.options.duration>0?mejs.Utility.secondsToTimeCode(this.options.duration,this.options.alwaysShowHours||this.media.duration>3600,this.options.showTimecodeFrameCount,this.options.framesPerSecond||25):(t.options.alwaysShowHours?"00:":"")+(t.options.showTimecodeFrameCount?"00:00:00":"00:00"))+"</span>").appendTo(n.find(".mejs-time")):(n.find(".mejs-currenttime").parent().addClass("mejs-currenttime-container"),e('<div class="mejs-time mejs-duration-container"><span class="mejs-duration">'+(this.options.duration>0?mejs.Utility.secondsToTimeCode(this.options.duration,this.options.alwaysShowHours||this.media.duration>3600,this.options.showTimecodeFrameCount,this.options.framesPerSecond||25):(t.options.alwaysShowHours?"00:":"")+(t.options.showTimecodeFrameCount?"00:00:00":"00:00"))+"</span></div>").appendTo(n)),this.durationD=this.controls.find(".mejs-duration"),i.addEventListener("timeupdate",function(){t.updateDuration()},!1)},updateCurrent:function(){this.currenttime&&this.currenttime.html(mejs.Utility.secondsToTimeCode(this.media.currentTime,this.options.alwaysShowHours||this.media.duration>3600,this.options.showTimecodeFrameCount,this.options.framesPerSecond||25))},updateDuration:function(){this.container.toggleClass("mejs-long-video",this.media.duration>3600),this.durationD&&(this.options.duration>0||this.media.duration)&&this.durationD.html(mejs.Utility.secondsToTimeCode(this.options.duration>0?this.options.duration:this.media.duration,this.options.alwaysShowHours,this.options.showTimecodeFrameCount,this.options.framesPerSecond||25))}})}(mejs.$),function(e){e.extend(mejs.MepDefaults,{muteText:mejs.i18n.t("Mute Toggle"),hideVolumeOnTouchDevices:!0,audioVolume:"horizontal",videoVolume:"vertical"}),e.extend(MediaElementPlayer.prototype,{buildvolume:function(t,n,r,i){if(!mejs.MediaFeatures.hasTouch||!this.options.hideVolumeOnTouchDevices){var s=this,o=s.isVideo?s.options.videoVolume:s.options.audioVolume,u=o=="horizontal"?e('<div class="mejs-button mejs-volume-button mejs-mute"><button type="button" aria-controls="'+s.id+'" title="'+s.options.muteText+'" aria-label="'+s.options.muteText+'"></button></div><div class="mejs-horizontal-volume-slider"><div class="mejs-horizontal-volume-total"></div><div class="mejs-horizontal-volume-current"></div><div class="mejs-horizontal-volume-handle"></div></div>').appendTo(n):e('<div class="mejs-button mejs-volume-button mejs-mute"><button type="button" aria-controls="'+s.id+'" title="'+s.options.muteText+'" aria-label="'+s.options.muteText+'"></button><div class="mejs-volume-slider"><div class="mejs-volume-total"></div><div class="mejs-volume-current"></div><div class="mejs-volume-handle"></div></div></div>').appendTo(n),a=s.container.find(".mejs-volume-slider, .mejs-horizontal-volume-slider"),l=s.container.find(".mejs-volume-total, .mejs-horizontal-volume-total"),c=s.container.find(".mejs-volume-current, .mejs-horizontal-volume-current"),h=s.container.find(".mejs-volume-handle, .mejs-horizontal-volume-handle"),p=function(e,t){if(!a.is(":visible")&&typeof t=="undefined")a.show(),p(e,!0),a.hide();else{e=Math.max(0,e),e=Math.min(e,1),e==0?u.removeClass("mejs-mute").addClass("mejs-unmute"):u.removeClass("mejs-unmute").addClass("mejs-mute");if(o=="vertical"){var n=l.height(),r=l.position(),i=n-n*e;h.css("top",Math.round(r.top+i-h.height()/2)),c.height(n-i),c.css("top",r.top+i)}else n=l.width(),r=l.position(),n*=e,h.css("left",Math.round(r.left+n-h.width()/2)),c.width(Math.round(n))}},d=function(e){var t=null,n=l.offset();if(o=="vertical"){t=l.height(),parseInt(l.css("top").replace(/px/,""),10),t=(t-(e.pageY-n.top))/t;if(n.top==0||n.left==0)return}else t=l.width(),t=(e.pageX-n.left)/t;t=Math.max(0,t),t=Math.min(t,1),p(t),t==0?i.setMuted(!0):i.setMuted(!1),i.setVolume(t)},v=!1,m=!1;u.hover(function(){a.show(),m=!0},function(){m=!1,!v&&o=="vertical"&&a.hide()}),a.bind("mouseover",function(){m=!0}).bind("mousedown",function(e){return d(e),s.globalBind("mousemove.vol",function(e){d(e)}),s.globalBind("mouseup.vol",function(){v=!1,s.globalUnbind(".vol"),!m&&o=="vertical"&&a.hide()}),v=!0,!1}),u.find("button").click(function(){i.setMuted(!i.muted)}),i.addEventListener("volumechange",function(){v||(i.muted?(p(0),u.removeClass("mejs-mute").addClass("mejs-unmute")):(p(i.volume),u.removeClass("mejs-unmute").addClass("mejs-mute")))},!1),s.container.is(":visible")&&(p(t.options.startVolume),t.options.startVolume===0&&i.setMuted(!0),i.pluginType==="native"&&i.setVolume(t.options.startVolume))}}})}(mejs.$),function(e){e.extend(mejs.MepDefaults,{usePluginFullScreen:!0,newWindowCallback:function(){return""},fullscreenText:mejs.i18n.t("Fullscreen")}),e.extend(MediaElementPlayer.prototype,{isFullScreen:!1,isNativeFullScreen:!1,isInIframe:!1,buildfullscreen:function(t,n,r,i){if(t.isVideo){t.isInIframe=window.location!=window.parent.location,mejs.MediaFeatures.hasTrueNativeFullScreen&&(r=function(){t.isFullScreen&&(mejs.MediaFeatures.isFullScreen()?(t.isNativeFullScreen=!0,t.setControlsSize()):(t.isNativeFullScreen=!1,t.exitFullScreen()))},mejs.MediaFeatures.hasMozNativeFullScreen?t.globalBind(mejs.MediaFeatures.fullScreenEventName,r):t.container.bind(mejs.MediaFeatures.fullScreenEventName,r));var s=this,o=e('<div class="mejs-button mejs-fullscreen-button"><button type="button" aria-controls="'+s.id+'" title="'+s.options.fullscreenText+'" aria-label="'+s.options.fullscreenText+'"></button></div>').appendTo(n);if(s.media.pluginType==="native"||!s.options.usePluginFullScreen&&!mejs.MediaFeatures.isFirefox)o.click(function(){mejs.MediaFeatures.hasTrueNativeFullScreen&&mejs.MediaFeatures.isFullScreen()||t.isFullScreen?t.exitFullScreen():t.enterFullScreen()});else{var u=null;if(function(){var e=document.createElement("x"),t=document.documentElement,n=window.getComputedStyle;return"pointerEvents"in e.style?(e.style.pointerEvents="auto",e.style.pointerEvents="x",t.appendChild(e),n=n&&n(e,"").pointerEvents==="auto",t.removeChild(e),!!n):!1}()&&!mejs.MediaFeatures.isOpera){var a=!1,l=function(){if(a){for(var e in c)c[e].hide();o.css("pointer-events",""),s.controls.css("pointer-events",""),s.media.removeEventListener("click",s.clickToPlayPauseCallback),a=!1}},c={};n=["top","left","right","bottom"];var h,p=function(){var e=o.offset().left-s.container.offset().left,t=o.offset().top-s.container.offset().top,n=o.outerWidth(!0),r=o.outerHeight(!0),i=s.container.width(),u=s.container.height();for(h in c)c[h].css({position:"absolute",top:0,left:0});c.top.width(i).height(t),c.left.width(e).height(r).css({top:t}),c.right.width(i-e-n).height(r).css({top:t,left:e+n}),c.bottom.width(i).height(u-r-t).css({top:t+r})};s.globalBind("resize",function(){p()}),h=0;for(r=n.length;h<r;h++)c[n[h]]=e('<div class="mejs-fullscreen-hover" />').appendTo(s.container).mouseover(l).hide();o.on("mouseover",function(){if(!s.isFullScreen){var e=o.offset(),n=t.container.offset();i.positionFullscreenButton(e.left-n.left,e.top-n.top,!1),o.css("pointer-events","none"),s.controls.css("pointer-events","none"),s.media.addEventListener("click",s.clickToPlayPauseCallback);for(h in c)c[h].show();p(),a=!0}}),i.addEventListener("fullscreenchange",function(){s.isFullScreen=!s.isFullScreen,s.isFullScreen?s.media.removeEventListener("click",s.clickToPlayPauseCallback):s.media.addEventListener("click",s.clickToPlayPauseCallback),l()}),s.globalBind("mousemove",function(e){if(a){var t=o.offset();if(e.pageY<t.top||e.pageY>t.top+o.outerHeight(!0)||e.pageX<t.left||e.pageX>t.left+o.outerWidth(!0))o.css("pointer-events",""),s.controls.css("pointer-events",""),a=!1}})}else o.on("mouseover",function(){u!==null&&(clearTimeout(u),delete u);var e=o.offset(),n=t.container.offset();i.positionFullscreenButton(e.left-n.left,e.top-n.top,!0)}).on("mouseout",function(){u!==null&&(clearTimeout(u),delete u),u=setTimeout(function(){i.hideFullscreenButton()},1500)})}t.fullscreenBtn=o,s.globalBind("keydown",function(e){(mejs.MediaFeatures.hasTrueNativeFullScreen&&mejs.MediaFeatures.isFullScreen()||s.isFullScreen)&&e.keyCode==27&&t.exitFullScreen()})}},cleanfullscreen:function(e){e.exitFullScreen()},containerSizeTimeout:null,enterFullScreen:function(){var t=this;if(t.media.pluginType==="native"||!mejs.MediaFeatures.isFirefox&&!t.options.usePluginFullScreen){e(document.documentElement).addClass("mejs-fullscreen"),normalHeight=t.container.height(),normalWidth=t.container.width();if(t.media.pluginType==="native")if(mejs.MediaFeatures.hasTrueNativeFullScreen)mejs.MediaFeatures.requestFullScreen(t.container[0]),t.isInIframe&&setTimeout(function r(){t.isNativeFullScreen&&(e(window).width()!==screen.width?t.exitFullScreen():setTimeout(r,500))},500);else if(mejs.MediaFeatures.hasSemiNativeFullScreen){t.media.webkitEnterFullscreen();return}if(t.isInIframe){var n=t.options.newWindowCallback(this);if(n!==""){if(!mejs.MediaFeatures.hasTrueNativeFullScreen){t.pause(),window.open(n,t.id,"top=0,left=0,width="+screen.availWidth+",height="+screen.availHeight+",resizable=yes,scrollbars=no,status=no,toolbar=no");return}setTimeout(function(){t.isNativeFullScreen||(t.pause(),window.open(n,t.id,"top=0,left=0,width="+screen.availWidth+",height="+screen.availHeight+",resizable=yes,scrollbars=no,status=no,toolbar=no"))},250)}}t.container.addClass("mejs-container-fullscreen").width("100%").height("100%"),t.containerSizeTimeout=setTimeout(function(){t.container.css({width:"100%",height:"100%"}),t.setControlsSize()},500),t.media.pluginType==="native"?t.$media.width("100%").height("100%"):(t.container.find(".mejs-shim").width("100%").height("100%"),t.media.setVideoSize(e(window).width(),e(window).height())),t.layers.children("div").width("100%").height("100%"),t.fullscreenBtn&&t.fullscreenBtn.removeClass("mejs-fullscreen").addClass("mejs-unfullscreen"),t.setControlsSize(),t.isFullScreen=!0}},exitFullScreen:function(){clearTimeout(this.containerSizeTimeout),this.media.pluginType!=="native"&&mejs.MediaFeatures.isFirefox?this.media.setFullscreen(!1):(mejs.MediaFeatures.hasTrueNativeFullScreen&&(mejs.MediaFeatures.isFullScreen()||this.isFullScreen)&&mejs.MediaFeatures.cancelFullScreen(),e(document.documentElement).removeClass("mejs-fullscreen"),this.container.removeClass("mejs-container-fullscreen").width(normalWidth).height(normalHeight),this.media.pluginType==="native"?this.$media.width(normalWidth).height(normalHeight):(this.container.find(".mejs-shim").width(normalWidth).height(normalHeight),this.media.setVideoSize(normalWidth,normalHeight)),this.layers.children("div").width(normalWidth).height(normalHeight),this.fullscreenBtn.removeClass("mejs-unfullscreen").addClass("mejs-fullscreen"),this.setControlsSize(),this.isFullScreen=!1)}})}(mejs.$),function(e){e.extend(mejs.MepDefaults,{startLanguage:"",tracksText:mejs.i18n.t("Captions/Subtitles"),hideCaptionsButtonWhenEmpty:!0,toggleCaptionsButtonWhenOnlyOne:!1,slidesSelector:""}),e.extend(MediaElementPlayer.prototype,{hasChapters:!1,buildtracks:function(t,n,r,i){if(t.tracks.length!=0){var s;if(this.domNode.textTracks)for(s=this.domNode.textTracks.length-1;s>=0;s--)this.domNode.textTracks[s].mode="hidden";t.chapters=e('<div class="mejs-chapters mejs-layer"></div>').prependTo(r).hide(),t.captions=e('<div class="mejs-captions-layer mejs-layer"><div class="mejs-captions-position mejs-captions-position-hover"><span class="mejs-captions-text"></span></div></div>').prependTo(r).hide(),t.captionsText=t.captions.find(".mejs-captions-text"),t.captionsButton=e('<div class="mejs-button mejs-captions-button"><button type="button" aria-controls="'+this.id+'" title="'+this.options.tracksText+'" aria-label="'+this.options.tracksText+'"></button><div class="mejs-captions-selector"><ul><li><input type="radio" name="'+t.id+'_captions" id="'+t.id+'_captions_none" value="none" checked="checked" /><label for="'+t.id+'_captions_none">'+mejs.i18n.t("None")+"</label></li></ul></div></div>").appendTo(n);for(s=n=0;s<t.tracks.length;s++)t.tracks[s].kind=="subtitles"&&n++;this.options.toggleCaptionsButtonWhenOnlyOne&&n==1?t.captionsButton.on("click",function(){t.setTrack(t.selectedTrack==null?t.tracks[0].srclang:"none")}):t.captionsButton.hover(function(){e(this).find(".mejs-captions-selector").css("visibility","visible")},function(){e(this).find(".mejs-captions-selector").css("visibility","hidden")}).on("click","input[type=radio]",function(){lang=this.value,t.setTrack(lang)}),t.options.alwaysShowControls?t.container.find(".mejs-captions-position").addClass("mejs-captions-position-hover"):t.container.bind("controlsshown",function(){t.container.find(".mejs-captions-position").addClass("mejs-captions-position-hover")}).bind("controlshidden",function(){i.paused||t.container.find(".mejs-captions-position").removeClass("mejs-captions-position-hover")}),t.trackToLoad=-1,t.selectedTrack=null,t.isLoadingTrack=!1;for(s=0;s<t.tracks.length;s++)t.tracks[s].kind=="subtitles"&&t.addTrackButton(t.tracks[s].srclang,t.tracks[s].label);t.loadNextTrack(),i.addEventListener("timeupdate",function(){t.displayCaptions()},!1),t.options.slidesSelector!=""&&(t.slidesContainer=e(t.options.slidesSelector),i.addEventListener("timeupdate",function(){t.displaySlides()},!1)),i.addEventListener("loadedmetadata",function(){t.displayChapters()},!1),t.container.hover(function(){t.hasChapters&&(t.chapters.css("visibility","visible"),t.chapters.fadeIn(200).height(t.chapters.find(".mejs-chapter").outerHeight()))},function(){t.hasChapters&&!i.paused&&t.chapters.fadeOut(200,function(){e(this).css("visibility","hidden"),e(this).css("display","block")})}),t.node.getAttribute("autoplay")!==null&&t.chapters.css("visibility","hidden")}},setTrack:function(e){var t;if(e=="none")this.selectedTrack=null,this.captionsButton.removeClass("mejs-captions-enabled");else for(t=0;t<this.tracks.length;t++)if(this.tracks[t].srclang==e){this.selectedTrack==null&&this.captionsButton.addClass("mejs-captions-enabled"),this.selectedTrack=this.tracks[t],this.captions.attr("lang",this.selectedTrack.srclang),this.displayCaptions();break}},loadNextTrack:function(){this.trackToLoad++,this.trackToLoad<this.tracks.length?(this.isLoadingTrack=!0,this.loadTrack(this.trackToLoad)):(this.isLoadingTrack=!1,this.checkForTracks())},loadTrack:function(t){var n=this,r=n.tracks[t];e.ajax({url:r.src,dataType:"text",success:function(e){r.entries=typeof e=="string"&&/<tt\s+xml/ig.exec(e)?mejs.TrackFormatParser.dfxp.parse(e):mejs.TrackFormatParser.webvvt.parse(e),r.isLoaded=!0,n.enableTrackButton(r.srclang,r.label),n.loadNextTrack(),r.kind=="chapters"&&n.media.addEventListener("play",function(){n.media.duration>0&&n.displayChapters(r)},!1),r.kind=="slides"&&n.setupSlides(r)},error:function(){n.loadNextTrack()}})},enableTrackButton:function(t,n){n===""&&(n=mejs.language.codes[t]||t),this.captionsButton.find("input[value="+t+"]").prop("disabled",!1).siblings("label").html(n),this.options.startLanguage==t&&e("#"+this.id+"_captions_"+t).click(),this.adjustLanguageBox()},addTrackButton:function(t,n){n===""&&(n=mejs.language.codes[t]||t),this.captionsButton.find("ul").append(e('<li><input type="radio" name="'+this.id+'_captions" id="'+this.id+"_captions_"+t+'" value="'+t+'" disabled="disabled" /><label for="'+this.id+"_captions_"+t+'">'+n+" (loading)</label></li>")),this.adjustLanguageBox(),this.container.find(".mejs-captions-translations option[value="+t+"]").remove()},adjustLanguageBox:function(){this.captionsButton.find(".mejs-captions-selector").height(this.captionsButton.find(".mejs-captions-selector ul").outerHeight(!0)+this.captionsButton.find(".mejs-captions-translations").outerHeight(!0))},checkForTracks:function(){var e=!1;if(this.options.hideCaptionsButtonWhenEmpty){for(i=0;i<this.tracks.length;i++)if(this.tracks[i].kind=="subtitles"){e=!0;break}e||(this.captionsButton.hide(),this.setControlsSize())}},displayCaptions:function(){if(typeof this.tracks!="undefined"){var e,t=this.selectedTrack;if(t!=null&&t.isLoaded)for(e=0;e<t.entries.times.length;e++)if(this.media.currentTime>=t.entries.times[e].start&&this.media.currentTime<=t.entries.times[e].stop){this.captionsText.html(t.entries.text[e]),this.captions.show().height(0);return}this.captions.hide()}},setupSlides:function(e){this.slides=e,this.slides.entries.imgs=[this.slides.entries.text.length],this.showSlide(0)},showSlide:function(t){if(typeof this.tracks!="undefined"&&typeof this.slidesContainer!="undefined"){var n=this,r=n.slides.entries.text[t],i=n.slides.entries.imgs[t];typeof i=="undefined"||typeof i.fadeIn=="undefined"?n.slides.entries.imgs[t]=i=e('<img src="'+r+'">').on("load",function(){i.appendTo(n.slidesContainer).hide().fadeIn().siblings(":visible").fadeOut()}):!i.is(":visible")&&!i.is(":animated")&&i.fadeIn().siblings(":visible").fadeOut()}},displaySlides:function(){if(typeof this.slides!="undefined"){var e=this.slides,t;for(t=0;t<e.entries.times.length;t++)if(this.media.currentTime>=e.entries.times[t].start&&this.media.currentTime<=e.entries.times[t].stop){this.showSlide(t);break}}},displayChapters:function(){var e;for(e=0;e<this.tracks.length;e++)if(this.tracks[e].kind=="chapters"&&this.tracks[e].isLoaded){this.drawChapters(this.tracks[e]),this.hasChapters=!0;break}},drawChapters:function(t){var n=this,r,i,s=i=0;n.chapters.empty();for(r=0;r<t.entries.times.length;r++){i=t.entries.times[r].stop-t.entries.times[r].start,i=Math.floor(i/n.media.duration*100);if(i+s>100||r==t.entries.times.length-1&&i+s<100)i=100-s;n.chapters.append(e('<div class="mejs-chapter" rel="'+t.entries.times[r].start+'" style="left: '+s.toString()+"%;width: "+i.toString()+'%;"><div class="mejs-chapter-block'+(r==t.entries.times.length-1?" mejs-chapter-block-last":"")+'"><span class="ch-title">'+t.entries.text[r]+'</span><span class="ch-time">'+mejs.Utility.secondsToTimeCode(t.entries.times[r].start)+"&ndash;"+mejs.Utility.secondsToTimeCode(t.entries.times[r].stop)+"</span></div></div>")),s+=i}n.chapters.find("div.mejs-chapter").click(function(){n.media.setCurrentTime(parseFloat(e(this).attr("rel"))),n.media.paused&&n.media.play()}),n.chapters.show()}}),mejs.language={codes:{af:"Afrikaans",sq:"Albanian",ar:"Arabic",be:"Belarusian",bg:"Bulgarian",ca:"Catalan",zh:"Chinese","zh-cn":"Chinese Simplified","zh-tw":"Chinese Traditional",hr:"Croatian",cs:"Czech",da:"Danish",nl:"Dutch",en:"English",et:"Estonian",tl:"Filipino",fi:"Finnish",fr:"French",gl:"Galician",de:"German",el:"Greek",ht:"Haitian Creole",iw:"Hebrew",hi:"Hindi",hu:"Hungarian",is:"Icelandic",id:"Indonesian",ga:"Irish",it:"Italian",ja:"Japanese",ko:"Korean",lv:"Latvian",lt:"Lithuanian",mk:"Macedonian",ms:"Malay",mt:"Maltese",no:"Norwegian",fa:"Persian",pl:"Polish",pt:"Portuguese",ro:"Romanian",ru:"Russian",sr:"Serbian",sk:"Slovak",sl:"Slovenian",es:"Spanish",sw:"Swahili",sv:"Swedish",tl:"Tagalog",th:"Thai",tr:"Turkish",uk:"Ukrainian",vi:"Vietnamese",cy:"Welsh",yi:"Yiddish"}},mejs.TrackFormatParser={webvvt:{pattern_identifier:/^([a-zA-z]+-)?[0-9]+$/,pattern_timecode:/^([0-9]{2}:[0-9]{2}:[0-9]{2}([,.][0-9]{1,3})?) --\> ([0-9]{2}:[0-9]{2}:[0-9]{2}([,.][0-9]{3})?)(.*)$/,parse:function(t){var n=0;t=mejs.TrackFormatParser.split2(t,/\r?\n/);for(var r={text:[],times:[]},i,s;n<t.length;n++)if(this.pattern_identifier.exec(t[n])){n++;if((i=this.pattern_timecode.exec(t[n]))&&n<t.length){n++,s=t[n];for(n++;t[n]!==""&&n<t.length;)s=s+"\n"+t[n],n++;s=e.trim(s).replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig,"<a href='$1' target='_blank'>$1</a>"),r.text.push(s),r.times.push({start:mejs.Utility.convertSMPTEtoSeconds(i[1])==0?.2:mejs.Utility.convertSMPTEtoSeconds(i[1]),stop:mejs.Utility.convertSMPTEtoSeconds(i[3]),settings:i[5]})}}return r}},dfxp:{parse:function(t){t=e(t).filter("tt");var n=0;n=t.children("div").eq(0);var r=n.find("p");n=t.find("#"+n.attr("style"));var i,s;t={text:[],times:[]};if(n.length){s=n.removeAttr("id").get(0).attributes;if(s.length){i={};for(n=0;n<s.length;n++)i[s[n].name.split(":")[1]]=s[n].value}}for(n=0;n<r.length;n++){var o;s={start:null,stop:null,style:null},r.eq(n).attr("begin")&&(s.start=mejs.Utility.convertSMPTEtoSeconds(r.eq(n).attr("begin"))),!s.start&&r.eq(n-1).attr("end")&&(s.start=mejs.Utility.convertSMPTEtoSeconds(r.eq(n-1).attr("end"))),r.eq(n).attr("end")&&(s.stop=mejs.Utility.convertSMPTEtoSeconds(r.eq(n).attr("end"))),!s.stop&&r.eq(n+1).attr("begin")&&(s.stop=mejs.Utility.convertSMPTEtoSeconds(r.eq(n+1).attr("begin")));if(i){o="";for(var u in i)o+=u+":"+i[u]+";"}o&&(s.style=o),s.start==0&&(s.start=.2),t.times.push(s),s=e.trim(r.eq(n).html()).replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig,"<a href='$1' target='_blank'>$1</a>"),t.text.push(s),t.times.start==0&&(t.times.start=2)}return t}},split2:function(e,t){return e.split(t)}},"x\n\ny".split(/\n/gi).length!=3&&(mejs.TrackFormatParser.split2=function(e,t){var n=[],r="",i;for(i=0;i<e.length;i++)r+=e.substring(i,i+1),t.test(r)&&(n.push(r.replace(t,"")),r="");return n.push(r),n})}(mejs.$),function(e){e.extend(mejs.MepDefaults,{contextMenuItems:[{render:function(e){return typeof e.enterFullScreen=="undefined"?null:e.isFullScreen?mejs.i18n.t("Turn off Fullscreen"):mejs.i18n.t("Go Fullscreen")},click:function(e){e.isFullScreen?e.exitFullScreen():e.enterFullScreen()}},{render:function(e){return e.media.muted?mejs.i18n.t("Unmute"):mejs.i18n.t("Mute")},click:function(e){e.media.muted?e.setMuted(!1):e.setMuted(!0)}},{isSeparator:!0},{render:function(){return mejs.i18n.t("Download Video")},click:function(e){window.location.href=e.media.currentSrc}}]}),e.extend(MediaElementPlayer.prototype,{buildcontextmenu:function(t){t.contextMenu=e('<div class="mejs-contextmenu"></div>').appendTo(e("body")).hide(),t.container.bind("contextmenu",function(e){if(t.isContextMenuEnabled)return e.preventDefault(),t.renderContextMenu(e.clientX-1,e.clientY-1),!1}),t.container.bind("click",function(){t.contextMenu.hide()}),t.contextMenu.bind("mouseleave",function(){t.startContextMenuTimer()})},cleancontextmenu:function(e){e.contextMenu.remove()},isContextMenuEnabled:!0,enableContextMenu:function(){this.isContextMenuEnabled=!0},disableContextMenu:function(){this.isContextMenuEnabled=!1},contextMenuTimeout:null,startContextMenuTimer:function(){var e=this;e.killContextMenuTimer(),e.contextMenuTimer=setTimeout(function(){e.hideContextMenu(),e.killContextMenuTimer()},750)},killContextMenuTimer:function(){var e=this.contextMenuTimer;e!=null&&(clearTimeout(e),delete e)},hideContextMenu:function(){this.contextMenu.hide()},renderContextMenu:function(t,n){for(var r=this,i="",s=r.options.contextMenuItems,o=0,u=s.length;o<u;o++)if(s[o].isSeparator)i+='<div class="mejs-contextmenu-separator"></div>';else{var a=s[o].render(r);a!=null&&(i+='<div class="mejs-contextmenu-item" data-itemindex="'+o+'" id="element-'+Math.random()*1e6+'">'+a+"</div>")}r.contextMenu.empty().append(e(i)).css({top:n,left:t}).show(),r.contextMenu.find(".mejs-contextmenu-item").each(function(){var t=e(this),n=parseInt(t.data("itemindex"),10),i=r.options.contextMenuItems[n];typeof i.show!="undefined"&&i.show(t,r),t.click(function(){typeof i.click!="undefined"&&i.click(r),r.contextMenu.hide()})}),setTimeout(function(){r.killControlsTimer("rev3")},100)}})}(mejs.$),function(e){e.extend(mejs.MepDefaults,{postrollCloseText:mejs.i18n.t("Close")}),e.extend(MediaElementPlayer.prototype,{buildpostroll:function(t,n,r){var i=this.container.find('link[rel="postroll"]').attr("href");typeof i!="undefined"&&(t.postroll=e('<div class="mejs-postroll-layer mejs-layer"><a class="mejs-postroll-close" onclick="$(this).parent().hide();return false;">'+this.options.postrollCloseText+'</a><div class="mejs-postroll-layer-content"></div></div>').prependTo(r).hide(),this.media.addEventListener("ended",function(){e.ajax({dataType:"html",url:i,success:function(e){r.find(".mejs-postroll-layer-content").html(e)}}),t.postroll.show()},!1))}})}(mejs.$),define("mediaelementjs",["jquery"],function(){}),define("interaction_view/model/preload",["interaction_view/model/base","text!interaction_view/template/preload.js","mediaelementjs"],function(){var e=require("text!interaction_view/template/preload.js");interaction_view.model.Preload=interaction_view.model.Base.extend({defaults:{iType:"Preload",iLock:!0,iVisibility:!0,iCommon:null,iDetail:null,iParent:"",iChild:"",iOptions:{createfocus:!0},iParentModel:null,iDraggable:!0,iResizable:!0,iTemplate:null,iParentdiv:".interaction-view",iAutoindex:!0,iSync:!1,iZindex:"-1",iUrl:null,iAutofocus:!1,iKeyscontrol:!0,callback:null,loaded:!1},setcollection:function(){this.pageid=this.get("pageid");if(this.get("pagetype")=="LayerRef"){var e=this.get("parentpageid"),t=this.get("layerid"),n=interaction_view.ipagelist.getPage(e)||interaction_view.imasterlist.get(e);this.page=n.iOverlaylist.get(this.pageid).layer[t]}else this.page=interaction_view.ipagelist.getPage(this.pageid)||interaction_view.imasterlist.get(this.pageid);this.page.ipreloadlist.get(this.id)||this.page.ipreloadlist.add(this)},setview:function(e){this.pageid=this.get("pageid");if(this.get("pagetype")=="LayerRef"){var t=this.get("parentpageid"),n=this.get("layerid"),r=interaction_view.ipagelist.getPage(t)||interaction_view.imasterlist.get(t);this.page=r.iOverlaylist.get(this.pageid).layer[n]}else this.page=interaction_view.ipagelist.getPage(this.pageid)||interaction_view.imasterlist.get(this.pageid);this.iview=new interaction_view.view.Preload({model:this})},setsyncmodel:function(){}}),interaction_view.collection.Preload=interaction_view.collection.Base.extend({preloadcheck:function(e,t,n){var r=this.where({loaded:!0});t==0&&(console.log("file:"+e+" load failed!"),interaction_view.message("alert","图像或媒体资源加载失败,可能会影响动画效果")),n.iview.afterpreload(e);if(this.where({loaded:false}).length==0)if(this.pagetype=="LayerRef"){var i=this.parentpageid,s=this.layerid,o=interaction_view.ipagelist.getPage(i)||interaction_view.imasterlist.get(i);refmodel=o.iOverlaylist.get(this.pageid),refmodel.iview.afterlayerload(s)}else interaction_view.finishPagePreload(this.pageid);interaction_view.setPreloadStatus&&interaction_view.setPreloadStatus()},preload:function(){this.each(function(e){e.iview.render()})}}),interaction_view.view.Preload=interaction_view.view.Base.extend({events:{},initstart:function(){$("div#preloader").append(_.template(e,{id:this.model.id,file:null}))},renderDynamicElement:function(){},render:function(){var e=this,t=this.elementmodel=e.model.page.iOverlaylist.get(this.model.get("overlay_id"));this.model.get("elementtype")=="Audio"?(console.info("Audio"),this.audioPreload()):this.model.get("elementtype")=="Video"?this.videoPreload():this.model.get("elementtype")=="LayerRef"||this.model.get("elementtype")=="LayerSlide"?this.layerPreload(this.model):$('img[id="'+this.model.id+'"]').load(function(){e.model.set("loaded",!0),e.model.page.ipreloadlist.preloadcheck(e.model.toJSON().file,!0,t)}).error(function(){e.model.set("loaded",!0),e.model.page.ipreloadlist.preloadcheck(e.model.toJSON().file,!1,t)}).attr("src",e.model.toJSON().file)},audioPreload:function(){var e=this,t=this.elementmodel,n=this.elementmodel.iview.getdetail(),r=n.iRepeat||!1,i=t.autoplay=n.iAutoplay||!1,s="Audio_"+e.model.id+this.elementmodel.id,o=this.model.toJSON().file;t.loaded=!1,$("div#preloader").append('<audio id="'+s+'" src="'+o+'"></audio>'),options={enablePluginDebug:!1,type:"",pluginPath:web_url+"common/js/mediaelementjs/",flashName:"flashmediaelement.swf",silverlightName:"silverlightmediaelement.xap",timerRate:100,pauseOtherPlayers:!1,features:[],loop:r,success:function(n,i){t.media=n,n.play();var s=!1;n.addEventListener("loadeddata",function(r){s||(n.pause(),s=!0,t.loaded=!0,console.info("audio loaded"),e.model.set("loaded",!0),e.model.page.ipreloadlist.preloadcheck(e.model.toJSON().file,!0,t))},!1),n.addEventListener("ended",function(e){r||(t.media.setCurrentTime(0),t.media.pause())},!1),n.addEventListener("timeupdate",function(e){console.log("time update")},!1)},error:function(){t.loaded=!1,e.model.set("loaded",!0),e.model.page.ipreloadlist.preloadcheck(e.model.toJSON().file,!1,t)}};if(_g.string.getUrlExt(o)==".m4a"||_g.string.getUrlExt(o)==".M4A")options.pluginVars="isvideo=true";options.plugins=["flash","silverlight"],$("#Audio_"+e.model.id+this.elementmodel.id).mediaelementplayer(options)},videoPreload:function(){var e=this,t=this.elementmodel,n=this.elementmodel.iview.getdetail(),r=n.iRepeat||!1,i=n.iControl||!1,s=t.iview.getcommon(),o=t.autoplay=n.iAutoplay||!1;$("#Video_"+this.elementmodel.id).attr("id","Video_"+e.model.id+this.elementmodel.id),t.videoloaded=!1;var u=n.iAutohide;u==null&&(u=!0),options={enablePluginDebug:!1,type:"",pluginPath:web_url+"common/js/mediaelementjs/",flashName:"flashmediaelement.swf",silverlightName:"silverlightmediaelement.xap",videoWidth:s.iWidth,videoHeight:s.iHeight,pluginWidth:-1,pluginHeight:-1,timerRate:100,pauseOtherPlayers:!1,features:i?["playpause","progress","current","duration","volume","fullscreen"]:[],loop:r,success:function(n,s){t.media=n,n.play();var a=!1;i||(t.iview.$el.find(".mejs-controls").addClass("hide"),t.iview.$el.find(".mejs-overlay-button").addClass("hide")),n.addEventListener("loadedmetadata",function(r){a||(a=!0,n.pause(),n.setCurrentTime(0),o||t.iview.$el.addClass("hide"),t.iview.$el.css("opacity",""),t.videoloaded=!0,console.info("video loaded"),t.iview.$el.children(".iVideo").removeClass("unloaded"),t.loaded=!0,e.model.set("loaded",!0),e.model.page.ipreloadlist.preloadcheck(e.model.toJSON().file,!0,t))},!1),n.addEventListener("ended",function(e){r||(n.setCurrentTime(0),n.pause(),u&&(t.iview.$el.addClass("hide"),t.hided=!0))},!1),n.addEventListener("timeupdate",function(e){console.log("time update")},!1)},error:function(){t.loaded=!1,e.model.set("loaded",!0),e.model.page.ipreloadlist.preloadcheck(e.model.toJSON().file,!1,t)}},options.plugins=["flash","silverlight"],t.iview.$el.removeClass("hide").css("opacity",0),$("#Video_"+e.model.id+this.elementmodel.id).mediaelementplayer(options)},layerPreload:function(){this.elementmodel.iview.loadLayer(this.model)},canPlayVideo:function(e){var t=document.createElement("video"),n,r,i,s;return t.canPlayType?(n=""!==t.canPlayType('video/mp4; codecs="mp4v.20.8"'),r=""!==(t.canPlayType('video/mp4; codecs="avc1.42E01E"')||t.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"')),i=""!==t.canPlayType('video/ogg; codecs="theora"'),s=""!==t.canPlayType('video/webm; codecs="vp8, vorbis"'),n||r?!0:!1):!1}}),interaction_view.ipreloadlist=new interaction_view.collection.Preload}),define("interaction_view/model/richtext",["interaction_view/model/base"],function(){interaction_view.model.RichText=interaction_view.model.Base.extend({defaults:{iType:"RichText",iLock:!0,iVisibility:!0,iCommon:{portait:{iStartx:400,iStarty:200,iWidth:200,iHeight:200},landscape:{iStartx:400,iStarty:200,iWidth:200,iHeight:200}},iDetail:{iAdapt:!1,iFullview:!1,iImg:null,iAnimation:[]},iParent:"",iChild:"",iOptions:{createfocus:!0},iParentModel:null,iDraggable:!0,iResizable:!0,iTemplate:null,iParentdiv:".interaction-view",iAutoindex:!1,iSync:!1,iZindex:"-1",iUrl:null,iAutofocus:!1,iKeyscontrol:!0,callback:null},setcollection:function(){iOverlaylist.get(this.id)||iOverlaylist.add(this)},setview:function(e){this.iview=new interaction_view.view.RichText({model:this})},setsyncmodel:function(){}}),interaction_view.view.RichText=interaction_view.view.Base.extend({events:{},render:function(e){interaction_view.setscrollnano(this.$el)}})}),define("interaction_view/model/slide",["interaction_view/model/base"],function(){interaction_view.model.Slide=interaction_view.model.Base.extend({defaults:{iType:"Slide",iLock:!0,iVisibility:!0,iCommon:{portait:{iStartx:400,iStarty:200,iWidth:200,iHeight:200},landscape:{iStartx:400,iStarty:200,iWidth:200,iHeight:200}},iDetail:{},iParent:"",iChild:"",iOptions:{createfocus:!0},iParentModel:null,iDraggable:!0,iResizable:!0,iTemplate:null,iParentdiv:".interaction-view",iAutoindex:!1,iSync:!1,iZindex:"-1",iUrl:null,iAutofocus:!1,iKeyscontrol:!0,callback:null,iBackground:"rgba(62,189,255,0.5)",iResourcesProperties:[{id:"iImg",type:"single"}],iAnimationProperties:[{id:"iAnimation",type:"object"}]},setcollection:function(){iOverlaylist.get(this.id)||iOverlaylist.add(this)},setview:function(e){this.iview=new interaction_view.view.Slide({model:this})},setsyncmodel:function(){}}),interaction_view.view.Slide=interaction_view.view.Base.extend({events:{},render:function(e){var t=this,n=this.getdetail();this.currentSlideIndex=null,this.model.on("slideTo",function(e){if(t.currentSlideIndex!=null&&t.currentSlideIndex==e)return!1;t.preloaded&&(interaction_view.events.onChangeTo(t.model.get("pageid"),t.model.id,e),t.currentSlideIndex=e)})},preload:function(){var e=this,t=this.getdetail(),n;this.checkImglist=_.pluck(t.iImg,"picture"),this.preloaded=!1,t.iImg&&_.each(t.iImg,function(t){_g.getUrlParameterByName("-playmode")=="1"?n=t.thumbnail:n=t.picture,e.sendToPreload({file:n})})},checkImgload:function(e){return this.checkImglist=_.reject(this.checkImglist,function(t){return t==e}),this.checkImglist.length==0?!0:!1},afterpreload:function(e){if(e&&this.preloaded)return;e&&(this.preloaded=this.checkImgload(e)),this.preloaded&&(this.playAnimation(),this.setZindex(),this.setElementDisplay(),this.copyelstyle=this.$el.attr("style"),this.copyelementstyle=this.$el.children(".iElement").attr("style"),this.$el.children(".Element").on("mousewheel",function(e){var t=e.wheelDelta;t>0?console.log("up"):console.log("down")}))},playAnimation:function(){var e=this,t=0,n=this.getdetail(),r=n.iSlidetype;this.delay=Number(n.iInterval)||2,this.autoplay=n.iAutoplay;var i=n.iRepeat?-1:0;this.iFade=n.iFade||0,this.timeline=new TimelineMax({paused:!0,repeat:i,onComplete:this.setRewind()}),this.slideel=e.$el.children(".Element").find(".slidecontent").first(),this.slidelength=n.iImg.length,this.repeat=i,this.iRewind=n.iRewind,this.slipable=n.iSlipable,this.setTimeline(),this.autoplay?this.timeline.play(0):this.setSlideDisplay(0),this.onChangeSlideTo(0),this.slipable&&(this.control(),this.autoplay||this.$el.attr("data-iSlipable",!0))},setTimeline:function(){if(this.iFade=="Fade"||0)this.setFade();else if(this.iFade=="Slip")this.setSlip();else{if(this.iFade!="None")return;this.setNone()}this.slideel.children().first().css({opacity:1,left:0,top:0}).nextAll().css("opacity",0)},testControl:function(){return!0},resetOtherStatus:function(){if(!this.slideel)return;this.slideel.children().first().css({opacity:1,left:0,top:0});var e=this.getdetail();this.autoplay=e.iAutoplay,this.currentIndex=0,this.timeline&&(this.timeline.pause(1e-5),this.autoplay?this.timeline.play(0):this.setSlideDisplay(0))}})}),define("interaction_view/model/video",["interaction_view/model/base"],function(){interaction_view.model.Video=interaction_view.model.Base.extend({defaults:{iType:"Video",iLock:!0,iVisibility:!0,iCommon:{portait:{iStartx:400,iStarty:200,iWidth:200,iHeight:200},landscape:{iStartx:400,iStarty:200,iWidth:200,iHeight:200}},iDetail:{iAdapt:!1,iFullview:!1,iImg:null,iAnimation:[]},iParent:"",iChild:"",iOptions:{createfocus:!0},iParentModel:null,iDraggable:!0,iResizable:!0,iTemplate:null,iParentdiv:".interaction-view",iAutoindex:!1,iSync:!1,iZindex:"-1",iUrl:null,iAutofocus:!1,iKeyscontrol:!0,callback:null,iBackground:"rgba(62,189,255,0.5)",iResourcesProperties:[{id:"iImg",type:"single"}],iAnimationProperties:[{id:"iAnimation",type:"object"}]},setcollection:function(){iOverlaylist.get(this.id)||iOverlaylist.add(this)},setview:function(e){this.iview=new interaction_view.view.Video({model:this})},setsyncmodel:function(){},getFile:function(){var e=this.get("iDetail");return e.iFile&&e.iFile[0]?e.iFile[0].file:null}}),interaction_view.view.Video=interaction_view.view.Base.extend({events:{},render:function(e){this.afterpreload()},preload:function(){var e=this.getdetail();if(e.iFile&&e.iFile[0]){var t=e.iFile[0].file||e.iFile[0].content;this.sendToPreload({file:t})}},resetOtherStatus:function(){this.model.hided||this.model.media.setCurrentTime(0)}})}),define("interaction_view/model/button",["interaction_view/model/base"],function(){interaction_view.model.Button=interaction_view.model.Base.extend({defaults:{iType:"Button",iVisibility:!0,iCommon:null,iDetail:null,iOptions:{createfocus:!0},iParentModel:null,iDraggable:!0,iResizable:!0,iTemplate:null,iParentdiv:".interaction-view",iAutoindex:!1,iSync:!1,iZindex:"-1",iUrl:null,iAutofocus:!1,iKeyscontrol:!0},setcollection:function(){iOverlaylist.get(this.id)||iOverlaylist.add(this)},setview:function(e){this.iview=new interaction_view.view.Button({model:this})},setsyncmodel:function(){}}),interaction_view.view.Button=interaction_view.view.Base.extend({events:{},render:function(e){},preload:function(){this.preloaded=!1,this.checkImglist=[];var e=this.getdetail();e.iconNormal&&e.iconNormal[0]&&(this.checkImglist.push(e.iconNormal[0].picture),this.sendToPreload({file:e.iconNormal[0].picture})),e.iconActive&&e.iconActive[0]&&(this.checkImglist.push(e.iconActive[0].picture),this.sendToPreload({file:e.iconActive[0].picture}))},checkImgload:function(e){return this.checkImglist=_.reject(this.checkImglist,function(t){return t==e}),this.checkImglist.length==0?!0:!1},afterpreload:function(e){if(e&&this.preloaded)return;e&&!this.preloaded&&(this.preloaded=this.checkImgload(e)),this.preloaded&&(this.setZindex(),this.setElementDisplay(),this.setOtherDisplay(),this.copyelstyle=this.$el.attr("style"),this.copyelementstyle=this.$el.children(".iElement").attr("style"))},setOtherDisplay:function(){this.active=!1,this.buttonon=!1;var e=this;this.$el.css("cursor","pointer");var t=this.getdetail();t.isSwitch?this.$el.on("click",function(t){e.changeStatus()}):(this.$el.on("mousedown",function(t){e.buttonon=!0,e.changeStatus()}),this.$el.on("mouseup",function(t){e.buttonon&&(e.buttonon=!1,t.stopPropagation(),e.changeStatus(),e.$el.trigger("click"))}))},changeStatus:function(){var e=this.getdetail(),t=this;if(!t.active)t.$el.find("img.iconActive").show(),t.$el.find("img.iconNormal").hide(),t.active=!0;else{if(t.groupcontrol&&e.isSwitch)return;t.$el.find("img.iconActive").hide(),t.$el.find("img.iconNormal").show(),t.active=!1}},resetOtherStatus:function(){this.resetButtonStatus()},resetButtonStatus:function(){this.$el.find("img.iconActive").hide(),this.$el.find("img.iconNormal").show(),this.active=!1}})}),define("interaction_view/model/map",["interaction_view/model/base"],function(){interaction_view.model.Map=interaction_view.model.Base.extend({defaults:{iType:"Map",iLock:!0,iVisibility:!0,iCommon:{portait:{iStartx:400,iStarty:200,iWidth:200,iHeight:200},landscape:{iStartx:400,iStarty:200,iWidth:200,iHeight:200}},iDetail:{iAdapt:!1,iFullview:!1,iImg:null,iAnimation:[]},iParent:"",iChild:"",iOptions:{createfocus:!0},iParentModel:null,iDraggable:!0,iResizable:!0,iTemplate:null,iParentdiv:".interaction-view",iAutoindex:!1,iSync:!1,iZindex:"-1",iUrl:null,iAutofocus:!1,iKeyscontrol:!0,callback:null},setcollection:function(){iOverlaylist.get(this.id)||iOverlaylist.add(this)},setview:function(e){this.iview=new interaction_view.view.Map({model:this})},setsyncmodel:function(){}}),interaction_view.view.Map=interaction_view.view.Base.extend({events:{},render:function(e){this.afterpreload()}})}),define("interaction_view/model/pay",["interaction_view/model/base"],function(){interaction_view.model.Pay=interaction_view.model.Base.extend({defaults:{iType:"Pay",iLock:!0,iVisibility:!0,iCommon:{portait:{iStartx:400,iStarty:200,iWidth:200,iHeight:200},landscape:{iStartx:400,iStarty:200,iWidth:200,iHeight:200}},iDetail:{iAdapt:!1,iFullview:!1,iImg:null,iAnimation:[]},iParent:"",iChild:"",iOptions:{createfocus:!0},iParentModel:null,iDraggable:!0,iResizable:!0,iTemplate:null,iParentdiv:".interaction-view",iAutoindex:!1,iSync:!1,iZindex:"-1",iUrl:null,iAutofocus:!1,iKeyscontrol:!0,callback:null},setcollection:function(){iOverlaylist.get(this.id)||iOverlaylist.add(this)},setview:function(e){this.iview=new interaction_view.view.Pay({model:this})},setsyncmodel:function(){}}),interaction_view.view.Pay=interaction_view.view.Base.extend({events:{},render:function(e){this.afterpreload()}})}),define("interaction_view/model/link",["interaction_view/model/base"],function(){interaction_view.model.Link=interaction_view.model.Base.extend({defaults:{iType:"Link",iLock:!0,iVisibility:!0,iCommon:{portait:{iStartx:400,iStarty:200,iWidth:200,iHeight:200},landscape:{iStartx:400,iStarty:200,iWidth:200,iHeight:200}},iDetail:{},iParent:"",iChild:"",iOptions:{createfocus:!0},iParentModel:null,iDraggable:!0,iResizable:!0,iTemplate:null,iParentdiv:".interaction-view",iAutoindex:!1,iSync:!1,iZindex:"-1",iUrl:null,iAutofocus:!1,iKeyscontrol:!0,callback:null},setcollection:function(){iOverlaylist.get(this.id)||iOverlaylist.add(this)},setview:function(e){this.iview=new interaction_view.view.Link({model:this})},setsyncmodel:function(){}}),interaction_view.view.Link=interaction_view.view.Base.extend({events:{},render:function(e){}})}),define("interaction_view/view/layer",["interaction_view/view/page"],function(){var e=require("interaction_view/view/page"),t=$.extend({},e,{template:null,className:null,containment:null,wrap:null,wrapClassName:null,autoRender:!1,position:1,parseData:null,afterload:function(){var e=this,t=this.model.get("iDetail").layer_ids;if(!t||t.length==0)return;_.each(t,function(t){var n=interaction_view.ilayerlist.get(t);if(!n)return;e.animations=_.map(n.animations,function(n){return n.pageid=e.model.id,n.parentpageid=e.model.get("pageid"),n.pagetype="LayerRef",n.layerid=t,n}),e.model.layer[t].iAnimationlist.reset(e.animations),overlays=_.filter(n.overlays,function(n){return n.pageid=e.model.id,n.parentpageid=e.model.get("pageid"),n.pagetype="LayerRef",n.layerid=t,interaction_view.model[n.iType]}),overlays=_.map(overlays,function(e){return new interaction_view.model[e.iType](e)}),e.model.layer[t].iOverlaylist.reset(overlays),e.model.layer[t].iOverlaylist.each(function(e){e.iview.setZindex()}),e.actions=_.map(n.actions,function(n){return n.pageid=e.model.id,n.parentpageid=e.model.get("pageid"),n.pagetype="LayerRef",n.layerid=t,n}),e.model.layer[t].iActionlist.reset(n.actions)}),e.startLayerLoad()},startLayerLoad:function(){var e=this;_.each(this.model.layer,function(t,n){t.ipreloadlist.length==0?e.model.iview.afterlayerload(n):t.ipreloadlist.preload()})}});return t}),function(e,t){function n(t,n){var i,s,o,u=t.nodeName.toLowerCase();return"area"===u?(i=t.parentNode,s=i.name,!t.href||!s||i.nodeName.toLowerCase()!=="map"?!1:(o=e("img[usemap=#"+s+"]")[0],!!o&&r(o))):(/input|select|textarea|button|object/.test(u)?!t.disabled:"a"===u?t.href||n:n)&&r(t)}function r(t){return e.expr.filters.visible(t)&&!e(t).parents().andSelf().filter(function(){return e.css(this,"visibility")==="hidden"}).length}var i=0,s=/^ui-id-\d+$/;e.ui=e.ui||{};if(e.ui.version)return;e.extend(e.ui,{version:"1.9.2",keyCode:{BACKSPACE:8,COMMA:188,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SPACE:32,TAB:9,UP:38}}),e.fn.extend({_focus:e.fn.focus,focus:function(t,n){return typeof t=="number"?this.each(function(){var r=this;setTimeout(function(){e(r).focus(),n&&n.call(r)},t)}):this._focus.apply(this,arguments)},scrollParent:function(){var t;return e.ui.ie&&/(static|relative)/.test(this.css("position"))||/absolute/.test(this.css("position"))?t=this.parents().filter(function(){return/(relative|absolute|fixed)/.test(e.css(this,"position"))&&/(auto|scroll)/.test(e.css(this,"overflow")+e.css(this,"overflow-y")+e.css(this,"overflow-x"))}).eq(0):t=this.parents().filter(function(){return/(auto|scroll)/.test(e.css(this,"overflow")+e.css(this,"overflow-y")+e.css(this,"overflow-x"))}).eq(0),/fixed/.test(this.css("position"))||!t.length?e(document):t},zIndex:function(n){if(n!==t)return this.css("zIndex",n);if(this.length){var r=e(this[0]),i,s;while(r.length&&r[0]!==document){i=r.css("position");if(i==="absolute"||i==="relative"||i==="fixed"){s=parseInt(r.css("zIndex"),10);if(!isNaN(s)&&s!==0)return s}r=r.parent()}}return 0},uniqueId:function(){return this.each(function(){this.id||(this.id="ui-id-"+ ++i)})},removeUniqueId:function(){return this.each(function(){s.test(this.id)&&e(this).removeAttr("id")})}}),e.extend(e.expr[":"],{data:e.expr.createPseudo?e.expr.createPseudo(function(t){return function(n){return!!e.data(n,t)}}):function(t,n,r){return!!e.data(t,r[3])},focusable:function(t){return n(t,!isNaN(e.attr(t,"tabindex")))},tabbable:function(t){var r=e.attr(t,"tabindex"),i=isNaN(r);return(i||r>=0)&&n(t,!i)}}),e(function(){var t=document.body,n=t.appendChild(n=document.createElement("div"));n.offsetHeight,e.extend(n.style,{minHeight:"100px",height:"auto",padding:0,borderWidth:0}),e.support.minHeight=n.offsetHeight===100,e.support.selectstart="onselectstart"in n,t.removeChild(n).style.display="none"}),e("<a>").outerWidth(1).jquery||e.each(["Width","Height"],function(n,r){function i(t,n,r,i){return e.each(s,function(){n-=parseFloat(e.css(t,"padding"+this))||0,r&&(n-=parseFloat(e.css(t,"border"+this+"Width"))||0),i&&(n-=parseFloat(e.css(t,"margin"+this))||0)}),n}var s=r==="Width"?["Left","Right"]:["Top","Bottom"],o=r.toLowerCase(),u={innerWidth:e.fn.innerWidth,innerHeight:e.fn.innerHeight,outerWidth:e.fn.outerWidth,outerHeight:e.fn.outerHeight};e.fn["inner"+r]=function(n){return n===t?u["inner"+r].call(this):this.each(function(){e(this).css(o,i(this,n)+"px")})},e.fn["outer"+r]=function(t,n){return typeof t!="number"?u["outer"+r].call(this,t):this.each(function(){e(this).css(o,i(this,t,!0,n)+"px")})}}),e("<a>").data("a-b","a").removeData("a-b").data("a-b")&&(e.fn.removeData=function(t){return function(n){return arguments.length?t.call(this,e.camelCase(n)):t.call(this)}}(e.fn.removeData)),function(){var t=/msie ([\w.]+)/.exec(navigator.userAgent.toLowerCase())||[];e.ui.ie=t.length?!0:!1,e.ui.ie6=parseFloat(t[1],10)===6}(),e.fn.extend({disableSelection:function(){return this.bind((e.support.selectstart?"selectstart":"mousedown")+".ui-disableSelection",function(e){e.preventDefault()})},enableSelection:function(){return this.unbind(".ui-disableSelection")}}),e.extend(e.ui,{plugin:{add:function(t,n,r){var i,s=e.ui[t].prototype;for(i in r)s.plugins[i]=s.plugins[i]||[],s.plugins[i].push([n,r[i]])},call:function(e,t,n){var r,i=e.plugins[t];if(!i||!e.element[0].parentNode||e.element[0].parentNode.nodeType===11)return;for(r=0;r<i.length;r++)e.options[i[r][0]]&&i[r][1].apply(e.element,n)}},contains:e.contains,hasScroll:function(t,n){if(e(t).css("overflow")==="hidden")return!1;var r=n&&n==="left"?"scrollLeft":"scrollTop",i=!1;return t[r]>0?!0:(t[r]=1,i=t[r]>0,t[r]=0,i)},isOverAxis:function(e,t,n){return e>t&&e<t+n},isOver:function(t,n,r,i,s,o){return e.ui.isOverAxis(t,r,s)&&e.ui.isOverAxis(n,i,o)}})}(jQuery),function(e,t){var n=0,r=Array.prototype.slice,i=e.cleanData;e.cleanData=function(t){for(var n=0,r;(r=t[n])!=null;n++)try{e(r).triggerHandler("remove")}catch(s){}i(t)},e.widget=function(t,n,r){var i,s,o,u,a=t.split(".")[0];t=t.split(".")[1],i=a+"-"+t,r||(r=n,n=e.Widget),e.expr[":"][i.toLowerCase()]=function(t){return!!e.data(t,i)},e[a]=e[a]||{},s=e[a][t],o=e[a][t]=function(e,t){if(!this._createWidget)return new o(e,t);arguments.length&&this._createWidget(e,t)},e.extend(o,s,{version:r.version,_proto:e.extend({},r),_childConstructors:[]}),u=new n,u.options=e.widget.extend({},u.options),e.each(r,function(t,i){e.isFunction(i)&&(r[t]=function(){var e=function(){return n.prototype[t].apply(this,arguments)},r=function(e){return n.prototype[t].apply(this,e)};return function(){var t=this._super,n=this._superApply,s;return this._super=e,this._superApply=r,s=i.apply(this,arguments),this._super=t,this._superApply=n,s}}())}),o.prototype=e.widget.extend(u,{widgetEventPrefix:s?u.widgetEventPrefix:t},r,{constructor:o,namespace:a,widgetName:t,widgetBaseClass:i,widgetFullName:i}),s?(e.each(s._childConstructors,function(t,n){var r=n.prototype;e.widget(r.namespace+"."+r.widgetName,o,n._proto)}),delete s._childConstructors):n._childConstructors.push(o),e.widget.bridge(t,o)},e.widget.extend=function(n){var i=r.call(arguments,1),s=0,o=i.length,u,a;for(;s<o;s++)for(u in i[s])a=i[s][u],i[s].hasOwnProperty(u)&&a!==t&&(e.isPlainObject(a)?n[u]=e.isPlainObject(n[u])?e.widget.extend({},n[u],a):e.widget.extend({},a):n[u]=a);return n},e.widget.bridge=function(n,i){var s=i.prototype.widgetFullName||n;e.fn[n]=function(o){var u=typeof o=="string",a=r.call(arguments,1),f=this;return o=!u&&a.length?e.widget.extend.apply(null,[o].concat(a)):o,u?this.each(function(){var r,i=e.data(this,s);if(!i)return e.error("cannot call methods on "+n+" prior to initialization; "+"attempted to call method '"+o+"'");if(!e.isFunction(i[o])||o.charAt(0)==="_")return e.error("no such method '"+o+"' for "+n+" widget instance");r=i[o].apply(i,a);if(r!==i&&r!==t)return f=r&&r.jquery?f.pushStack(r.get()):r,!1}):this.each(function(){var t=e.data(this,s);t?t.option(o||{})._init():e.data(this,s,new i(o,this))}),f}},e.Widget=function(){},e.Widget._childConstructors=[],e.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",defaultElement:"<div>",options:{disabled:!1,create:null},_createWidget:function(t,r){r=e(r||this.defaultElement||this)[0],this.element=e(r),this.uuid=n++,this.eventNamespace="."+this.widgetName+this.uuid,this.options=e.widget.extend({},this.options,this._getCreateOptions(),t),this.bindings=e(),this.hoverable=e(),this.focusable=e(),r!==this&&(e.data(r,this.widgetName,this),e.data(r,this.widgetFullName,this),this._on(!0,this.element,{remove:function(e){e.target===r&&this.destroy()}}),this.document=e(r.style?r.ownerDocument:r.document||r),this.window=e(this.document[0].defaultView||this.document[0].parentWindow)),this._create(),this._trigger("create",null,this._getCreateEventData()),this._init()},_getCreateOptions:e.noop,_getCreateEventData:e.noop,_create:e.noop,_init:e.noop,destroy:function(){this._destroy(),this.element.unbind(this.eventNamespace).removeData(this.widgetName).removeData(this.widgetFullName).removeData(e.camelCase(this.widgetFullName)),this.widget().unbind(this.eventNamespace).removeAttr("aria-disabled").removeClass(this.widgetFullName+"-disabled "+"ui-state-disabled"),this.bindings.unbind(this.eventNamespace),this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus")},_destroy:e.noop,widget:function(){return this.element},option:function(n,r){var i=n,s,o,u;if(arguments.length===0)return e.widget.extend({},this.options);if(typeof n=="string"){i={},s=n.split("."),n=s.shift();if(s.length){o=i[n]=e.widget.extend({},this.options[n]);for(u=0;u<s.length-1;u++)o[s[u]]=o[s[u]]||{},o=o[s[u]];n=s.pop();if(r===t)return o[n]===t?null:o[n];o[n]=r}else{if(r===t)return this.options[n]===t?null:this.options[n];i[n]=r}}return this._setOptions(i),this},_setOptions:function(e){var t;for(t in e)this._setOption(t,e[t]);return this},_setOption:function(e,t){return this.options[e]=t,e==="disabled"&&(this.widget().toggleClass(this.widgetFullName+"-disabled ui-state-disabled",!!t).attr("aria-disabled",t),this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus")),this},enable:function(){return this._setOption("disabled",!1)},disable:function(){return this._setOption("disabled",!0)},_on:function(t,n,r){var i,s=this;typeof t!="boolean"&&(r=n,n=t,t=!1),r?(n=i=e(n),this.bindings=this.bindings.add(n)):(r=n,n=this.element,i=this.widget()),e.each(r,function(r,o){function u(){if(!t&&(s.options.disabled===!0||e(this).hasClass("ui-state-disabled")))return;return(typeof o=="string"?s[o]:o).apply(s,arguments)}typeof o!="string"&&(u.guid=o.guid=o.guid||u.guid||e.guid++);var a=r.match(/^(\w+)\s*(.*)$/),f=a[1]+s.eventNamespace,l=a[2];l?i.delegate(l,f,u):n.bind(f,u)})},_off:function(e,t){t=(t||"").split(" ").join(this.eventNamespace+" ")+this.eventNamespace,e.unbind(t).undelegate(t)},_delay:function(e,t){function n(){return(typeof e=="string"?r[e]:e).apply(r,arguments)}var r=this;return setTimeout(n,t||0)},_hoverable:function(t){this.hoverable=this.hoverable.add(t),this._on(t,{mouseenter:function(t){e(t.currentTarget).addClass("ui-state-hover")},mouseleave:function(t){e(t.currentTarget).removeClass("ui-state-hover")}})},_focusable:function(t){this.focusable=this.focusable.add(t),this._on(t,{focusin:function(t){e(t.currentTarget).addClass("ui-state-focus")},focusout:function(t){e(t.currentTarget).removeClass("ui-state-focus")}})},_trigger:function(t,n,r){var i,s,o=this.options[t];r=r||{},n=e.Event(n),n.type=(t===this.widgetEventPrefix?t:this.widgetEventPrefix+t).toLowerCase(),n.target=this.element[0],s=n.originalEvent;if(s)for(i in s)i in n||(n[i]=s[i]);return this.element.trigger(n,r),!(e.isFunction(o)&&o.apply(this.element[0],[n].concat(r))===!1||n.isDefaultPrevented())}},e.each({show:"fadeIn",hide:"fadeOut"},function(t,n){e.Widget.prototype["_"+t]=function(r,i,s){typeof i=="string"&&(i={effect:i});var o,u=i?i===!0||typeof i=="number"?n:i.effect||n:t;i=i||{},typeof i=="number"&&(i={duration:i}),o=!e.isEmptyObject(i),i.complete=s,i.delay&&r.delay(i.delay),o&&e.effects&&(e.effects.effect[u]||e.uiBackCompat!==!1&&e.effects[u])?r[t](i):u!==t&&r[u]?r[u](i.duration,i.easing,s):r.queue(function(n){e(this)[t](),s&&s.call(r[0]),n()})}}),e.uiBackCompat!==!1&&(e.Widget.prototype._getCreateOptions=function(){return e.metadata&&e.metadata.get(this.element[0])[this.widgetName]})}(jQuery),function(e,t){var n=!1;e(document).mouseup(function(e){n=!1}),e.widget("ui.mouse",{version:"1.9.2",options:{cancel:"input,textarea,button,select,option",distance:1,delay:0},_mouseInit:function(){var t=this;this.element.bind("mousedown."+this.widgetName,function(e){return t._mouseDown(e)}).bind("click."+this.widgetName,function(n){if(!0===e.data(n.target,t.widgetName+".preventClickEvent"))return e.removeData(n.target,t.widgetName+".preventClickEvent"),n.stopImmediatePropagation(),!1}),this.started=!1},_mouseDestroy:function(){this.element.unbind("."+this.widgetName),this._mouseMoveDelegate&&e(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate)},_mouseDown:function(t){if(n)return;this._mouseStarted&&this._mouseUp(t),this._mouseDownEvent=t;var r=this,i=t.which===1,s=typeof this.options.cancel=="string"&&t.target.nodeName?e(t.target).closest(this.options.cancel).length:!1;if(!i||s||!this._mouseCapture(t))return!0;this.mouseDelayMet=!this.options.delay,this.mouseDelayMet||(this._mouseDelayTimer=setTimeout(function(){r.mouseDelayMet=!0},this.options.delay));if(this._mouseDistanceMet(t)&&this._mouseDelayMet(t)){this._mouseStarted=this._mouseStart(t)!==!1;if(!this._mouseStarted)return t.preventDefault(),!0}return!0===e.data(t.target,this.widgetName+".preventClickEvent")&&e.removeData(t.target,this.widgetName+".preventClickEvent"),this._mouseMoveDelegate=function(e){return r._mouseMove(e)},this._mouseUpDelegate=function(e){return r._mouseUp(e)},e(document).bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate),t.preventDefault(),n=!0,!0},_mouseMove:function(t){return!e.ui.ie||document.documentMode>=9||!!t.button?this._mouseStarted?(this._mouseDrag(t),t.preventDefault()):(this._mouseDistanceMet(t)&&this._mouseDelayMet(t)&&(this._mouseStarted=this._mouseStart(this._mouseDownEvent,t)!==!1,this._mouseStarted?this._mouseDrag(t):this._mouseUp(t)),!this._mouseStarted):this._mouseUp(t)},_mouseUp:function(t){return e(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate),this._mouseStarted&&(this._mouseStarted=!1,t.target===this._mouseDownEvent.target&&e.data(t.target,this.widgetName+".preventClickEvent",!0),this._mouseStop(t)),!1},_mouseDistanceMet:function(e){return Math.max(Math.abs(this._mouseDownEvent.pageX-e.pageX),Math.abs(this._mouseDownEvent.pageY-e.pageY))>=this.options.distance},_mouseDelayMet:function(e){return this.mouseDelayMet},_mouseStart:function(e){},_mouseDrag:function(e){},_mouseStop:function(e){},_mouseCapture:function(e){return!0}})}(jQuery),function(e,t){function n(e,t,n){return[parseInt(e[0],10)*(h.test(e[0])?t/100:1),parseInt(e[1],10)*(h.test(e[1])?n/100:1)]}function r(t,n){return parseInt(e.css(t,n),10)||0}e.ui=e.ui||{};var i,s=Math.max,o=Math.abs,u=Math.round,a=/left|center|right/,f=/top|center|bottom/,l=/[\+\-]\d+%?/,c=/^\w+/,h=/%$/,p=e.fn.position;e.position={scrollbarWidth:function(){if(i!==t)return i;var n,r,s=e("<div style='display:block;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>"),o=s.children()[0];return e("body").append(s),n=o.offsetWidth,s.css("overflow","scroll"),r=o.offsetWidth,n===r&&(r=s[0].clientWidth),s.remove(),i=n-r},getScrollInfo:function(t){var n=t.isWindow?"":t.element.css("overflow-x"),r=t.isWindow?"":t.element.css("overflow-y"),i=n==="scroll"||n==="auto"&&t.width<t.element[0].scrollWidth,s=r==="scroll"||r==="auto"&&t.height<t.element[0].scrollHeight;return{width:i?e.position.scrollbarWidth():0,height:s?e.position.scrollbarWidth():0}},getWithinInfo:function(t){var n=e(t||window),r=e.isWindow(n[0]);return{element:n,isWindow:r,offset:n.offset()||{left:0,top:0},scrollLeft:n.scrollLeft(),scrollTop:n.scrollTop(),width:r?n.width():n.outerWidth(),height:r?n.height():n.outerHeight()}}},e.fn.position=function(t){if(!t||!t.of)return p.apply(this,arguments);t=e.extend({},t);var i,h,d,v,m,g=e(t.of),y=e.position.getWithinInfo(t.within),b=e.position.getScrollInfo(y),w=g[0],E=(t.collision||"flip").split(" "),S={};return w.nodeType===9?(h=g.width(),d=g.height(),v={top:0,left:0}):e.isWindow(w)?(h=g.width(),d=g.height(),v={top:g.scrollTop(),left:g.scrollLeft()}):w.preventDefault?(t.at="left top",h=d=0,v={top:w.pageY,left:w.pageX}):(h=g.outerWidth(),d=g.outerHeight(),v=g.offset()),m=e.extend({},v),e.each(["my","at"],function(){var e=(t[this]||"").split(" "),n,r;e.length===1&&(e=a.test(e[0])?e.concat(["center"]):f.test(e[0])?["center"].concat(e):["center","center"]),e[0]=a.test(e[0])?e[0]:"center",e[1]=f.test(e[1])?e[1]:"center",n=l.exec(e[0]),r=l.exec(e[1]),S[this]=[n?n[0]:0,r?r[0]:0],t[this]=[c.exec(e[0])[0],c.exec(e[1])[0]]}),E.length===1&&(E[1]=E[0]),t.at[0]==="right"?m.left+=h:t.at[0]==="center"&&(m.left+=h/2),t.at[1]==="bottom"?m.top+=d:t.at[1]==="center"&&(m.top+=d/2),i=n(S.at,h,d),m.left+=i[0],m.top+=i[1],this.each(function(){var a,f,l=e(this),c=l.outerWidth(),p=l.outerHeight(),w=r(this,"marginLeft"),x=r(this,"marginTop"),T=c+w+r(this,"marginRight")+b.width,N=p+x+r(this,"marginBottom")+b.height,C=e.extend({},m),k=n(S.my,l.outerWidth(),l.outerHeight());t.my[0]==="right"?C.left-=c:t.my[0]==="center"&&(C.left-=c/2),t.my[1]==="bottom"?C.top-=p:t.my[1]==="center"&&(C.top-=p/2),C.left+=k[0],C.top+=k[1],e.support.offsetFractions||(C.left=u(C.left),C.top=u(C.top)),a={marginLeft:w,marginTop:x},e.each(["left","top"],function(n,r){e.ui.position[E[n]]&&e.ui.position[E[n]][r](C,{targetWidth:h,targetHeight:d,elemWidth:c,elemHeight:p,collisionPosition:a,collisionWidth:T,collisionHeight:N,offset:[i[0]+k[0],i[1]+k[1]],my:t.my,at:t.at,within:y,elem:l})}),e.fn.bgiframe&&l.bgiframe(),t.using&&(f=function(e){var n=v.left-C.left,r=n+h-c,i=v.top-C.top,u=i+d-p,a={target:{element:g,left:v.left,top:v.top,width:h,height:d},element:{element:l,left:C.left,top:C.top,width:c,height:p},horizontal:r<0?"left":n>0?"right":"center",vertical:u<0?"top":i>0?"bottom":"middle"};h<c&&o(n+r)<h&&(a.horizontal="center"),d<p&&o(i+u)<d&&(a.vertical="middle"),s(o(n),o(r))>s(o(i),o(u))?a.important="horizontal":a.important="vertical",t.using.call(this,e,a)}),l.offset(e.extend(C,{using:f}))})},e.ui.position={fit:{left:function(e,t){var n=t.within,r=n.isWindow?n.scrollLeft:n.offset.left,i=n.width,o=e.left-t.collisionPosition.marginLeft,u=r-o,a=o+t.collisionWidth-i-r,f;t.collisionWidth>i?u>0&&a<=0?(f=e.left+u+t.collisionWidth-i-r,e.left+=u-f):a>0&&u<=0?e.left=r:u>a?e.left=r+i-t.collisionWidth:e.left=r:u>0?e.left+=u:a>0?e.left-=a:e.left=s(e.left-o,e.left)},top:function(e,t){var n=t.within,r=n.isWindow?n.scrollTop:n.offset.top,i=t.within.height,o=e.top-t.collisionPosition.marginTop,u=r-o,a=o+t.collisionHeight-i-r,f;t.collisionHeight>i?u>0&&a<=0?(f=e.top+u+t.collisionHeight-i-r,e.top+=u-f):a>0&&u<=0?e.top=r:u>a?e.top=r+i-t.collisionHeight:e.top=r:u>0?e.top+=u:a>0?e.top-=a:e.top=s(e.top-o,e.top)}},flip:{left:function(e,t){var n=t.within,r=n.offset.left+n.scrollLeft,i=n.width,s=n.isWindow?n.scrollLeft:n.offset.left,u=e.left-t.collisionPosition.marginLeft,a=u-s,f=u+t.collisionWidth-i-s,l=t.my[0]==="left"?-t.elemWidth:t.my[0]==="right"?t.elemWidth:0,c=t.at[0]==="left"?t.targetWidth:t.at[0]==="right"?-t.targetWidth:0,h=-2*t.offset[0],p,d;if(a<0){p=e.left+l+c+h+t.collisionWidth-i-r;if(p<0||p<o(a))e.left+=l+c+h}else if(f>0){d=e.left-t.collisionPosition.marginLeft+l+c+h-s;if(d>0||o(d)<f)e.left+=l+c+h}},top:function(e,t){var n=t.within,r=n.offset.top+n.scrollTop,i=n.height,s=n.isWindow?n.scrollTop:n.offset.top,u=e.top-t.collisionPosition.marginTop,a=u-s,f=u+t.collisionHeight-i-s,l=t.my[1]==="top",c=l?-t.elemHeight:t.my[1]==="bottom"?t.elemHeight:0,h=t.at[1]==="top"?t.targetHeight:t.at[1]==="bottom"?-t.targetHeight:0,p=-2*t.offset[1],d,v;a<0?(v=e.top+c+h+p+t.collisionHeight-i-r,e.top+c+h+p>a&&(v<0||v<o(a))&&(e.top+=c+h+p)):f>0&&(d=e.top-t.collisionPosition.marginTop+c+h+p-s,e.top+c+h+p>f&&(d>0||o(d)<f)&&(e.top+=c+h+p))}},flipfit:{left:function(){e.ui.position.flip.left.apply(this,arguments),e.ui.position.fit.left.apply(this,arguments)},top:function(){e.ui.position.flip.top.apply(this,arguments),e.ui.position.fit.top.apply(this,arguments)}}},function(){var t,n,r,i,s,o=document.getElementsByTagName("body")[0],u=document.createElement("div");t=document.createElement(o?"div":"body"),r={visibility:"hidden",width:0,height:0,border:0,margin:0,background:"none"},o&&e.extend(r,{position:"absolute",left:"-1000px",top:"-1000px"});for(s in r)t.style[s]=r[s];t.appendChild(u),n=o||document.documentElement,n.insertBefore(t,n.firstChild),u.style.cssText="position: absolute; left: 10.7432222px;",i=e(u).offset().left,e.support.offsetFractions=i>10&&i<11,t.innerHTML="",n.removeChild(t)}(),e.uiBackCompat!==!1&&function(e){var n=e.fn.position;e.fn.position=function(r){if(!r||!r.offset)return n.call(this,r);var i=r.offset.split(" "),s=r.at.split(" ");return i.length===1&&(i[1]=i[0]),/^\d/.test(i[0])&&(i[0]="+"+i[0]),/^\d/.test(i[1])&&(i[1]="+"+i[1]),s.length===1&&(/left|center|right/.test(s[0])?s[1]="center":(s[1]=s[0],s[0]="center")),n.call(this,e.extend(r,{at:s[0]+i[0]+" "+s[1]+i[1],offset:t}))}}(jQuery)}(jQuery),function(e,t){e.widget("ui.draggable",e.ui.mouse,{version:"1.9.2",widgetEventPrefix:"drag",options:{addClasses:!0,appendTo:"parent",axis:!1,connectToSortable:!1,containment:!1,cursor:"auto",cursorAt:!1,grid:!1,handle:!1,helper:"original",iframeFix:!1,opacity:!1,refreshPositions:!1,revert:!1,revertDuration:500,scope:"default",scroll:!0,scrollSensitivity:20,scrollSpeed:20,snap:!1,snapMode:"both",snapTolerance:20,stack:!1,zIndex:!1},_create:function(){this.options.helper=="original"&&!/^(?:r|a|f)/.test(this.element.css("position"))&&(this.element[0].style.position="relative"),this.options.addClasses&&this.element.addClass("ui-draggable"),this.options.disabled&&this.element.addClass("ui-draggable-disabled"),this._mouseInit()},_destroy:function(){this.element.removeClass("ui-draggable ui-draggable-dragging ui-draggable-disabled"),this._mouseDestroy()},_mouseCapture:function(t){var n=this.options;return this.helper||n.disabled||e(t.target).is(".ui-resizable-handle")?!1:(this.handle=this._getHandle(t),this.handle?(e(n.iframeFix===!0?"iframe":n.iframeFix).each(function(){e('<div class="ui-draggable-iframeFix" style="background: #fff;"></div>').css({width:this.offsetWidth+"px",height:this.offsetHeight+"px",position:"absolute",opacity:"0.001",zIndex:1e3}).css(e(this).offset()).appendTo("body")}),!0):!1)},_mouseStart:function(t){var n=this.options;return this.helper=this._createHelper(t),this.helper.addClass("ui-draggable-dragging"),this._cacheHelperProportions(),e.ui.ddmanager&&(e.ui.ddmanager.current=this),this._cacheMargins(),this.cssPosition=this.helper.css("position"),this.scrollParent=this.helper.scrollParent(),this.offset=this.positionAbs=this.element.offset(),this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left},e.extend(this.offset,{click:{left:t.pageX-this.offset.left,top:t.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()}),this.originalPosition=this.position=this._generatePosition(t),this.originalPageX=t.pageX,this.originalPageY=t.pageY,n.cursorAt&&this._adjustOffsetFromHelper(n.cursorAt),n.containment&&this._setContainment(),this._trigger("start",t)===!1?(this._clear(),!1):(this._cacheHelperProportions(),e.ui.ddmanager&&!n.dropBehaviour&&e.ui.ddmanager.prepareOffsets(this,t),this._mouseDrag(t,!0),e.ui.ddmanager&&e.ui.ddmanager.dragStart(this,t),!0)},_mouseDrag:function(t,n){this.position=this._generatePosition(t),this.positionAbs=this._convertPositionTo("absolute");if(!n){var r=this._uiHash();if(this._trigger("drag",t,r)===!1)return this._mouseUp({}),!1;this.position=r.position}if(!this.options.axis||this.options.axis!="y")this.helper[0].style.left=this.position.left+"px";if(!this.options.axis||this.options.axis!="x")this.helper[0].style.top=this.position.top+"px";return e.ui.ddmanager&&e.ui.ddmanager.drag(this,t),!1},_mouseStop:function(t){var n=!1;e.ui.ddmanager&&!this.options.dropBehaviour&&(n=e.ui.ddmanager.drop(this,t)),this.dropped&&(n=this.dropped,this.dropped=!1);var r=this.element[0],i=!1;while(r&&(r=r.parentNode))r==document&&(i=!0);if(!i&&this.options.helper==="original")return!1;if(this.options.revert=="invalid"&&!n||this.options.revert=="valid"&&n||this.options.revert===!0||e.isFunction(this.options.revert)&&this.options.revert.call(this.element,n)){var s=this;e(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){s._trigger("stop",t)!==!1&&s._clear()})}else this._trigger("stop",t)!==!1&&this._clear();return!1},_mouseUp:function(t){return e("div.ui-draggable-iframeFix").each(function(){this.parentNode.removeChild(this)}),e.ui.ddmanager&&e.ui.ddmanager.dragStop(this,t),e.ui.mouse.prototype._mouseUp.call(this,t)},cancel:function(){return this.helper.is(".ui-draggable-dragging")?this._mouseUp({}):this._clear(),this},_getHandle:function(t){var n=!this.options.handle||!e(this.options.handle,this.element).length?!0:!1;return e(this.options.handle,this.element).find("*").andSelf().each(function(){this==t.target&&(n=!0)}),n},_createHelper:function(t){var n=this.options,r=e.isFunction(n.helper)?e(n.helper.apply(this.element[0],[t])):n.helper=="clone"?this.element.clone().removeAttr("id"):this.element;return r.parents("body").length||r.appendTo(n.appendTo=="parent"?this.element[0].parentNode:n.appendTo),r[0]!=this.element[0]&&!/(fixed|absolute)/.test(r.css("position"))&&r.css("position","absolute"),r},_adjustOffsetFromHelper:function(t){typeof t=="string"&&(t=t.split(" ")),e.isArray(t)&&(t={left:+t[0],top:+t[1]||0}),"left"in t&&(this.offset.click.left=t.left+this.margins.left),"right"in t&&(this.offset.click.left=this.helperProportions.width-t.right+this.margins.left),"top"in t&&(this.offset.click.top=t.top+this.margins.top),"bottom"in t&&(this.offset.click.top=this.helperProportions.height-t.bottom+this.margins.top)},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var t=this.offsetParent.offset();this.cssPosition=="absolute"&&this.scrollParent[0]!=document&&e.contains(this.scrollParent[0],this.offsetParent[0])&&(t.left+=this.scrollParent.scrollLeft(),t.top+=this.scrollParent.scrollTop());if(this.offsetParent[0]==document.body||this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()=="html"&&e.ui.ie)t={top:0,left:0};return{top:t.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:t.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if(this.cssPosition=="relative"){var e=this.element.position();return{top:e.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:e.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.element.css("marginLeft"),10)||0,top:parseInt(this.element.css("marginTop"),10)||0,right:parseInt(this.element.css("marginRight"),10)||0,bottom:parseInt(this.element.css("marginBottom"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var t=this.options;t.containment=="parent"&&(t.containment=this.helper[0].parentNode);if(t.containment=="document"||t.containment=="window")this.containment=[t.containment=="document"?0:e(window).scrollLeft()-this.offset.relative.left-this.offset.parent.left,t.containment=="document"?0:e(window).scrollTop()-this.offset.relative.top-this.offset.parent.top,(t.containment=="document"?0:e(window).scrollLeft())+e(t.containment=="document"?document:window).width()-this.helperProportions.width-this.margins.left,(t.containment=="document"?0:e(window).scrollTop())+(e(t.containment=="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top];if(!/^(document|window|parent)$/.test(t.containment)&&t.containment.constructor!=Array){var n=e(t.containment),r=n[0];if(!r)return;var i=n.offset(),s=e(r).css("overflow")!="hidden";this.containment=[(parseInt(e(r).css("borderLeftWidth"),10)||0)+(parseInt(e(r).css("paddingLeft"),10)||0),(parseInt(e(r).css("borderTopWidth"),10)||0)+(parseInt(e(r).css("paddingTop"),10)||0),(s?Math.max(r.scrollWidth,r.offsetWidth):r.offsetWidth)-(parseInt(e(r).css("borderLeftWidth"),10)||0)-(parseInt(e(r).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left-this.margins.right,(s?Math.max(r.scrollHeight,r.offsetHeight):r.offsetHeight)-(parseInt(e(r).css("borderTopWidth"),10)||0)-(parseInt(e(r).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top-this.margins.bottom],this.relative_container=n}else t.containment.constructor==Array&&(this.containment=t.containment)},_convertPositionTo:function(t,n){n||(n=this.position);var r=t=="absolute"?1:-1,i=this.options,s=this.cssPosition!="absolute"||this.scrollParent[0]!=document&&!!e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,o=/(html|body)/i.test(s[0].tagName);return{top:n.top+this.offset.relative.top*r+this.offset.parent.top*r-(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():o?0:s.scrollTop())*r,left:n.left+this.offset.relative.left*r+this.offset.parent.left*r-(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():o?0:s.scrollLeft())*r}},_generatePosition:function(t){var n=this.options,r=this.cssPosition!="absolute"||this.scrollParent[0]!=document&&!!e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,i=/(html|body)/i.test(r[0].tagName),s=t.pageX,o=t.pageY;if(this.originalPosition){var u;if(this.containment){if(this.relative_container){var a=this.relative_container.offset();u=[this.containment[0]+a.left,this.containment[1]+a.top,this.containment[2]+a.left,this.containment[3]+a.top]}else u=this.containment;t.pageX-this.offset.click.left<u[0]&&(s=u[0]+this.offset.click.left),t.pageY-this.offset.click.top<u[1]&&(o=u[1]+this.offset.click.top),t.pageX-this.offset.click.left>u[2]&&(s=u[2]+this.offset.click.left),t.pageY-this.offset.click.top>u[3]&&(o=u[3]+this.offset.click.top)}if(n.grid){var f=n.grid[1]?this.originalPageY+Math.round((o-this.originalPageY)/n.grid[1])*n.grid[1]:this.originalPageY;o=u?f-this.offset.click.top<u[1]||f-this.offset.click.top>u[3]?f-this.offset.click.top<u[1]?f+n.grid[1]:f-n.grid[1]:f:f;var l=n.grid[0]?this.originalPageX+Math.round((s-this.originalPageX)/n.grid[0])*n.grid[0]:this.originalPageX;s=u?l-this.offset.click.left<u[0]||l-this.offset.click.left>u[2]?l-this.offset.click.left<u[0]?l+n.grid[0]:l-n.grid[0]:l:l}}return{top:o-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():i?0:r.scrollTop()),left:s-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():i?0:r.scrollLeft())}},_clear:function(){this.helper.removeClass("ui-draggable-dragging"),this.helper[0]!=this.element[0]&&!this.cancelHelperRemoval&&this.helper.remove(),this.helper=null,this.cancelHelperRemoval=!1},_trigger:function(t,n,r){return r=r||this._uiHash(),e.ui.plugin.call(this,t,[n,r]),t=="drag"&&(this.positionAbs=this._convertPositionTo("absolute")),e.Widget.prototype._trigger.call(this,t,n,r)},plugins:{},_uiHash:function(e){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs}}}),e.ui.plugin.add("draggable","connectToSortable",{start:function(t,n){var r=e(this).data("draggable"),i=r.options,s=e.extend({},n,{item:r.element});r.sortables=[],e(i.connectToSortable).each(function(){var n=e.data(this,"sortable");n&&!n.options.disabled&&(r.sortables.push({instance:n,shouldRevert:n.options.revert}),n.refreshPositions(),n._trigger("activate",t,s))})},stop:function(t,n){var r=e(this).data("draggable"),i=e.extend({},n,{item:r.element});e.each(r.sortables,function(){this.instance.isOver?(this.instance.isOver=0,r.cancelHelperRemoval=!0,this.instance.cancelHelperRemoval=!1,this.shouldRevert&&(this.instance.options.revert=!0),this.instance._mouseStop(t),this.instance.options.helper=this.instance.options._helper,r.options.helper=="original"&&this.instance.currentItem.css({top:"auto",left:"auto"})):(this.instance.cancelHelperRemoval=!1,this.instance._trigger("deactivate",t,i))})},drag:function(t,n){var r=e(this).data("draggable"),i=this,s=function(t){var n=this.offset.click.top,r=this.offset.click.left,i=this.positionAbs.top,s=this.positionAbs.left,o=t.height,u=t.width,a=t.top,f=t.left;return e.ui.isOver(i+n,s+r,a,f,o,u)};e.each(r.sortables,function(s){var o=!1,u=this;this.instance.positionAbs=r.positionAbs,this.instance.helperProportions=r.helperProportions,this.instance.offset.click=r.offset.click,this.instance._intersectsWith(this.instance.containerCache)&&(o=!0,e.each(r.sortables,function(){return this.instance.positionAbs=r.positionAbs,this.instance.helperProportions=r.helperProportions,this.instance.offset.click=r.offset.click,this!=u&&this.instance._intersectsWith(this.instance.containerCache)&&e.ui.contains(u.instance.element[0],this.instance.element[0])&&(o=!1),o})),o?(this.instance.isOver||(this.instance.isOver=1,this.instance.currentItem=e(i).clone().removeAttr("id").appendTo(this.instance.element).data("sortable-item",!0),this.instance.options._helper=this.instance.options.helper,this.instance.options.helper=function(){return n.helper[0]},t.target=this.instance.currentItem[0],this.instance._mouseCapture(t,!0),this.instance._mouseStart(t,!0,!0),this.instance.offset.click.top=r.offset.click.top,this.instance.offset.click.left=r.offset.click.left,this.instance.offset.parent.left-=r.offset.parent.left-this.instance.offset.parent.left,this.instance.offset.parent.top-=r.offset.parent.top-this.instance.offset.parent.top,r._trigger("toSortable",t),r.dropped=this.instance.element,r.currentItem=r.element,this.instance.fromOutside=r),this.instance.currentItem&&this.instance._mouseDrag(t)):this.instance.isOver&&(this.instance.isOver=0,this.instance.cancelHelperRemoval=!0,this.instance.options.revert=!1,this.instance._trigger("out",t,this.instance._uiHash(this.instance)),this.instance._mouseStop(t,!0),this.instance.options.helper=this.instance.options._helper,this.instance.currentItem.remove(),this.instance.placeholder&&this.instance.placeholder.remove(),r._trigger("fromSortable",t),r.dropped=!1)})}}),e.ui.plugin.add("draggable","cursor",{start:function(t,n){var r=e("body"),i=e(this).data("draggable").options;r.css("cursor")&&(i._cursor=r.css("cursor")),r.css("cursor",i.cursor)},stop:function(t,n){var r=e(this).data("draggable").options;r._cursor&&e("body").css("cursor",r._cursor)}}),e.ui.plugin.add("draggable","opacity",{start:function(t,n){var r=e(n.helper),i=e(this).data("draggable").options;r.css("opacity")&&(i._opacity=r.css("opacity")),r.css("opacity",i.opacity)},stop:function(t,n){var r=e(this).data("draggable").options;r._opacity&&e(n.helper).css("opacity",r._opacity)}}),e.ui.plugin.add("draggable","scroll",{start:function(t,n){var r=e(this).data("draggable");r.scrollParent[0]!=document&&r.scrollParent[0].tagName!="HTML"&&(r.overflowOffset=r.scrollParent.offset())},drag:function(t,n){var r=e(this).data("draggable"),i=r.options,s=!1;if(r.scrollParent[0]!=document&&r.scrollParent[0].tagName!="HTML"){if(!i.axis||i.axis!="x")r.overflowOffset.top+r.scrollParent[0].offsetHeight-t.pageY<i.scrollSensitivity?r.scrollParent[0].scrollTop=s=r.scrollParent[0].scrollTop+i.scrollSpeed:t.pageY-r.overflowOffset.top<i.scrollSensitivity&&(r.scrollParent[0].scrollTop=s=r.scrollParent[0].scrollTop-i.scrollSpeed);if(!i.axis||i.axis!="y")r.overflowOffset.left+r.scrollParent[0].offsetWidth-t.pageX<i.scrollSensitivity?r.scrollParent[0].scrollLeft=s=r.scrollParent[0].scrollLeft+i.scrollSpeed:t.pageX-r.overflowOffset.left<i.scrollSensitivity&&(r.scrollParent[0].scrollLeft=s=r.scrollParent[0].scrollLeft-i.scrollSpeed)}else{if(!i.axis||i.axis!="x")t.pageY-e(document).scrollTop()<i.scrollSensitivity?s=e(document).scrollTop(e(document).scrollTop()-i.scrollSpeed):e(window).height()-(t.pageY-e(document).scrollTop())<i.scrollSensitivity&&(s=e(document).scrollTop(e(document).scrollTop()+i.scrollSpeed));if(!i.axis||i.axis!="y")t.pageX-e(document).scrollLeft()<i.scrollSensitivity?s=e(document).scrollLeft(e(document).scrollLeft()-i.scrollSpeed):e(window).width()-(t.pageX-e(document).scrollLeft())<i.scrollSensitivity&&(s=e(document).scrollLeft(e(document).scrollLeft()+i.scrollSpeed))}s!==!1&&e.ui.ddmanager&&!i.dropBehaviour&&e.ui.ddmanager.prepareOffsets(r,t)}}),e.ui.plugin.add("draggable","snap",{start:function(t,n){var r=e(this).data("draggable"),i=r.options;r.snapElements=[],e(i.snap.constructor!=String?i.snap.items||":data(draggable)":i.snap).each(function(){var t=e(this),n=t.offset();this!=r.element[0]&&r.snapElements.push({item:this,width:t.outerWidth(),height:t.outerHeight(),top:n.top,left:n.left})})},drag:function(t,n){var r=e(this).data("draggable"),i=r.options,s=i.snapTolerance,o=n.offset.left,u=o+r.helperProportions.width,a=n.offset.top,f=a+r.helperProportions.height;for(var l=r.snapElements.length-1;l>=0;l--){var c=r.snapElements[l].left,h=c+r.snapElements[l].width,p=r.snapElements[l].top,d=p+r.snapElements[l].height;if(!(c-s<o&&o<h+s&&p-s<a&&a<d+s||c-s<o&&o<h+s&&p-s<f&&f<d+s||c-s<u&&u<h+s&&p-s<a&&a<d+s||c-s<u&&u<h+s&&p-s<f&&f<d+s)){r.snapElements[l].snapping&&r.options.snap.release&&r.options.snap.release.call(r.element,t,e.extend(r._uiHash(),{snapItem:r.snapElements[l].item})),r.snapElements[l].snapping=!1;continue}if(i.snapMode!="inner"){var v=Math.abs(p-f)<=s,m=Math.abs(d-a)<=s,g=Math.abs(c-u)<=s,y=Math.abs(h-o)<=s;v&&(n.position.top=r._convertPositionTo("relative",{top:p-r.helperProportions.height,left:0}).top-r.margins.top),m&&(n.position.top=r._convertPositionTo("relative",{top:d,left:0}).top-r.margins.top),g&&(n.position.left=r._convertPositionTo("relative",{top:0,left:c-r.helperProportions.width}).left-r.margins.left),y&&(n.position.left=r._convertPositionTo("relative",{top:0,left:h}).left-r.margins.left)}var b=v||m||g||y;if(i.snapMode!="outer"){var v=Math.abs(p-a)<=s,m=Math.abs(d-f)<=s,g=Math.abs(c-o)<=s,y=Math.abs(h-u)<=s;v&&(n.position.top=r._convertPositionTo("relative",{top:p,left:0}).top-r.margins.top),m&&(n.position.top=r._convertPositionTo("relative",{top:d-r.helperProportions.height,left:0}).top-r.margins.top),g&&(n.position.left=r._convertPositionTo("relative",{top:0,left:c}).left-r.margins.left),y&&(n.position.left=r._convertPositionTo("relative",{top:0,left:h-r.helperProportions.width}).left-r.margins.left)}!r.snapElements[l].snapping&&(v||m||g||y||b)&&r.options.snap.snap&&r.options.snap.snap.call(r.element,t,e.extend(r._uiHash(),{snapItem:r.snapElements[l].item})),r.snapElements[l].snapping=v||m||g||y||b}}}),e.ui.plugin.add("draggable","stack",{start:function(t,n){var r=e(this).data("draggable").options,i=e.makeArray(e(r.stack)).sort(function(t,n){return(parseInt(e(t).css("zIndex"),10)||0)-(parseInt(e(n).css("zIndex"),10)||0)});if(!i.length)return;var s=parseInt(i[0].style.zIndex)||0;e(i).each(function(e){this.style.zIndex=s+e}),this[0].style.zIndex=s+i.length}}),e.ui.plugin.add("draggable","zIndex",{start:function(t,n){var r=e(n.helper),i=e(this).data("draggable").options;r.css("zIndex")&&(i._zIndex=r.css("zIndex")),r.css("zIndex",i.zIndex)},stop:function(t,n){var r=e(this).data("draggable").options;r._zIndex&&e(n.helper).css("zIndex",r._zIndex)}})}(jQuery),function(e,t){e.widget("ui.droppable",{version:"1.9.2",widgetEventPrefix:"drop",options:{accept:"*",activeClass:!1,addClasses:!0,greedy:!1,hoverClass:!1,scope:"default",tolerance:"intersect"},_create:function(){var t=this.options,n=t.accept;this.isover=0,this.isout=1,this.accept=e.isFunction(n)?n:function(e){return e.is(n)},this.proportions={width:this.element[0].offsetWidth,height:this.element[0].offsetHeight},e.ui.ddmanager.droppables[t.scope]=e.ui.ddmanager.droppables[t.scope]||[],e.ui.ddmanager.droppables[t.scope].push(this),t.addClasses&&this.element.addClass("ui-droppable")},_destroy:function(){var t=e.ui.ddmanager.droppables[this.options.scope];for(var n=0;n<t.length;n++)t[n]==this&&t.splice(n,1);this.element.removeClass("ui-droppable ui-droppable-disabled")},_setOption:function(t,n){t=="accept"&&(this.accept=e.isFunction(n)?n:function(e){return e.is(n)}),e.Widget.prototype._setOption.apply(this,arguments)},_activate:function(t){var n=e.ui.ddmanager.current;this.options.activeClass&&this.element.addClass(this.options.activeClass),n&&this._trigger("activate",t,this.ui(n))},_deactivate:function(t){var n=e.ui.ddmanager.current;this.options.activeClass&&this.element.removeClass(this.options.activeClass),n&&this._trigger("deactivate",t,this.ui(n))},_over:function(t){var n=e.ui.ddmanager.current;if(!n||(n.currentItem||n.element)[0]==this.element[0])return;this.accept.call(this.element[0],n.currentItem||n.element)&&(this.options.hoverClass&&this.element.addClass(this.options.hoverClass),this._trigger("over",t,this.ui(n)))},_out:function(t){var n=e.ui.ddmanager.current;if(!n||(n.currentItem||n.element)[0]==this.element[0])return;this.accept.call(this.element[0],n.currentItem||n.element)&&(this.options.hoverClass&&this.element.removeClass(this.options.hoverClass),this._trigger("out",t,this.ui(n)))},_drop:function(t,n){var r=n||e.ui.ddmanager.current;if(!r||(r.currentItem||r.element)[0]==this.element[0])return!1;var i=!1;return this.element.find(":data(droppable)").not(".ui-draggable-dragging").each(function(){var t=e.data(this,"droppable");if(t.options.greedy&&!t.options.disabled&&t.options.scope==r.options.scope&&t.accept.call(t.element[0],r.currentItem||r.element)&&e.ui.intersect(r,e.extend(t,{offset:t.element.offset()}),t.options.tolerance))return i=!0,!1}),i?!1:this.accept.call(this.element[0],r.currentItem||r.element)?(this.options.activeClass&&this.element.removeClass(this.options.activeClass),this.options.hoverClass&&this.element.removeClass(this.options.hoverClass),this._trigger("drop",t,this.ui(r)),this.element):!1},ui:function(e){return{draggable:e.currentItem||e.element,helper:e.helper,position:e.position,offset:e.positionAbs}}}),e.ui.intersect=function(t,n,r){if(!n.offset)return!1;var i=(t.positionAbs||t.position.absolute).left,s=i+t.helperProportions.width,o=(t.positionAbs||t.position.absolute).top,u=o+t.helperProportions.height,a=n.offset.left,f=a+n.proportions.width,l=n.offset.top,c=l+n.proportions.height;switch(r){case"fit":return a<=i&&s<=f&&l<=o&&u<=c;case"intersect":return a<i+t.helperProportions.width/2&&s-t.helperProportions.width/2<f&&l<o+t.helperProportions.height/2&&u-t.helperProportions.height/2<c;case"pointer":var h=(t.positionAbs||t.position.absolute).left+(t.clickOffset||t.offset.click).left,p=(t.positionAbs||t.position.absolute).top+(t.clickOffset||t.offset.click).top,d=e.ui.isOver(p,h,l,a,n.proportions.height,n.proportions.width);return d;case"touch":return(o>=l&&o<=c||u>=l&&u<=c||o<l&&u>c)&&(i>=a&&i<=f||s>=a&&s<=f||i<a&&s>f);default:return!1}},e.ui.ddmanager={current:null,droppables:{"default":[]},prepareOffsets:function(t,n){var r=e.ui.ddmanager.droppables[t.options.scope]||[],i=n?n.type:null,s=(t.currentItem||t.element).find(":data(droppable)").andSelf();e:for(var o=0;o<r.length;o++){if(r[o].options.disabled||t&&!r[o].accept.call(r[o].element[0],t.currentItem||t.element))continue;for(var u=0;u<s.length;u++)if(s[u]==r[o].element[0]){r[o].proportions.height=0;continue e}r[o].visible=r[o].element.css("display")!="none";if(!r[o].visible)continue;i=="mousedown"&&r[o]._activate.call(r[o],n),r[o].offset=r[o].element.offset(),r[o].proportions={width:r[o].element[0].offsetWidth,height:r[o].element[0].offsetHeight}}},drop:function(t,n){var r=!1;return e.each(e.ui.ddmanager.droppables[t.options.scope]||[],function(){if(!this.options)return;!this.options.disabled&&this.visible&&e.ui.intersect(t,this,this.options.tolerance)&&(r=this._drop.call(this,n)||r),!this.options.disabled&&this.visible&&this.accept.call(this.element[0],t.currentItem||t.element)&&(this.isout=1,this.isover=0,this._deactivate.call(this,n))}),r},dragStart:function(t,n){t.element.parentsUntil("body").bind("scroll.droppable",function(){t.options.refreshPositions||e.ui.ddmanager.prepareOffsets(t,n)})},drag:function(t,n){t.options.refreshPositions&&e.ui.ddmanager.prepareOffsets(t,n),e.each(e.ui.ddmanager.droppables[t.options.scope]||[],function(){if(this.options.disabled||this.greedyChild||!this.visible)return;var r=e.ui.intersect(t,this,this.options.tolerance),i=!r&&this.isover==1?"isout":r&&this.isover==0?"isover":null;if(!i)return;var s;if(this.options.greedy){var o=this.options.scope,u=this.element.parents(":data(droppable)").filter(function(){return e.data(this,"droppable").options.scope===o});u.length&&(s=e.data(u[0],"droppable"),s.greedyChild=i=="isover"?1:0)}s&&i=="isover"&&(s.isover=0,s.isout=1,s._out.call(s,n)),this[i]=1,this[i=="isout"?"isover":"isout"]=0,this[i=="isover"?"_over":"_out"].call(this,n),s&&i=="isout"&&(s.isout=0,s.isover=1,s._over.call(s,n))})},dragStop:function(t,n){t.element.parentsUntil("body").unbind("scroll.droppable"),t.options.refreshPositions||e.ui.ddmanager.prepareOffsets(t,n)}}}(jQuery),function(e,t){e.widget("ui.resizable",e.ui.mouse,{version:"1.9.2",widgetEventPrefix:"resize",options:{alsoResize:!1,animate:!1,animateDuration:"slow",animateEasing:"swing",aspectRatio:!1,autoHide:!1,containment:!1,ghost:!1,grid:!1,handles:"e,s,se",helper:!1,maxHeight:null,maxWidth:null,minHeight:10,minWidth:10,zIndex:1e3},_create:function(){var t=this,n=this.options;this.element.addClass("ui-resizable"),e.extend(this,{_aspectRatio:!!n.aspectRatio,aspectRatio:n.aspectRatio,originalElement:this.element,_proportionallyResizeElements:[],_helper:n.helper||n.ghost||n.animate?n.helper||"ui-resizable-helper":null}),this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)&&(this.element.wrap(e('<div class="ui-wrapper" style="overflow: hidden;"></div>').css({position:this.element.css("position"),width:this.element.outerWidth(),height:this.element.outerHeight(),top:this.element.css("top"),left:this.element.css("left")})),this.element=this.element.parent().data("resizable",this.element.data("resizable")),this.elementIsWrapper=!0,this.element.css({marginLeft:this.originalElement.css("marginLeft"),marginTop:this.originalElement.css("marginTop"),marginRight:this.originalElement.css("marginRight"),marginBottom:this.originalElement.css("marginBottom")}),this.originalElement.css({marginLeft:0,marginTop:0,marginRight:0,marginBottom:0}),this.originalResizeStyle=this.originalElement.css("resize"),this.originalElement.css("resize","none"),this._proportionallyResizeElements.push(this.originalElement.css({position:"static",zoom:1,display:"block"})),this.originalElement.css({margin:this.originalElement.css("margin")}),this._proportionallyResize()),this.handles=n.handles||(e(".ui-resizable-handle",this.element).length?{n:".ui-resizable-n",e:".ui-resizable-e",s:".ui-resizable-s",w:".ui-resizable-w",se:".ui-resizable-se",sw:".ui-resizable-sw",ne:".ui-resizable-ne",nw:".ui-resizable-nw"}:"e,s,se");if(this.handles.constructor==String){this.handles=="all"&&(this.handles="n,e,s,w,se,sw,ne,nw");var r=this.handles.split(",");this.handles={};for(var i=0;i<r.length;i++){var s=e.trim(r[i]),o="ui-resizable-"+s,u=e('<div class="ui-resizable-handle '+o+'"></div>');u.css({zIndex:n.zIndex}),"se"==s&&u.addClass("ui-icon ui-icon-gripsmall-diagonal-se"),this.handles[s]=".ui-resizable-"+s,this.element.append(u)}}this._renderAxis=function(t){t=t||this.element;for(var n in this.handles){this.handles[n].constructor==String&&(this.handles[n]=e(this.handles[n],this.element).show());if(this.elementIsWrapper&&this.originalElement[0].nodeName.match(/textarea|input|select|button/i)){var r=e(this.handles[n],this.element),i=0;i=/sw|ne|nw|se|n|s/.test(n)?r.outerHeight():r.outerWidth();var s=["padding",/ne|nw|n/.test(n)?"Top":/se|sw|s/.test(n)?"Bottom":/^e$/.test(n)?"Right":"Left"].join("");t.css(s,i),this._proportionallyResize()}if(!e(this.handles[n]).length)continue}},this._renderAxis(this.element),this._handles=e(".ui-resizable-handle",this.element).disableSelection(),this._handles.mouseover(function(){if(!t.resizing){if(this.className)var e=this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i);t.axis=e&&e[1]?e[1]:"se"}}),n.autoHide&&(this._handles.hide(),e(this.element).addClass("ui-resizable-autohide").mouseenter(function(){if(n.disabled)return;e(this).removeClass("ui-resizable-autohide"),t._handles.show()}).mouseleave(function(){if(n.disabled)return;t.resizing||(e(this).addClass("ui-resizable-autohide"),t._handles.hide())})),this._mouseInit()},_destroy:function(){this._mouseDestroy();var t=function(t){e(t).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing").removeData("resizable").removeData("ui-resizable").unbind(".resizable").find(".ui-resizable-handle").remove()};if(this.elementIsWrapper){t(this.element);var n=this.element;this.originalElement.css({position:n.css("position"),width:n.outerWidth(),height:n.outerHeight(),top:n.css("top"),left:n.css("left")}).insertAfter(n),n.remove()}return this.originalElement.css("resize",this.originalResizeStyle),t(this.originalElement),this},_mouseCapture:function(t){var n=!1;for(var r in this.handles)e(this.handles[r])[0]==t.target&&(n=!0);return!this.options.disabled&&n},_mouseStart:function(t){var r=this.options,i=this.element.position(),s=this.element;this.resizing=!0,this.documentScroll={top:e(document).scrollTop(),left:e(document).scrollLeft()},(s.is(".ui-draggable")||/absolute/.test(s.css("position")))&&s.css({position:"absolute",top:i.top,left:i.left}),this._renderProxy();var o=n(this.helper.css("left")),u=n(this.helper.css("top"));r.containment&&(o+=e(r.containment).scrollLeft()||0,u+=e(r.containment).scrollTop()||0),this.offset=this.helper.offset(),this.position={left:o,top:u},this.size=this._helper?{width:s.outerWidth(),height:s.outerHeight()}:{width:s.width(),height:s.height()},this.originalSize=this._helper?{width:s.outerWidth(),height:s.outerHeight()}:{width:s.width(),height:s.height()},this.originalPosition={left:o,top:u},this.sizeDiff={width:s.outerWidth()-s.width(),height:s.outerHeight()-s.height()},this.originalMousePosition={left:t.pageX,top:t.pageY},this.aspectRatio=typeof r.aspectRatio=="number"?r.aspectRatio:this.originalSize.width/this.originalSize.height||1;var a=e(".ui-resizable-"+this.axis).css("cursor");return e("body").css("cursor",a=="auto"?this.axis+"-resize":a),s.addClass("ui-resizable-resizing"),this._propagate("start",t),!0},_mouseDrag:function(e){var t=this.helper,n=this.options,r={},i=this,s=this.originalMousePosition,o=this.axis,u=e.pageX-s.left||0,a=e.pageY-s.top||0,f=this._change[o];if(!f)return!1;var l=f.apply(this,[e,u,a]);this._updateVirtualBoundaries(e.shiftKey);if(this._aspectRatio||e.shiftKey)l=this._updateRatio(l,e);return l=this._respectSize(l,e),this._propagate("resize",e),t.css({top:this.position.top+"px",left:this.position.left+"px",width:this.size.width+"px",height:this.size.height+"px"}),!this._helper&&this._proportionallyResizeElements.length&&this._proportionallyResize(),this._updateCache(l),this._trigger("resize",e,this.ui()),!1},_mouseStop:function(t){this.resizing=!1;var n=this.options,r=this;if(this._helper){var i=this._proportionallyResizeElements,s=i.length&&/textarea/i.test(i[0].nodeName),o=s&&e.ui.hasScroll(i[0],"left")?0:r.sizeDiff.height,u=s?0:r.sizeDiff.width,a={width:r.helper.width()-u,height:r.helper.height()-o},f=parseInt(r.element.css("left"),10)+(r.position.left-r.originalPosition.left)||null,l=parseInt(r.element.css("top"),10)+(r.position.top-r.originalPosition.top)||null;n.animate||this.element.css(e.extend(a,{top:l,left:f})),r.helper.height(r.size.height),r.helper.width(r.size.width),this._helper&&!n.animate&&this._proportionallyResize()}return e("body").css("cursor","auto"),this.element.removeClass("ui-resizable-resizing"),this._propagate("stop",t),this._helper&&this.helper.remove(),!1},_updateVirtualBoundaries:function(e){var t=this.options,n,i,s,o,u;u={minWidth:r(t.minWidth)?t.minWidth:0,maxWidth:r(t.maxWidth)?t.maxWidth:Infinity,minHeight:r(t.minHeight)?t.minHeight:0,maxHeight:r(t.maxHeight)?t.maxHeight:Infinity};if(this._aspectRatio||e)n=u.minHeight*this.aspectRatio,s=u.minWidth/this.aspectRatio,i=u.maxHeight*this.aspectRatio,o=u.maxWidth/this.aspectRatio,n>u.minWidth&&(u.minWidth=n),s>u.minHeight&&(u.minHeight=s),i<u.maxWidth&&(u.maxWidth=i),o<u.maxHeight&&(u.maxHeight=o);this._vBoundaries=u},_updateCache:function(e){var t=this.options;this.offset=this.helper.offset(),r(e.left)&&(this.position.left=e.left),r(e.top)&&(this.position.top=e.top),r(e.height)&&(this.size.height=e.height),r(e.width)&&(this.size.width=e.width)},_updateRatio:function(e,t){var n=this.options,i=this.position,s=this.size,o=this.axis;return r(e.height)?e.width=e.height*this.aspectRatio:r(e.width)&&(e.height=e.width/this.aspectRatio),o=="sw"&&(e.left=i.left+(s.width-e.width),e.top=null),o=="nw"&&(e.top=i.top+(s.height-e.height),e.left=i.left+(s.width-e.width)),e},_respectSize:function(e,t){var n=this.helper,i=this._vBoundaries,s=this._aspectRatio||t.shiftKey,o=this.axis,u=r(e.width)&&i.maxWidth&&i.maxWidth<e.width,a=r(e.height)&&i.maxHeight&&i.maxHeight<e.height,f=r(e.width)&&i.minWidth&&i.minWidth>e.width,l=r(e.height)&&i.minHeight&&i.minHeight>e.height;f&&(e.width=i.minWidth),l&&(e.height=i.minHeight),u&&(e.width=i.maxWidth),a&&(e.height=i.maxHeight);var c=this.originalPosition.left+this.originalSize.width,h=this.position.top+this.size.height,p=/sw|nw|w/.test(o),d=/nw|ne|n/.test(o);f&&p&&(e.left=c-i.minWidth),u&&p&&(e.left=c-i.maxWidth),l&&d&&(e.top=h-i.minHeight),a&&d&&(e.top=h-i.maxHeight);var v=!e.width&&!e.height;return v&&!e.left&&e.top?e.top=null:v&&!e.top&&e.left&&(e.left=null),e},_proportionallyResize:function(){var t=this.options;if(!this._proportionallyResizeElements.length)return;var n=this.helper||this.element;for(var r=0;r<this._proportionallyResizeElements.length;r++){var i=this._proportionallyResizeElements[r];if(!this.borderDif){var s=[i.css("borderTopWidth"),i.css("borderRightWidth"),i.css("borderBottomWidth"),i.css("borderLeftWidth")],o=[i.css("paddingTop"),i.css("paddingRight"),i.css("paddingBottom"),i.css("paddingLeft")];this.borderDif=e.map(s,function(e,t){var n=parseInt(e,10)||0,r=parseInt(o[t],10)||0;return n+r})}i.css({height:n.height()-this.borderDif[0]-this.borderDif[2]||0,width:n.width()-this.borderDif[1]-this.borderDif[3]||0})}},_renderProxy:function(){var t=this.element,n=this.options;this.elementOffset=t.offset();if(this._helper){this.helper=this.helper||e('<div style="overflow:hidden;"></div>');var r=e.ui.ie6?1:0,i=e.ui.ie6?2:-1;this.helper.addClass(this._helper).css({width:this.element.outerWidth()+i,height:this.element.outerHeight()+i,position:"absolute",left:this.elementOffset.left-r+"px",top:this.elementOffset.top-r+"px",zIndex:++n.zIndex}),this.helper.appendTo("body").disableSelection()}else this.helper=this.element},_change:{e:function(e,t,n){return{width:this.originalSize.width+t}},w:function(e,t,n){var r=this.options,i=this.originalSize,s=this.originalPosition;return{left:s.left+t,width:i.width-t}},n:function(e,t,n){var r=this.options,i=this.originalSize,s=this.originalPosition;return{top:s.top+n,height:i.height-n}},s:function(e,t,n){return{height:this.originalSize.height+n}},se:function(t,n,r){return e.extend(this._change.s.apply(this,arguments),this._change.e.apply(this,[t,n,r]))},sw:function(t,n,r){return e.extend(this._change.s.apply(this,arguments),this._change.w.apply(this,[t,n,r]))},ne:function(t,n,r){return e.extend(this._change.n.apply(this,arguments),this._change.e.apply(this,[t,n,r]))},nw:function(t,n,r){return e.extend(this._change.n.apply(this,arguments),this._change.w.apply(this,[t,n,r]))}},_propagate:function(t,n){e.ui.plugin.call(this,t,[n,this.ui()]),t!="resize"&&this._trigger(t,n,this.ui())},plugins:{},ui:function(){return{originalElement:this.originalElement,element:this.element,helper:this.helper,position:this.position,size:this.size,originalSize:this.originalSize,originalPosition:this.originalPosition}}}),e.ui.plugin.add("resizable","alsoResize",{start:function(t,n){var r=e(this).data("resizable"),i=r.options,s=function(t){e(t).each(function(){var t=e(this);t.data("resizable-alsoresize",{width:parseInt(t.width(),10),height:parseInt(t.height(),10),left:parseInt(t.css("left"),10),top:parseInt(t.css("top"),10)})})};typeof i.alsoResize=="object"&&!i.alsoResize.parentNode?i.alsoResize.length?(i.alsoResize=i.alsoResize[0],s(i.alsoResize)):e.each(i.alsoResize,function(e){s(e)}):s(i.alsoResize)},resize:function(t,n){var r=e(this).data("resizable"),i=r.options,s=r.originalSize,o=r.originalPosition,u={height:r.size.height-s.height||0,width:r.size.width-s.width||0,top:r.position.top-o.top||0,left:r.position.left-o.left||0},a=function(t,r){e(t).each(function(){var t=e(this),i=e(this).data("resizable-alsoresize"),s={},o=r&&r.length?r:t.parents(n.originalElement[0]).length?["width","height"]:["width","height","top","left"];e.each(o,function(e,t){var n=(i[t]||0)+(u[t]||0);n&&n>=0&&(s[t]=n||null)}),t.css(s)})};typeof i.alsoResize=="object"&&!i.alsoResize.nodeType?e.each(i.alsoResize,function(e,t){a(e,t)}):a(i.alsoResize)},stop:function(t,n){e(this).removeData("resizable-alsoresize")}}),e.ui.plugin.add("resizable","animate",{stop:function(t,n){var r=e(this).data("resizable"),i=r.options,s=r._proportionallyResizeElements,o=s.length&&/textarea/i.test(s[0].nodeName),u=o&&e.ui.hasScroll(s[0],"left")?0:r.sizeDiff.height,a=o?0:r.sizeDiff.width,f={width:r.size.width-a,height:r.size.height-u},l=parseInt(r.element.css("left"),10)+(r.position.left-r.originalPosition.left)||null,c=parseInt(r.element.css("top"),10)+(r.position.top-r.originalPosition.top)||null;r.element.animate(e.extend(f,c&&l?{top:c,left:l}:{}),{duration:i.animateDuration,easing:i.animateEasing,step:function(){var n={width:parseInt(r.element.css("width"),10),height:parseInt(r.element.css("height"),10),top:parseInt(r.element.css("top"),10),left:parseInt(r.element.css("left"),10)};s&&s.length&&e(s[0]).css({width:n.width,height:n.height}),r._updateCache(n),r._propagate("resize",t)}})}}),e.ui.plugin.add("resizable","containment",{start:function(t,r){var i=e(this).data("resizable"),s=i.options,o=i.element,u=s.containment,a=u instanceof e?u.get(0):/parent/.test(u)?o.parent().get(0):u;if(!a)return;i.containerElement=e(a);if(/document/.test(u)||u==document)i.containerOffset={left:0,top:0},i.containerPosition={left:0,top:0},i.parentData={element:e(document),left:0,top:0,width:e(document).width(),height:e(document).height()||document.body.parentNode.scrollHeight};else{var f=e(a),l=[];e(["Top","Right","Left","Bottom"]).each(function(e,t){l[e]=n(f.css("padding"+t))}),i.containerOffset=f.offset(),i.containerPosition=f.position(),i.containerSize={height:f.innerHeight()-l[3],width:f.innerWidth()-l[1]};var c=i.containerOffset,h=i.containerSize.height,p=i.containerSize.width,d=e.ui.hasScroll(a,"left")?a.scrollWidth:p,v=e.ui.hasScroll(a)?a.scrollHeight:h;i.parentData={element:a,left:c.left,top:c.top,width:d,height:v}}},resize:function(t,n){var r=e(this).data("resizable"),i=r.options,s=r.containerSize,o=r.containerOffset,u=r.size,a=r.position,f=r._aspectRatio||t.shiftKey,l={top:0,left:0},c=r.containerElement;c[0]!=document&&/static/.test(c.css("position"))&&(l=o),a.left<(r._helper?o.left:0)&&(r.size.width=r.size.width+(r._helper?r.position.left-o.left:r.position.left-l.left),f&&(r.size.height=r.size.width/r.aspectRatio),r.position.left=i.helper?o.left:0),a.top<(r._helper?o.top:0)&&(r.size.height=r.size.height+(r._helper?r.position.top-o.top:r.position.top),f&&(r.size.width=r.size.height*r.aspectRatio),r.position.top=r._helper?o.top:0),r.offset.left=r.parentData.left+r.position.left,r.offset.top=r.parentData.top+r.position.top;var h=Math.abs((r._helper?r.offset.left-l.left:r.offset.left-l.left)+r.sizeDiff.width),p=Math.abs((r._helper?r.offset.top-l.top:r.offset.top-o.top)+r.sizeDiff.height),d=r.containerElement.get(0)==r.element.parent().get(0),v=/relative|absolute/.test(r.containerElement.css("position"));d&&v&&(h-=r.parentData.left),h+r.size.width>=r.parentData.width&&(r.size.width=r.parentData.width-h,f&&(r.size.height=r.size.width/r.aspectRatio)),p+r.size.height>=r.parentData.height&&(r.size.height=r.parentData.height-p,f&&(r.size.width=r.size.height*r.aspectRatio))},stop:function(t,n){var r=e(this).data("resizable"),i=r.options,s=r.position,o=r.containerOffset,u=r.containerPosition,a=r.containerElement,f=e(r.helper),l=f.offset(),c=f.outerWidth()-r.sizeDiff.width,h=f.outerHeight()-r.sizeDiff.height;r._helper&&!i.animate&&/relative/.test(a.css("position"))&&e(this).css({left:l.left-u.left-o.left,width:c,height:h}),r._helper&&!i.animate&&/static/.test(a.css("position"))&&e(this).css({left:l.left-u.left-o.left,width:c,height:h})}}),e.ui.plugin.add("resizable","ghost",{start:function(t,n){var r=e(this).data("resizable"),i=r.options,s=r.size;r.ghost=r.originalElement.clone(),r.ghost.css({opacity:.25,display:"block",position:"relative",height:s.height,width:s.width,margin:0,left:0,top:0}).addClass("ui-resizable-ghost").addClass(typeof i.ghost=="string"?i.ghost:""),r.ghost.appendTo(r.helper)},resize:function(t,n){var r=e(this).data("resizable"),i=r.options;r.ghost&&r.ghost.css({position:"relative",height:r.size.height,width:r.size.width})},stop:function(t,n){var r=e(this).data("resizable"),i=r.options;r.ghost&&r.helper&&r.helper.get(0).removeChild(r.ghost.get(0))}}),e.ui.plugin.add("resizable","grid",{resize:function(t,n){var r=e(this).data("resizable"),i=r.options,s=r.size,o=r.originalSize,u=r.originalPosition,a=r.axis,f=i._aspectRatio||t.shiftKey;i.grid=typeof i.grid=="number"?[i.grid,i.grid]:i.grid;var l=Math.round((s.width-o.width)/(i.grid[0]||1))*(i.grid[0]||1),c=Math.round((s.height-o.height)/(i.grid[1]||1))*(i.grid[1]||1);/^(se|s|e)$/.test(a)?(r.size.width=o.width+l,r.size.height=o.height+c):/^(ne)$/.test(a)?(r.size.width=o.width+l,r.size.height=o.height+c,r.position.top=u.top-c):/^(sw)$/.test(a)?(r.size.width=o.width+l,r.size.height=o.height+c,r.position.left=u.left-l):(r.size.width=o.width+l,r.size.height=o.height+c,r.position.top=u.top-c,r.position.left=u.left-l)}});var n=function(e){return parseInt(e,10)||0},r=function(e){return!isNaN(parseInt(e,10))}}(jQuery),function(e,t){e.widget("ui.selectable",e.ui.mouse,{version:"1.9.2",options:{appendTo:"body",autoRefresh:!0,distance:0,filter:"*",tolerance:"touch"},_create:function(){var t=this;this.element.addClass("ui-selectable"),this.dragged=!1;var n;this.refresh=function(){n=e(t.options.filter,t.element[0]),n.addClass("ui-selectee"),n.each(function(){var t=e(this),n=t.offset();e.data(this,"selectable-item",{element:this,$element:t,left:n.left,top:n.top,right:n.left+t.outerWidth(),bottom:n.top+t.outerHeight(),startselected:!1,selected:t.hasClass("ui-selected"),selecting:t.hasClass("ui-selecting"),unselecting:t.hasClass("ui-unselecting")})})},this.refresh(),this.selectees=n.addClass("ui-selectee"),this._mouseInit(),this.helper=e("<div class='ui-selectable-helper'></div>")},_destroy:function(){this.selectees.removeClass("ui-selectee").removeData("selectable-item"),this.element.removeClass("ui-selectable ui-selectable-disabled"),this._mouseDestroy()},_mouseStart:function(t){var n=this;this.opos=[t.pageX,t.pageY];if(this.options.disabled)return;var r=this.options;this.selectees=e(r.filter,this.element[0]),this._trigger("start",t),e(r.appendTo).append(this.helper),this.helper.css({left:t.clientX,top:t.clientY,width:0,height:0}),r.autoRefresh&&this.refresh(),this.selectees.filter(".ui-selected").each(function(){var r=e.data(this,"selectable-item");r.startselected=!0,!t.metaKey&&!t.ctrlKey&&(r.$element.removeClass("ui-selected"),r.selected=!1,r.$element.addClass("ui-unselecting"),r.unselecting=!0,n._trigger("unselecting",t,{unselecting:r.element}))}),e(t.target).parents().andSelf().each(function(){var r=e.data(this,"selectable-item");if(r){var i=!t.metaKey&&!t.ctrlKey||!r.$element.hasClass("ui-selected");return r.$element.removeClass(i?"ui-unselecting":"ui-selected").addClass(i?"ui-selecting":"ui-unselecting"),r.unselecting=!i,r.selecting=i,r.selected=i,i?n._trigger("selecting",t,{selecting:r.element}):n._trigger("unselecting",t,{unselecting:r.element}),!1}})},_mouseDrag:function(t){var n=this;this.dragged=!0;if(this.options.disabled)return;var r=this.options,i=this.opos[0],s=this.opos[1],o=t.pageX,u=t.pageY;if(i>o){var a=o;o=i,i=a}if(s>u){var a=u;u=s,s=a}return this.helper.css({left:i,top:s,width:o-i,height:u-s}),this.selectees.each(function(){var a=e.data(this,"selectable-item");if(!a||a.element==n.element[0])return;var f=!1;r.tolerance=="touch"?f=!(a.left>o||a.right<i||a.top>u||a.bottom<s):r.tolerance=="fit"&&(f=a.left>i&&a.right<o&&a.top>s&&a.bottom<u),f?(a.selected&&(a.$element.removeClass("ui-selected"),a.selected=!1),a.unselecting&&(a.$element.removeClass("ui-unselecting"),a.unselecting=!1),a.selecting||(a.$element.addClass("ui-selecting"),a.selecting=!0,n._trigger("selecting",t,{selecting:a.element}))):(a.selecting&&((t.metaKey||t.ctrlKey)&&a.startselected?(a.$element.removeClass("ui-selecting"),a.selecting=!1,a.$element.addClass("ui-selected"),a.selected=!0):(a.$element.removeClass("ui-selecting"),a.selecting=!1,a.startselected&&(a.$element.addClass("ui-unselecting"),a.unselecting=!0),n._trigger("unselecting",t,{unselecting:a.element}))),a.selected&&!t.metaKey&&!t.ctrlKey&&!a.startselected&&(a.$element.removeClass("ui-selected"),a.selected=!1,a.$element.addClass("ui-unselecting"),a.unselecting=!0,n._trigger("unselecting",t,{unselecting:a.element})))}),!1},_mouseStop:function(t){var n=this;this.dragged=!1;var r=this.options;return e(".ui-unselecting",this.element[0]).each(function(){var r=e.data(this,"selectable-item");r.$element.removeClass("ui-unselecting"),r.unselecting=!1,r.startselected=!1,n._trigger("unselected",t,{unselected:r.element})}),e(".ui-selecting",this.element[0]).each(function(){var r=e.data(this,"selectable-item");r.$element.removeClass("ui-selecting").addClass("ui-selected"),r.selecting=!1,r.selected=!0,r.startselected=!0,n._trigger("selected",t,{selected:r.element})}),this._trigger("stop",t),this.helper.remove(),!1}})}(jQuery),function(e,t){e.widget("ui.sortable",e.ui.mouse,{version:"1.9.2",widgetEventPrefix:"sort",ready:!1,options:{appendTo:"parent",axis:!1,connectWith:!1,containment:!1,cursor:"auto",cursorAt:!1,dropOnEmpty:!0,forcePlaceholderSize:!1,forceHelperSize:!1,grid:!1,handle:!1,helper:"original",items:"> *",opacity:!1,placeholder:!1,revert:!1,scroll:!0,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1e3},_create:function(){var e=this.options;this.containerCache={},this.element.addClass("ui-sortable"),this.refresh(),this.floating=this.items.length?e.axis==="x"||/left|right/.test(this.items[0].item.css("float"))||/inline|table-cell/.test(this.items[0].item.css("display")):!1,this.offset=this.element.offset(),this._mouseInit(),this.ready=!0},_destroy:function(){this.element.removeClass("ui-sortable ui-sortable-disabled"),this._mouseDestroy();for(var e=this.items.length-1;e>=0;e--)this.items[e].item.removeData(this.widgetName+"-item");return this},_setOption:function(t,n){t==="disabled"?(this.options[t]=n,this.widget().toggleClass("ui-sortable-disabled",!!n)):e.Widget.prototype._setOption.apply(this,arguments)},_mouseCapture:function(t,n){var r=this;if(this.reverting)return!1;if(this.options.disabled||this.options.type=="static")return!1;this._refreshItems(t);var i=null,s=e(t.target).parents().each(function(){if(e.data(this,r.widgetName+"-item")==r)return i=e(this),!1});e.data(t.target,r.widgetName+"-item")==r&&(i=e(t.target));if(!i)return!1;if(this.options.handle&&!n){var o=!1;e(this.options.handle,i).find("*").andSelf().each(function(){this==t.target&&(o=!0)});if(!o)return!1}return this.currentItem=i,this._removeCurrentsFromItems(),!0},_mouseStart:function(t,n,r){var i=this.options;this.currentContainer=this,this.refreshPositions(),this.helper=this._createHelper(t),this._cacheHelperProportions(),this._cacheMargins(),this.scrollParent=this.helper.scrollParent(),this.offset=this.currentItem.offset(),this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left},e.extend(this.offset,{click:{left:t.pageX-this.offset.left,top:t.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()}),this.helper.css("position","absolute"),this.cssPosition=this.helper.css("position"),this.originalPosition=this._generatePosition(t),this.originalPageX=t.pageX,this.originalPageY=t.pageY,i.cursorAt&&this._adjustOffsetFromHelper(i.cursorAt),this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]},this.helper[0]!=this.currentItem[0]&&this.currentItem.hide(),this._createPlaceholder(),i.containment&&this._setContainment(),i.cursor&&(e("body").css("cursor")&&(this._storedCursor=e("body").css("cursor")),e("body").css("cursor",i.cursor)),i.opacity&&(this.helper.css("opacity")&&(this._storedOpacity=this.helper.css("opacity")),this.helper.css("opacity",i.opacity)),i.zIndex&&(this.helper.css("zIndex")&&(this._storedZIndex=this.helper.css("zIndex")),this.helper.css("zIndex",i.zIndex)),this.scrollParent[0]!=document&&this.scrollParent[0].tagName!="HTML"&&(this.overflowOffset=this.scrollParent.offset()),this._trigger("start",t,this._uiHash()),this._preserveHelperProportions||this._cacheHelperProportions();if(!r)for(var s=this.containers.length-1;s>=0;s--)this.containers[s]._trigger("activate",t,this._uiHash(this));return e.ui.ddmanager&&(e.ui.ddmanager.current=this),e.ui.ddmanager&&!i.dropBehaviour&&e.ui.ddmanager.prepareOffsets(this,t),this.dragging=!0,this.helper.addClass("ui-sortable-helper"),this._mouseDrag(t),!0},_mouseDrag:function(t){this.position=this._generatePosition(t),this.positionAbs=this._convertPositionTo("absolute"),this.lastPositionAbs||(this.lastPositionAbs=this.positionAbs);if(this.options.scroll){var n=this.options,r=!1;this.scrollParent[0]!=document&&this.scrollParent[0].tagName!="HTML"?(this.overflowOffset.top+this.scrollParent[0].offsetHeight-t.pageY<n.scrollSensitivity?this.scrollParent[0].scrollTop=r=this.scrollParent[0].scrollTop+n.scrollSpeed:t.pageY-this.overflowOffset.top<n.scrollSensitivity&&(this.scrollParent[0].scrollTop=r=this.scrollParent[0].scrollTop-n.scrollSpeed),this.overflowOffset.left+this.scrollParent[0].offsetWidth-t.pageX<n.scrollSensitivity?this.scrollParent[0].scrollLeft=r=this.scrollParent[0].scrollLeft+n.scrollSpeed:t.pageX-this.overflowOffset.left<n.scrollSensitivity&&(this.scrollParent[0].scrollLeft=r=this.scrollParent[0].scrollLeft-n.scrollSpeed)):(t.pageY-e(document).scrollTop()<n.scrollSensitivity?r=e(document).scrollTop(e(document).scrollTop()-n.scrollSpeed):e(window).height()-(t.pageY-e(document).scrollTop())<n.scrollSensitivity&&(r=e(document).scrollTop(e(document).scrollTop()+n.scrollSpeed)),t.pageX-e(document).scrollLeft()<n.scrollSensitivity?r=e(document).scrollLeft(e(document).scrollLeft()-n.scrollSpeed):e(window).width()-(t.pageX-e(document).scrollLeft())<n.scrollSensitivity&&(r=e(document).scrollLeft(e(document).scrollLeft()+n.scrollSpeed))),r!==!1&&e.ui.ddmanager&&!n.dropBehaviour&&e.ui.ddmanager.prepareOffsets(this,t)}this.positionAbs=this._convertPositionTo("absolute");if(!this.options.axis||this.options.axis!="y")this.helper[0].style.left=this.position.left+"px";if(!this.options.axis||this.options.axis!="x")this.helper[0].style.top=this.position.top+"px";for(var i=this.items.length-1;i>=0;i--){var s=this.items[i],o=s.item[0],u=this._intersectsWithPointer(s);if(!u)continue;if(s.instance!==this.currentContainer)continue;if(o!=this.currentItem[0]&&this.placeholder[u==1?"next":"prev"]()[0]!=o&&!e.contains(this.placeholder[0],o)&&(this.options.type=="semi-dynamic"?!e.contains(this.element[0],o):!0)){this.direction=u==1?"down":"up";if(this.options.tolerance!="pointer"&&!this._intersectsWithSides(s))break;this._rearrange(t,s),this._trigger("change",t,this._uiHash());break}}return this._contactContainers(t),e.ui.ddmanager&&e.ui.ddmanager.drag(this,t),this._trigger("sort",t,this._uiHash()),this.lastPositionAbs=this.positionAbs,!1},_mouseStop:function(t,n){if(!t)return;e.ui.ddmanager&&!this.options.dropBehaviour&&e.ui.ddmanager.drop(this,t);if(this.options.revert){var r=this,i=this.placeholder.offset();this.reverting=!0,e(this.helper).animate({left:i.left-this.offset.parent.left-this.margins.left+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollLeft),top:i.top-this.offset.parent.top-this.margins.top+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollTop)},parseInt(this.options.revert,10)||500,function(){r._clear(t)})}else this._clear(t,n);return!1},cancel:function(){if(this.dragging){this._mouseUp({target:null}),this.options.helper=="original"?this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"):this.currentItem.show();for(var t=this.containers.length-1;t>=0;t--)this.containers[t]._trigger("deactivate",null,this._uiHash(this)),this.containers[t].containerCache.over&&(this.containers[t]._trigger("out",null,this._uiHash(this)),this.containers[t].containerCache.over=0)}return this.placeholder&&(this.placeholder[0].parentNode&&this.placeholder[0].parentNode.removeChild(this.placeholder[0]),this.options.helper!="original"&&this.helper&&this.helper[0].parentNode&&this.helper.remove(),e.extend(this,{helper:null,dragging:!1,reverting:!1,_noFinalSort:null}),this.domPosition.prev?e(this.domPosition.prev).after(this.currentItem):e(this.domPosition.parent).prepend(this.currentItem)),this},serialize:function(t){var n=this._getItemsAsjQuery(t&&t.connected),r=[];return t=t||{},e(n).each(function(){var n=(e(t.item||this).attr(t.attribute||"id")||"").match(t.expression||/(.+)[-=_](.+)/);n&&r.push((t.key||n[1]+"[]")+"="+(t.key&&t.expression?n[1]:n[2]))}),!r.length&&t.key&&r.push(t.key+"="),r.join("&")},toArray:function(t){var n=this._getItemsAsjQuery(t&&t.connected),r=[];return t=t||{},n.each(function(){r.push(e(t.item||this).attr(t.attribute||"id")||"")}),r},_intersectsWith:function(e){var t=this.positionAbs.left,n=t+this.helperProportions.width,r=this.positionAbs.top,i=r+this.helperProportions.height,s=e.left,o=s+e.width,u=e.top,a=u+e.height,f=this.offset.click.top,l=this.offset.click.left,c=r+f>u&&r+f<a&&t+l>s&&t+l<o;return this.options.tolerance=="pointer"||this.options.forcePointerForContainers||this.options.tolerance!="pointer"&&this.helperProportions[this.floating?"width":"height"]>e[this.floating?"width":"height"]?c:s<t+this.helperProportions.width/2&&n-this.helperProportions.width/2<o&&u<r+this.helperProportions.height/2&&i-this.helperProportions.height/2<a},_intersectsWithPointer:function(t){var n=this.options.axis==="x"||e.ui.isOverAxis(this.positionAbs.top+this.offset.click.top,t.top,t.height),r=this.options.axis==="y"||e.ui.isOverAxis(this.positionAbs.left+this.offset.click.left,t.left,t.width),i=n&&r,s=this._getDragVerticalDirection(),o=this._getDragHorizontalDirection();return i?this.floating?o&&o=="right"||s=="down"?2:1:s&&(s=="down"?2:1):!1},_intersectsWithSides:function(t){var n=e.ui.isOverAxis(this.positionAbs.top+this.offset.click.top,t.top+t.height/2,t.height),r=e.ui.isOverAxis(this.positionAbs.left+this.offset.click.left,t.left+t.width/2,t.width),i=this._getDragVerticalDirection(),s=this._getDragHorizontalDirection();return this.floating&&s?s=="right"&&r||s=="left"&&!r:i&&(i=="down"&&n||i=="up"&&!n)},_getDragVerticalDirection:function(){var e=this.positionAbs.top-this.lastPositionAbs.top;return e!=0&&(e>0?"down":"up")},_getDragHorizontalDirection:function(){var e=this.positionAbs.left-this.lastPositionAbs.left;return e!=0&&(e>0?"right":"left")},refresh:function(e){return this._refreshItems(e),this.refreshPositions(),this},_connectWith:function(){var e=this.options;return e.connectWith.constructor==String?[e.connectWith]:e.connectWith},_getItemsAsjQuery:function(t){var n=[],r=[],i=this._connectWith();if(i&&t)for(var s=i.length-1;s>=0;s--){var o=e(i[s]);for(var u=o.length-1;u>=0;u--){var a=e.data(o[u],this.widgetName);a&&a!=this&&!a.options.disabled&&r.push([e.isFunction(a.options.items)?a.options.items.call(a.element):e(a.options.items,a.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),a])}}r.push([e.isFunction(this.options.items)?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):e(this.options.items,this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),this]);for(var s=r.length-1;s>=0;s--)r[s][0].each(function(){n.push(this)});return e(n)},_removeCurrentsFromItems:function(){var t=this.currentItem.find(":data("+this.widgetName+"-item)");this.items=e.grep(this.items,function(e){for(var n=0;n<t.length;n++)if(t[n]==e.item[0])return!1;return!0})},_refreshItems:function(t){this.items=[],this.containers=[this];var n=this.items,r=[[e.isFunction(this.options.items)?this.options.items.call(this.element[0],t,{item:this.currentItem}):e(this.options.items,this.element),this]],i=this._connectWith();if(i&&this.ready)for(var s=i.length-1;s>=0;s--){var o=e(i[s]);for(var u=o.length-1;u>=0;u--){var a=e.data(o[u],this.widgetName);a&&a!=this&&!a.options.disabled&&(r.push([e.isFunction(a.options.items)?a.options.items.call(a.element[0],t,{item:this.currentItem}):e(a.options.items,a.element),a]),this.containers.push(a))}}for(var s=r.length-1;s>=0;s--){var f=r[s][1],l=r[s][0];for(var u=0,c=l.length;u<c;u++){var h=e(l[u]);h.data(this.widgetName+"-item",f),n.push({item:h,instance:f,width:0,height:0,left:0,top:0})}}},refreshPositions:function(t){this.offsetParent&&this.helper&&(this.offset.parent=this._getParentOffset());for(var n=this.items.length-1;n>=0;n--){var r=this.items[n];if(r.instance!=this.currentContainer&&this.currentContainer&&r.item[0]!=this.currentItem[0])continue;var i=this.options.toleranceElement?e(this.options.toleranceElement,r.item):r.item;t||(r.width=i.outerWidth(),r.height=i.outerHeight());var s=i.offset();r.left=s.left,r.top=s.top}if(this.options.custom&&this.options.custom.refreshContainers)this.options.custom.refreshContainers.call(this);else for(var n=this.containers.length-1;n>=0;n--){var s=this.containers[n].element.offset();this.containers[n].containerCache.left=s.left,this.containers[n].containerCache.top=s.top,this.containers[n].containerCache.width=this.containers[n].element.outerWidth(),this.containers[n].containerCache.height=this.containers[n].element.outerHeight()}return this},_createPlaceholder:function(t){t=t||this;var n=t.options;if(!n.placeholder||n.placeholder.constructor==String){var r=n.placeholder;n.placeholder={element:function(){var n=e(document.createElement(t.currentItem[0].nodeName)).addClass(r||t.currentItem[0].className+" ui-sortable-placeholder").removeClass("ui-sortable-helper")[0];return r||(n.style.visibility="hidden"),n},update:function(e,i){if(r&&!n.forcePlaceholderSize)return;i.height()||i.height(t.currentItem.innerHeight()-parseInt(t.currentItem.css("paddingTop")||0,10)-parseInt(t.currentItem.css("paddingBottom")||0,10)),i.width()||i.width(t.currentItem.innerWidth()-parseInt(t.currentItem.css("paddingLeft")||0,10)-parseInt(t.currentItem.css("paddingRight")||0,10))}}}t.placeholder=e(n.placeholder.element.call(t.element,t.currentItem)),t.currentItem.after(t.placeholder),n.placeholder.update(t,t.placeholder)},_contactContainers:function(t){var n=null,r=null;for(var i=this.containers.length-1;i>=0;i--){if(e.contains(this.currentItem[0],this.containers[i].element[0]))continue;if(this._intersectsWith(this.containers[i].containerCache)){if(n&&e.contains(this.containers[i].element[0],n.element[0]))continue;n=this.containers[i],r=i}else this.containers[i].containerCache.over&&(this.containers[i]._trigger("out",t,this._uiHash(this)),this.containers[i].containerCache.over=0)}if(!n)return;if(this.containers.length===1)this.containers[r]._trigger("over",t,this._uiHash(this)),this.containers[r].containerCache.over=1;else{var s=1e4,o=null,u=this.containers[r].floating?"left":"top",a=this.containers[r].floating?"width":"height",f=this.positionAbs[u]+this.offset.click[u];for(var l=this.items.length-1;l>=0;l--){if(!e.contains(this.containers[r].element[0],this.items[l].item[0]))continue;if(this.items[l].item[0]==this.currentItem[0])continue;var c=this.items[l].item.offset()[u],h=!1;Math.abs(c-f)>Math.abs(c+this.items[l][a]-f)&&(h=!0,c+=this.items[l][a]),Math.abs(c-f)<s&&(s=Math.abs(c-f),o=this.items[l],this.direction=h?"up":"down")}if(!o&&!this.options.dropOnEmpty)return;this.currentContainer=this.containers[r],o?this._rearrange(t,o,null,!0):this._rearrange(t,null,this.containers[r].element,!0),this._trigger("change",t,this._uiHash()),this.containers[r]._trigger("change",t,this._uiHash(this)),this.options.placeholder.update(this.currentContainer,this.placeholder),this.containers[r]._trigger("over",t,this._uiHash(this)),this.containers[r].containerCache.over=1}},_createHelper:function(t){var n=this.options,r=e.isFunction(n.helper)?e(n.helper.apply(this.element[0],[t,this.currentItem])):n.helper=="clone"?this.currentItem.clone():this.currentItem;return r.parents("body").length||e(n.appendTo!="parent"?n.appendTo:this.currentItem[0].parentNode)[0].appendChild(r[0]),r[0]==this.currentItem[0]&&(this._storedCSS={width:this.currentItem[0].style.width,height:this.currentItem[0].style.height,position:this.currentItem.css("position"),top:this.currentItem.css("top"),left:this.currentItem.css("left")}),(r[0].style.width==""||n.forceHelperSize)&&r.width(this.currentItem.width()),(r[0].style.height==""||n.forceHelperSize)&&r.height(this.currentItem.height()),r},_adjustOffsetFromHelper:function(t){typeof t=="string"&&(t=t.split(" ")),e.isArray(t)&&(t={left:+t[0],top:+t[1]||0}),"left"in t&&(this.offset.click.left=t.left+this.margins.left),"right"in t&&(this.offset.click.left=this.helperProportions.width-t.right+this.margins.left),"top"in t&&(this.offset.click.top=t.top+this.margins.top),"bottom"in t&&(this.offset.click.top=this.helperProportions.height-t.bottom+this.margins.top)},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var t=this.offsetParent.offset();this.cssPosition=="absolute"&&this.scrollParent[0]!=document&&e.contains(this.scrollParent[0],this.offsetParent[0])&&(t.left+=this.scrollParent.scrollLeft(),t.top+=this.scrollParent.scrollTop());if(this.offsetParent[0]==document.body||this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()=="html"&&e.ui.ie)t={top:0,left:0};return{top:t.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:t.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if(this.cssPosition=="relative"){var e=this.currentItem.position();return{top:e.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:e.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.currentItem.css("marginLeft"),10)||0,top:parseInt(this.currentItem.css("marginTop"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var t=this.options;t.containment=="parent"&&(t.containment=this.helper[0].parentNode);if(t.containment=="document"||t.containment=="window")this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,e(t.containment=="document"?document:window).width()-this.helperProportions.width-this.margins.left,(e(t.containment=="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top];if(!/^(document|window|parent)$/.test(t.containment)){var n=e(t.containment)[0],r=e(t.containment).offset(),i=e(n).css("overflow")!="hidden";this.containment=[r.left+(parseInt(e(n).css("borderLeftWidth"),10)||0)+(parseInt(e(n).css("paddingLeft"),10)||0)-this.margins.left,r.top+(parseInt(e(n).css("borderTopWidth"),10)||0)+(parseInt(e(n).css("paddingTop"),10)||0)-this.margins.top,r.left+(i?Math.max(n.scrollWidth,n.offsetWidth):n.offsetWidth)-(parseInt(e(n).css("borderLeftWidth"),10)||0)-(parseInt(e(n).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,r.top+(i?Math.max(n.scrollHeight,n.offsetHeight):n.offsetHeight)-(parseInt(e(n).css("borderTopWidth"),10)||0)-(parseInt(e(n).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top]}},_convertPositionTo:function(t,n){n||(n=this.position);var r=t=="absolute"?1:-1,i=this.options,s=this.cssPosition!="absolute"||this.scrollParent[0]!=document&&!!e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,o=/(html|body)/i.test(s[0].tagName);return{top:n.top+this.offset.relative.top*r+this.offset.parent.top*r-(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():o?0:s.scrollTop())*r,left:n.left+this.offset.relative.left*r+this.offset.parent.left*r-(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():o?0:s.scrollLeft())*r}},_generatePosition:function(t){var n=this.options,r=this.cssPosition!="absolute"||this.scrollParent[0]!=document&&!!e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,i=/(html|body)/i.test(r[0].tagName);this.cssPosition=="relative"&&(this.scrollParent[0]==document||this.scrollParent[0]==this.offsetParent[0])&&(this.offset.relative=this._getRelativeOffset());var s=t.pageX,o=t.pageY;if(this.originalPosition){this.containment&&(t.pageX-this.offset.click.left<this.containment[0]&&(s=this.containment[0]+this.offset.click.left),t.pageY-this.offset.click.top<this.containment[1]&&(o=this.containment[1]+this.offset.click.top),t.pageX-this.offset.click.left>this.containment[2]&&(s=this.containment[2]+this.offset.click.left),t.pageY-this.offset.click.top>this.containment[3]&&(o=this.containment[3]+this.offset.click.top));if(n.grid){var u=this.originalPageY+Math.round((o-this.originalPageY)/n.grid[1])*n.grid[1];o=this.containment?u-this.offset.click.top<this.containment[1]||u-this.offset.click.top>this.containment[3]?u-this.offset.click.top<this.containment[1]?u+n.grid[1]:u-n.grid[1]:u:u;var a=this.originalPageX+Math.round((s-this.originalPageX)/n.grid[0])*n.grid[0];s=this.containment?a-this.offset.click.left<this.containment[0]||a-this.offset.click.left>this.containment[2]?a-this.offset.click.left<this.containment[0]?a+n.grid[0]:a-n.grid[0]:a:a}}return{top:o-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():i?0:r.scrollTop()),left:s-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():i?0:r.scrollLeft())}},_rearrange:function(e,t,n,r){n?n[0].appendChild(this.placeholder[0]):t.item[0].parentNode.insertBefore(this.placeholder[0],this.direction=="down"?t.item[0]:t.item[0].nextSibling),this.counter=this.counter?++this.counter:1;var i=this.counter;this._delay(function(){i==this.counter&&this.refreshPositions(!r)})},_clear:function(t,n){this.reverting=!1;var r=[];!this._noFinalSort&&this.currentItem.parent().length&&this.placeholder.before(this.currentItem),this._noFinalSort=null;if(this.helper[0]==this.currentItem[0]){for(var i in this._storedCSS)if(this._storedCSS[i]=="auto"||this._storedCSS[i]=="static")this._storedCSS[i]="";this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else this.currentItem.show();this.fromOutside&&!n&&r.push(function(e){this._trigger("receive",e,this._uiHash(this.fromOutside))}),(this.fromOutside||this.domPosition.prev!=this.currentItem.prev().not(".ui-sortable-helper")[0]||this.domPosition.parent!=this.currentItem.parent()[0])&&!n&&r.push(function(e){this._trigger("update",e,this._uiHash())}),this!==this.currentContainer&&(n||(r.push(function(e){this._trigger("remove",e,this._uiHash())}),r.push(function(e){return function(t){e._trigger("receive",t,this._uiHash(this))}}.call(this,this.currentContainer)),r.push(function(e){return function(t){e._trigger("update",t,this._uiHash(this))}}.call(this,this.currentContainer))));for(var i=this.containers.length-1;i>=0;i--)n||r.push(function(e){return function(t){e._trigger("deactivate",t,this._uiHash(this))}}.call(this,this.containers[i])),this.containers[i].containerCache.over&&(r.push(function(e){return function(t){e._trigger("out",t,this._uiHash(this))}}.call(this,this.containers[i])),this.containers[i].containerCache.over=0);this._storedCursor&&e("body").css("cursor",this._storedCursor),this._storedOpacity&&this.helper.css("opacity",this._storedOpacity),this._storedZIndex&&this.helper.css("zIndex",this._storedZIndex=="auto"?"":this._storedZIndex),this.dragging=!1;if(this.cancelHelperRemoval){if(!n){this._trigger("beforeStop",t,this._uiHash());for(var i=0;i<r.length;i++)r[i].call(this,t);this._trigger("stop",t,this._uiHash())}return this.fromOutside=!1,!1}n||this._trigger("beforeStop",t,this._uiHash()),this.placeholder[0].parentNode.removeChild(this.placeholder[0]),this.helper[0]!=this.currentItem[0]&&this.helper.remove(),this.helper=null;if(!n){for(var i=0;i<r.length;i++)r[i].call(this,t);this._trigger("stop",t,this._uiHash())}return this.fromOutside=!1,!0},_trigger:function(){e.Widget.prototype._trigger.apply(this,arguments)===!1&&this.cancel()},_uiHash:function(t){var n=t||this;return{helper:n.helper,placeholder:n.placeholder||e([]),position:n.position,originalPosition:n.originalPosition,offset:n.positionAbs,item:n.currentItem,sender:t?t.element:null}}})}(jQuery),jQuery.effects||function(e,t){var n=e.uiBackCompat!==!1,r="ui-effects-";e.effects={effect:{}},function(t,n){function r(e,t,n){var r=c[t.type]||{};return e==null?n||!t.def?null:t.def:(e=r.floor?~~e:parseFloat(e),isNaN(e)?t.def:r.mod?(e+r.mod)%r.mod:0>e?0:r.max<e?r.max:e)}function i(e){var n=f(),r=n._rgba=[];return e=e.toLowerCase(),v(a,function(t,i){var s,o=i.re.exec(e),u=o&&i.parse(o),a=i.space||"rgba";if(u)return s=n[a](u),n[l[a].cache]=s[l[a].cache],r=n._rgba=s._rgba,!1}),r.length?(r.join()==="0,0,0,0"&&t.extend(r,d.transparent),n):d[e]}function s(e,t,n){return n=(n+1)%1,n*6<1?e+(t-e)*n*6:n*2<1?t:n*3<2?e+(t-e)*(2/3-n)*6:e}var o="backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor".split(" "),u=/^([\-+])=\s*(\d+\.?\d*)/,a=[{re:/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d+(?:\.\d+)?)\s*)?\)/,parse:function(e){return[e[1],e[2],e[3],e[4]]}},{re:/rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d+(?:\.\d+)?)\s*)?\)/,parse:function(e){return[e[1]*2.55,e[2]*2.55,e[3]*2.55,e[4]]}},{re:/#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})/,parse:function(e){return[parseInt(e[1],16),parseInt(e[2],16),parseInt(e[3],16)]}},{re:/#([a-f0-9])([a-f0-9])([a-f0-9])/,parse:function(e){return[parseInt(e[1]+e[1],16),parseInt(e[2]+e[2],16),parseInt(e[3]+e[3],16)]}},{re:/hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d+(?:\.\d+)?)\s*)?\)/,space:"hsla",parse:function(e){return[e[1],e[2]/100,e[3]/100,e[4]]}}],f=t.Color=function(e,n,r,i){return new t.Color.fn.parse(e,n,r,i)},l={rgba:{props:{red:{idx:0,type:"byte"},green:{idx:1,type:"byte"},blue:{idx:2,type:"byte"}}},hsla:{props:{hue:{idx:0,type:"degrees"},saturation:{idx:1,type:"percent"},lightness:{idx:2,type:"percent"}}}},c={"byte":{floor:!0,max:255},percent:{max:1},degrees:{mod:360,floor:!0}},h=f.support={},p=t("<p>")[0],d,v=t.each;p.style.cssText="background-color:rgba(1,1,1,.5)",h.rgba=p.style.backgroundColor.indexOf("rgba")>-1,v(l,function(e,t){t.cache="_"+e,t.props.alpha={idx:3,type:"percent",def:1}}),f.fn=t.extend(f.prototype,{parse:function(s,o,u,a){if(s===n)return this._rgba=[null,null,null,null],this;if(s.jquery||s.nodeType)s=t(s).css(o),o=n;var c=this,h=t.type(s),p=this._rgba=[];o!==n&&(s=[s,o,u,a],h="array");if(h==="string")return this.parse(i(s)||d._default);if(h==="array")return v(l.rgba.props,function(e,t){p[t.idx]=r(s[t.idx],t)}),this;if(h==="object")return s instanceof f?v(l,function(e,t){s[t.cache]&&(c[t.cache]=s[t.cache].slice())}):v(l,function(t,n){var i=n.cache;v(n.props,function(e,t){if(!c[i]&&n.to){if(e==="alpha"||s[e]==null)return;c[i]=n.to(c._rgba)}c[i][t.idx]=r(s[e],t,!0)}),c[i]&&e.inArray(null,c[i].slice(0,3))<0&&(c[i][3]=1,n.from&&(c._rgba=n.from(c[i])))}),this},is:function(e){var t=f(e),n=!0,r=this;return v(l,function(e,i){var s,o=t[i.cache];return o&&(s=r[i.cache]||i.to&&i.to(r._rgba)||[],v(i.props,function(e,t){if(o[t.idx]!=null)return n=o[t.idx]===s[t.idx],n})),n}),n},_space:function(){var e=[],t=this;return v(l,function(n,r){t[r.cache]&&e.push(n)}),e.pop()},transition:function(e,t){var n=f(e),i=n._space(),s=l[i],o=this.alpha()===0?f("transparent"):this,u=o[s.cache]||s.to(o._rgba),a=u.slice();return n=n[s.cache],v(s.props,function(e,i){var s=i.idx,o=u[s],f=n[s],l=c[i.type]||{};if(f===null)return;o===null?a[s]=f:(l.mod&&(f-o>l.mod/2?o+=l.mod:o-f>l.mod/2&&(o-=l.mod)),a[s]=r((f-o)*t+o,i))}),this[i](a)},blend:function(e){if(this._rgba[3]===1)return this;var n=this._rgba.slice(),r=n.pop(),i=f(e)._rgba;return f(t.map(n,function(e,t){return(1-r)*i[t]+r*e}))},toRgbaString:function(){var e="rgba(",n=t.map(this._rgba,function(e,t){return e==null?t>2?1:0:e});return n[3]===1&&(n.pop(),e="rgb("),e+n.join()+")"},toHslaString:function(){var e="hsla(",n=t.map(this.hsla(),function(e,t){return e==null&&(e=t>2?1:0),t&&t<3&&(e=Math.round(e*100)+"%"),e});return n[3]===1&&(n.pop(),e="hsl("),e+n.join()+")"},toHexString:function(e){var n=this._rgba.slice(),r=n.pop();return e&&n.push(~~(r*255)),"#"+t.map(n,function(e){return e=(e||0).toString(16),e.length===1?"0"+e:e}).join("")},toString:function(){return this._rgba[3]===0?"transparent":this.toRgbaString()}}),f.fn.parse.prototype=f.fn,l.hsla.to=function(e){if(e[0]==null||e[1]==null||e[2]==null)return[null,null,null,e[3]];var t=e[0]/255,n=e[1]/255,r=e[2]/255,i=e[3],s=Math.max(t,n,r),o=Math.min(t,n,r),u=s-o,a=s+o,f=a*.5,l,c;return o===s?l=0:t===s?l=60*(n-r)/u+360:n===s?l=60*(r-t)/u+120:l=60*(t-n)/u+240,f===0||f===1?c=f:f<=.5?c=u/a:c=u/(2-a),[Math.round(l)%360,c,f,i==null?1:i]},l.hsla.from=function(e){if(e[0]==null||e[1]==null||e[2]==null)return[null,null,null,e[3]];var t=e[0]/360,n=e[1],r=e[2],i=e[3],o=r<=.5?r*(1+n):r+n-r*n,u=2*r-o;return[Math.round(s(u,o,t+1/3)*255),Math.round(s(u,o,t)*255),Math.round(s(u,o,t-1/3)*255),i]},v(l,function(e,i){var s=i.props,o=i.cache,a=i.to,l=i.from;f.fn[e]=function(e){a&&!this[o]&&(this[o]=a(this._rgba));if(e===n)return this[o].slice();var i,u=t.type(e),c=u==="array"||u==="object"?e:arguments,h=this[o].slice();return v(s,function(e,t){var n=c[u==="object"?e:t.idx];n==null&&(n=h[t.idx]),h[t.idx]=r(n,t)}),l?(i=f(l(h)),i[o]=h,i):f(h)},v(s,function(n,r){if(f.fn[n])return;f.fn[n]=function(i){var s=t.type(i),o=n==="alpha"?this._hsla?"hsla":"rgba":e,a=this[o](),f=a[r.idx],l;return s==="undefined"?f:(s==="function"&&(i=i.call(this,f),s=t.type(i)),i==null&&r.empty?this:(s==="string"&&(l=u.exec(i),l&&(i=f+parseFloat(l[2])*(l[1]==="+"?1:-1))),a[r.idx]=i,this[o](a)))}})}),v(o,function(e,n){t.cssHooks[n]={set:function(e,r){var s,o,u="";if(t.type(r)!=="string"||(s=i(r))){r=f(s||r);if(!h.rgba&&r._rgba[3]!==1){o=n==="backgroundColor"?e.parentNode:e;while((u===""||u==="transparent")&&o&&o.style)try{u=t.css(o,"backgroundColor"),o=o.parentNode}catch(a){}r=r.blend(u&&u!=="transparent"?u:"_default")}r=r.toRgbaString()}try{e.style[n]=r}catch(l){}}},t.fx.step[n]=function(e){e.colorInit||(e.start=f(e.elem,n),e.end=f(e.end),e.colorInit=!0),t.cssHooks[n].set(e.elem,e.start.transition(e.end,e.pos))}}),t.cssHooks.borderColor={expand:function(e){var t={};return v(["Top","Right","Bottom","Left"],function(n,r){t["border"+r+"Color"]=e}),t}},d=t.Color.names={aqua:"#00ffff",black:"#000000",blue:"#0000ff",fuchsia:"#ff00ff",gray:"#808080",green:"#008000",lime:"#00ff00",maroon:"#800000",navy:"#000080",olive:"#808000",purple:"#800080",red:"#ff0000",silver:"#c0c0c0",teal:"#008080",white:"#ffffff",yellow:"#ffff00",transparent:[null,null,null,0],_default:"#ffffff"}}(jQuery),function(){function n(){var t=this.ownerDocument.defaultView?this.ownerDocument.defaultView.getComputedStyle(this,null):this.currentStyle,n={},r,i;if(t&&t.length&&t[0]&&t[t[0]]){i=t.length;while(i--)r=t[i],typeof t[r]=="string"&&(n[e.camelCase(r)]=t[r])}else for(r in t)typeof t[r]=="string"&&(n[r]=t[r]);return n}function r(t,n){var r={},i,o;for(i in n)o=n[i],t[i]!==o&&!s[i]&&(e.fx.step[i]||!isNaN(parseFloat(o)))&&(r[i]=o);return r}var i=["add","remove","toggle"],s={border:1,borderBottom:1,borderColor:1,borderLeft:1,borderRight:1,borderTop:1,borderWidth:1,margin:1,padding:1};e.each(["borderLeftStyle","borderRightStyle","borderBottomStyle","borderTopStyle"],function(t,n){e.fx.step[n]=function(e){if(e.end!=="none"&&!e.setAttr||e.pos===1&&!e.setAttr)jQuery.style(e.elem,n,e.end),e.setAttr=!0}}),e.effects.animateClass=function(t,s,o,u){var a=e.speed(s,o,u);return this.queue(function(){var s=e(this),o=s.attr("class")||"",u,f=a.children?s.find("*").andSelf():s;f=f.map(function(){var t=e(this);return{el:t,start:n.call(this)}}),u=function(){e.each(i,function(e,n){t[n]&&s[n+"Class"](t[n])})},u(),f=f.map(function(){return this.end=n.call(this.el[0]),this.diff=r(this.start,this.end),this}),s.attr("class",o),f=f.map(function(){var t=this,n=e.Deferred(),r=jQuery.extend({},a,{queue:!1,complete:function(){n.resolve(t)}});return this.el.animate(this.diff,r),n.promise()}),e.when.apply(e,f.get()).done(function(){u(),e.each(arguments,function(){var t=this.el;e.each(this.diff,function(e){t.css(e,"")})}),a.complete.call(s[0])})})},e.fn.extend({_addClass:e.fn.addClass,addClass:function(t,n,r,i){return n?e.effects.animateClass.call(this,{add:t},n,r,i):this._addClass(t)},_removeClass:e.fn.removeClass,removeClass:function(t,n,r,i){return n?e.effects.animateClass.call(this,{remove:t},n,r,i):this._removeClass(t)},_toggleClass:e.fn.toggleClass,toggleClass:function(n,r,i,s,o){return typeof r=="boolean"||r===t?i?e.effects.animateClass.call(this,r?{add:n}:{remove:n},i,s,o):this._toggleClass(n,r):e.effects.animateClass.call(this,{toggle:n},r,i,s)},switchClass:function(t,n,r,i,s){return e.effects.animateClass.call(this,{add:n,remove:t},r,i,s)}})}(),function(){function i(t,n,r,i){e.isPlainObject(t)&&(n=t,t=t.effect),t={effect:t},n==null&&(n={}),e.isFunction(n)&&(i=n,r=null,n={});if(typeof n=="number"||e.fx.speeds[n])i=r,r=n,n={};return e.isFunction(r)&&(i=r,r=null),n&&e.extend(t,n),r=r||n.duration,t.duration=e.fx.off?0:typeof r=="number"?r:r in e.fx.speeds?e.fx.speeds[r]:e.fx.speeds._default,t.complete=i||n.complete,t}function s(t){return!t||typeof t=="number"||e.fx.speeds[t]?!0:typeof t=="string"&&!e.effects.effect[t]?n&&e.effects[t]?!1:!0:!1}e.extend(e.effects,{version:"1.9.2",save:function(e,t){for(var n=0;n<t.length;n++)t[n]!==null&&e.data(r+t[n],e[0].style[t[n]])},restore:function(e,n){var i,s;for(s=0;s<n.length;s++)n[s]!==null&&(i=e.data(r+n[s]),i===t&&(i=""),e.css(n[s],i))},setMode:function(e,t){return t==="toggle"&&(t=e.is(":hidden")?"show":"hide"),t},getBaseline:function(e,t){var n,r;switch(e[0]){case"top":n=0;break;case"middle":n=.5;break;case"bottom":n=1;break;default:n=e[0]/t.height}switch(e[1]){case"left":r=0;break;case"center":r=.5;break;case"right":r=1;break;default:r=e[1]/t.width}return{x:r,y:n}},createWrapper:function(t){if(t.parent().is(".ui-effects-wrapper"))return t.parent();var n={width:t.outerWidth(!0),height:t.outerHeight(!0),"float":t.css("float")},r=e("<div></div>").addClass("ui-effects-wrapper").css({fontSize:"100%",background:"transparent",border:"none",margin:0,padding:0}),i={width:t.width(),height:t.height()},s=document.activeElement;try{s.id}catch(o){s=document.body}return t.wrap(r),(t[0]===s||e.contains(t[0],s))&&e(s).focus(),r=t.parent(),t.css("position")==="static"?(r.css({position:"relative"}),t.css({position:"relative"})):(e.extend(n,{position:t.css("position"),zIndex:t.css("z-index")}),e.each(["top","left","bottom","right"],function(e,r){n[r]=t.css(r),isNaN(parseInt(n[r],10))&&(n[r]="auto")}),t.css({position:"relative",top:0,left:0,right:"auto",bottom:"auto"})),t.css(i),r.css(n).show()},removeWrapper:function(t){var n=document.activeElement;return t.parent().is(".ui-effects-wrapper")&&(t.parent().replaceWith(t),(t[0]===n||e.contains(t[0],n))&&e(n).focus()),t},setTransition:function(t,n,r,i){return i=i||{},e.each(n,function(e,n){var s=t.cssUnit(n);s[0]>0&&(i[n]=s[0]*r+s[1])}),i}}),e.fn.extend({effect:function(){function t(t){function n(){e.isFunction(s)&&s.call(i[0]),e.isFunction(t)&&t()}var i=e(this),s=r.complete,o=r.mode;(i.is(":hidden")?o==="hide":o==="show")?n():u.call(i[0],r,n)}var r=i.apply(this,arguments),s=r.mode,o=r.queue,u=e.effects.effect[r.effect],a=!u&&n&&e.effects[r.effect];return e.fx.off||!u&&!a?s?this[s](r.duration,r.complete):this.each(function(){r.complete&&r.complete.call(this)}):u?o===!1?this.each(t):this.queue(o||"fx",t):a.call(this,{options:r,duration:r.duration,callback:r.complete,mode:r.mode})},_show:e.fn.show,show:function(e){if(s(e))return this._show.apply(this,arguments);var t=i.apply(this,arguments);return t.mode="show",this.effect.call(this,t)},_hide:e.fn.hide,hide:function(e){if(s(e))return this._hide.apply(this,arguments);var t=i.apply(this,arguments);return t.mode="hide",this.effect.call(this,t)},__toggle:e.fn.toggle,toggle:function(t){if(s(t)||typeof t=="boolean"||e.isFunction(t))return this.__toggle.apply(this,arguments);var n=i.apply(this,arguments);return n.mode="toggle",this.effect.call(this,n)},cssUnit:function(t){var n=this.css(t),r=[];return e.each(["em","px","%","pt"],function(e,t){n.indexOf(t)>0&&(r=[parseFloat(n),t])}),r}})}(),function(){var t={};e.each(["Quad","Cubic","Quart","Quint","Expo"],function(e,n){t[n]=function(t){return Math.pow(t,e+2)}}),e.extend(t,{Sine:function(e){return 1-Math.cos(e*Math.PI/2)},Circ:function(e){return 1-Math.sqrt(1-e*e)},Elastic:function(e){return e===0||e===1?e:-Math.pow(2,8*(e-1))*Math.sin(((e-1)*80-7.5)*Math.PI/15)},Back:function(e){return e*e*(3*e-2)},Bounce:function(e){var t,n=4;while(e<((t=Math.pow(2,--n))-1)/11);return 1/Math.pow(4,3-n)-7.5625*Math.pow((t*3-2)/22-e,2)}}),e.each(t,function(t,n){e.easing["easeIn"+t]=n,e.easing["easeOut"+t]=function(e){return 1-n(1-e)},e.easing["easeInOut"+t]=function(e){return e<.5?n(e*2)/2:1-n(e*-2+2)/2}})}()}(jQuery),function(e,t){var n=/up|down|vertical/,r=/up|left|vertical|horizontal/;e.effects.effect.blind=function(t,i){var s=e(this),o=["position","top","bottom","left","right","height","width"],u=e.effects.setMode(s,t.mode||"hide"),a=t.direction||"up",f=n.test(a),l=f?"height":"width",c=f?"top":"left",h=r.test(a),p={},d=u==="show",v,m,g;s.parent().is(".ui-effects-wrapper")?e.effects.save(s.parent(),o):e.effects.save(s,o),s.show(),v=e.effects.createWrapper(s).css({overflow:"hidden"}),m=v[l](),g=parseFloat(v.css(c))||0,p[l]=d?m:0,h||(s.css(f?"bottom":"right",0).css(f?"top":"left","auto").css({position:"absolute"}),p[c]=d?g:m+g),d&&(v.css(l,0),h||v.css(c,g+m)),v.animate(p,{duration:t.duration,easing:t.easing,queue:!1,complete:function(){u==="hide"&&s.hide(),e.effects.restore(s,o),e.effects.removeWrapper(s),i()}})}}(jQuery),function(e,t){e.effects.effect.bounce=function(t,n){var r=e(this),i=["position","top","bottom","left","right","height","width"],s=e.effects.setMode(r,t.mode||"effect"),o=s==="hide",u=s==="show",a=t.direction||"up",f=t.distance,l=t.times||5,c=l*2+(u||o?1:0),h=t.duration/c,p=t.easing,d=a==="up"||a==="down"?"top":"left",v=a==="up"||a==="left",m,g,y,b=r.queue(),w=b.length;(u||o)&&i.push("opacity"),e.effects.save(r,i),r.show(),e.effects.createWrapper(r),f||(f=r[d==="top"?"outerHeight":"outerWidth"]()/3),u&&(y={opacity:1},y[d]=0,r.css("opacity",0).css(d,v?-f*2:f*2).animate(y,h,p)),o&&(f/=Math.pow(2,l-1)),y={},y[d]=0;for(m=0;m<l;m++)g={},g[d]=(v?"-=":"+=")+f,r.animate(g,h,p).animate(y,h,p),f=o?f*2:f/2;o&&(g={opacity:0},g[d]=(v?"-=":"+=")+f,r.animate(g,h,p)),r.queue(function(){o&&r.hide(),e.effects.restore(r,i),e.effects.removeWrapper(r),n()}),w>1&&b.splice.apply(b,[1,0].concat(b.splice(w,c+1))),r.dequeue()}}(jQuery),function(e,t){e.effects.effect.clip=function(t,n){var r=e(this),i=["position","top","bottom","left","right","height","width"],s=e.effects.setMode(r,t.mode||"hide"),o=s==="show",u=t.direction||"vertical",a=u==="vertical",f=a?"height":"width",l=a?"top":"left",c={},h,p,d;e.effects.save(r,i),r.show(),h=e.effects.createWrapper(r).css({overflow:"hidden"}),p=r[0].tagName==="IMG"?h:r,d=p[f](),o&&(p.css(f,0),p.css(l,d/2)),c[f]=o?d:0,c[l]=o?0:d/2,p.animate(c,{queue:!1,duration:t.duration,easing:t.easing,complete:function(){o||r.hide(),e.effects.restore(r,i),e.effects.removeWrapper(r),n()}})}}(jQuery),function(e,t){e.effects.effect.drop=function(t,n){var r=e(this),i=["position","top","bottom","left","right","opacity","height","width"],s=e.effects.setMode(r,t.mode||"hide"),o=s==="show",u=t.direction||"left",a=u==="up"||u==="down"?"top":"left",f=u==="up"||u==="left"?"pos":"neg",l={opacity:o?1:0},c;e.effects.save(r,i),r.show(),e.effects.createWrapper(r),c=t.distance||r[a==="top"?"outerHeight":"outerWidth"](!0)/2,o&&r.css("opacity",0).css(a,f==="pos"?-c:c),l[a]=(o?f==="pos"?"+=":"-=":f==="pos"?"-=":"+=")+c,r.animate(l,{queue:!1,duration:t.duration,easing:t.easing,complete:function(){s==="hide"&&r.hide(),e.effects.restore(r,i),e.effects.removeWrapper(r),n()}})}}(jQuery),function(e,t){e.effects.effect.explode=function(t,n){function r(){p.push(this),p.length===s*o&&i()}function i(){u.css({visibility:"visible"}),e(p).remove(),f||u.hide(),n()}var s=t.pieces?Math.round(Math.sqrt(t.pieces)):3,o=s,u=e(this),a=e.effects.setMode(u,t.mode||"hide"),f=a==="show",l=u.show().css("visibility","hidden").offset(),c=Math.ceil(u.outerWidth()/o),h=Math.ceil(u.outerHeight()/s),p=[],d,v,m,g,y,b;for(d=0;d<s;d++){g=l.top+d*h,b=d-(s-1)/2;for(v=0;v<o;v++)m=l.left+v*c,y=v-(o-1)/2,u.clone().appendTo("body").wrap("<div></div>").css({position:"absolute",visibility:"visible",left:-v*c,top:-d*h}).parent().addClass("ui-effects-explode").css({position:"absolute",overflow:"hidden",width:c,height:h,left:m+(f?y*c:0),top:g+(f?b*h:0),opacity:f?0:1}).animate({left:m+(f?0:y*c),top:g+(f?0:b*h),opacity:f?1:0},t.duration||500,t.easing,r)}}}(jQuery),function(e,t){e.effects.effect.fade=function(t,n){var r=e(this),i=e.effects.setMode(r,t.mode||"toggle");r.animate({opacity:i},{queue:!1,duration:t.duration,easing:t.easing,complete:n})}}(jQuery),function(e,t){e.effects.effect.fold=function(t,n){var r=e(this),i=["position","top","bottom","left","right","height","width"],s=e.effects.setMode(r,t.mode||"hide"),o=s==="show",u=s==="hide",a=t.size||15,f=/([0-9]+)%/.exec(a),l=!!t.horizFirst,c=o!==l,h=c?["width","height"]:["height","width"],p=t.duration/2,d,v,m={},g={};e.effects.save(r,i),r.show(),d=e.effects.createWrapper(r).css({overflow:"hidden"}),v=c?[d.width(),d.height()]:[d.height(),d.width()],f&&(a=parseInt(f[1],10)/100*v[u?0:1]),o&&d.css(l?{height:0,width:a}:{height:a,width:0}),m[h[0]]=o?v[0]:a,g[h[1]]=o?v[1]:0,d.animate(m,p,t.easing).animate(g,p,t.easing,function(){u&&r.hide(),e.effects.restore(r,i),e.effects.removeWrapper(r),n()})}}(jQuery),function(e,t){e.effects.effect.highlight=function(t,n){var r=e(this),i=["backgroundImage","backgroundColor","opacity"],s=e.effects.setMode(r,t.mode||"show"),o={backgroundColor:r.css("backgroundColor")};s==="hide"&&(o.opacity=0),e.effects.save(r,i),r.show().css({backgroundImage:"none",backgroundColor:t.color||"#ffff99"}).animate(o,{queue:!1,duration:t.duration,easing:t.easing,complete:function(){s==="hide"&&r.hide(),e.effects.restore(r,i),n()}})}}(jQuery),function(e,t){e.effects.effect.pulsate=function(t,n){var r=e(this),i=e.effects.setMode(r,t.mode||"show"),s=i==="show",o=i==="hide",u=s||i==="hide",a=(t.times||5)*2+(u?1:0),f=t.duration/a,l=0,c=r.queue(),h=c.length,p;if(s||!r.is(":visible"))r.css("opacity",0).show(),l=1;for(p=1;p<a;p++)r.animate({opacity:l},f,t.easing),l=1-l;r.animate({opacity:l},f,t.easing),r.queue(function(){o&&r.hide(),n()}),h>1&&c.splice.apply(c,[1,0].concat(c.splice(h,a+1))),r.dequeue()}}(jQuery),function(e,t){e.effects.effect.puff=function(t,n){var r=e(this),i=e.effects.setMode(r,t.mode||"hide"),s=i==="hide",o=parseInt(t.percent,10)||150,u=o/100,a={height:r.height(),width:r.width(),outerHeight:r.outerHeight(),outerWidth:r.outerWidth()};e.extend(t,{effect:"scale",queue:!1,fade:!0,mode:i,complete:n,percent:s?o:100,from:s?a:{height:a.height*u,width:a.width*u,outerHeight:a.outerHeight*u,outerWidth:a.outerWidth*u}}),r.effect(t)},e.effects.effect.scale=function(t,n){var r=e(this),i=e.extend(!0,{},t),s=e.effects.setMode(r,t.mode||"effect"),o=parseInt(t.percent,10)||(parseInt(t.percent,10)===0?0:s==="hide"?0:100),u=t.direction||"both",a=t.origin,f={height:r.height(),width:r.width(),outerHeight:r.outerHeight(),outerWidth:r.outerWidth()},l={y:u!=="horizontal"?o/100:1,x:u!=="vertical"?o/100:1};i.effect="size",i.queue=!1,i.complete=n,s!=="effect"&&(i.origin=a||["middle","center"],i.restore=!0),i.from=t.from||(s==="show"?{height:0,width:0,outerHeight:0,outerWidth:0}:f),i.to={height:f.height*l.y,width:f.width*l.x,outerHeight:f.outerHeight*l.y,outerWidth:f.outerWidth*l.x},i.fade&&(s==="show"&&(i.from.opacity=0,i.to.opacity=1),s==="hide"&&(i.from.opacity=1,i.to.opacity=0)),r.effect(i)},e.effects.effect.size=function(t,n){var r,i,s,o=e(this),u=["position","top","bottom","left","right","width","height","overflow","opacity"],a=["position","top","bottom","left","right","overflow","opacity"],f=["width","height","overflow"],l=["fontSize"],c=["borderTopWidth","borderBottomWidth","paddingTop","paddingBottom"],h=["borderLeftWidth","borderRightWidth","paddingLeft","paddingRight"],p=e.effects.setMode(o,t.mode||"effect"),d=t.restore||p!=="effect",v=t.scale||"both",m=t.origin||["middle","center"],g=o.css("position"),y=d?u:a,b={height:0,width:0,outerHeight:0,outerWidth:0};p==="show"&&o.show(),r={height:o.height(),width:o.width(),outerHeight:o.outerHeight(),outerWidth:o.outerWidth()},t.mode==="toggle"&&p==="show"?(o.from=t.to||b,o.to=t.from||r):(o.from=t.from||(p==="show"?b:r),o.to=t.to||(p==="hide"?b:r)),s={from:{y:o.from.height/r.height,x:o.from.width/r.width},to:{y:o.to.height/r.height,x:o.to.width/r.width}};if(v==="box"||v==="both")s.from.y!==s.to.y&&(y=y.concat(c),o.from=e.effects.setTransition(o,c,s.from.y,o.from),o.to=e.effects.setTransition(o,c,s.to.y,o.to)),s.from.x!==s.to.x&&(y=y.concat(h),o.from=e.effects.setTransition(o,h,s.from.x,o.from),o.to=e.effects.setTransition(o,h,s.to.x,o.to));(v==="content"||v==="both")&&s.from.y!==s.to.y&&(y=y.concat(l).concat(f),o.from=e.effects.setTransition(o,l,s.from.y,o.from),o.to=e.effects.setTransition(o,l,s.to.y,o.to)),e.effects.save(o,y),o.show(),e.effects.createWrapper(o),o.css("overflow","hidden").css(o.from),m&&(i=e.effects.getBaseline(m,r),o.from.top=(r.outerHeight-o.outerHeight())*i.y,o.from.left=(r.outerWidth-o.outerWidth())*i.x,o.to.top=(r.outerHeight-o.to.outerHeight)*i.y,o.to.left=(r.outerWidth-o.to.outerWidth)*i.x),o.css(o.from);if(v==="content"||v==="both")c=c.concat(["marginTop","marginBottom"]).concat(l),h=h.concat(["marginLeft","marginRight"]),f=u.concat(c).concat(h),o.find("*[width]").each(function(){var n=e(this),r={height:n.height(),width:n.width(),outerHeight:n.outerHeight(),outerWidth:n.outerWidth()};d&&e.effects.save(n,f),n.from={height:r.height*s.from.y,width:r.width*s.from.x,outerHeight:r.outerHeight*s.from.y,outerWidth:r.outerWidth*s.from.x},n.to={height:r.height*s.to.y,width:r.width*s.to.x,outerHeight:r.height*s.to.y,outerWidth:r.width*s.to.x},s.from.y!==s.to.y&&(n.from=e.effects.setTransition(n,c,s.from.y,n.from),n.to=e.effects.setTransition(n,c,s.to.y,n.to)),s.from.x!==s.to.x&&(n.from=e.effects.setTransition(n,h,s.from.x,n.from),n.to=e.effects.setTransition(n,h,s.to.x,n.to)),n.css(n.from),n.animate(n.to,t.duration,t.easing,function(){d&&e.effects.restore(n,f)})});o.animate(o.to,{queue:!1,duration:t.duration,easing:t.easing,complete:function(){o.to.opacity===0&&o.css("opacity",o.from.opacity),p==="hide"&&o.hide(),e.effects.restore(o,y),d||(g==="static"?o.css({position:"relative",top:o.to.top,left:o.to.left}):e.each(["top","left"],function(e,t){o.css(t,function(t,n){var r=parseInt(n,10),i=e?o.to.left:o.to.top;return n==="auto"?i+"px":r+i+"px"})})),e.effects.removeWrapper(o),n()}})}}(jQuery),function(e,t){e.effects.effect.shake=function(t,n){var r=e(this),i=["position","top","bottom","left","right","height","width"],s=e.effects.setMode(r,t.mode||"effect"),o=t.direction||"left",u=t.distance||20,a=t.times||3,f=a*2+1,l=Math.round(t.duration/f),c=o==="up"||o==="down"?"top":"left",h=o==="up"||o==="left",p={},d={},v={},m,g=r.queue(),y=g.length;e.effects.save(r,i),r.show(),e.effects.createWrapper(r),p[c]=(h?"-=":"+=")+u,d[c]=(h?"+=":"-=")+u*2,v[c]=(h?"-=":"+=")+u*2,r.animate(p,l,t.easing);for(m=1;m<a;m++)r.animate(d,l,t.easing).animate(v,l,t.easing);r.animate(d,l,t.easing).animate(p,l/2,t.easing).queue(function(){s==="hide"&&r.hide(),e.effects.restore(r,i),e.effects.removeWrapper(r),n()}),y>1&&g.splice.apply(g,[1,0].concat(g.splice(y,f+1))),r.dequeue()}}(jQuery),function(e,t){e.effects.effect.slide=function(t,n){var r=e(this),i=["position","top","bottom","left","right","width","height"],s=e.effects.setMode(r,t.mode||"show"),o=s==="show",u=t.direction||"left",a=u==="up"||u==="down"?"top":"left",f=u==="up"||u==="left",l,c={};e.effects.save(r,i),r.show(),l=t.distance||r[a==="top"?"outerHeight":"outerWidth"](!0),e.effects.createWrapper(r).css({overflow:"hidden"}),o&&r.css(a,f?isNaN(l)?"-"+l:-l:l),c[a]=(o?f?"+=":"-=":f?"-=":"+=")+l,r.animate(c,{queue:!1,duration:t.duration,easing:t.easing,complete:function(){s==="hide"&&r.hide(),e.effects.restore(r,i),e.effects.removeWrapper(r),n()}})}}(jQuery),function(e,t){e.effects.effect.transfer=function(t,n){var r=e(this),i=e(t.to),s=i.css("position")==="fixed",o=e("body"),u=s?o.scrollTop():0,a=s?o.scrollLeft():0,f=i.offset(),l={top:f.top-u,left:f.left-a,height:i.innerHeight(),width:i.innerWidth()},c=r.offset(),h=e('<div class="ui-effects-transfer"></div>').appendTo(document.body).addClass(t.className).css({top:c.top-u,left:c.left-a,height:r.innerHeight(),width:r.innerWidth(),position:s?"fixed":"absolute"}).animate(l,t.duration,t.easing,function(){h.remove(),n()})}}(jQuery),define("jqueryui",["jquery"],function(){}),define("interaction_view/model/layerref",["interaction_view/model/base","interaction_view/view/layer","jqueryui"],function(){interaction_view.model.LayerRef=interaction_view.model.Base.extend({defaults:{iType:"LayerRef",iLock:!0,iVisibility:!0,iCommon:null,iDetail:null,iParent:"",iChild:"",iOptions:{createfocus:!0},iParentModel:null,iDraggable:!0,iResizable:!0,iTemplate:null,iParentdiv:".interaction-view",iAutoindex:!1,iSync:!1,iZindex:"-1",iUrl:null,iAutofocus:!1,iKeyscontrol:!0,callback:null},setcollection:function(){iOverlaylist.get(this.id)||iOverlaylist.add(this)},setview:function(e){var t=this.get("iDetail"),n=this;n.layer={},this.filterlayers(),t.layer_ids&&t.layer_ids.length>0&&_.each(t.layer_ids,function(e){n.layer[e]={},n.layer[e].iOverlaylist=new interaction_view.collection.list,n.layer[e].iAnimationlist=new interaction_view.collection.Animation,n.layer[e].iActionlist=new interaction_view.collection.Action,n.layer[e].ipreloadlist=new interaction_view.collection.Preload,n.layer[e].ipreloadlist.pageid=n.layer[e].iOverlaylist.pageid=n.layer[e].iAnimationlist.pageid=n.layer[e].iActionlist.pageid=n.id,n.layer[e].ipreloadlist.pagetype=n.layer[e].iOverlaylist.pagetype=n.layer[e].iAnimationlist.pagetype=n.layer[e].iActionlist.pagetype="LayerRef",n.layer[e].ipreloadlist.parentpageid=n.layer[e].iOverlaylist.parentpageid=n.layer[e].iAnimationlist.parentpageid=n.layer[e].iActionlist.parentpageid=n.get("pageid"),n.layer[e].ipreloadlist.layerid=n.layer[e].iOverlaylist.layerid=n.layer[e].iAnimationlist.layerid=n.layer[e].iActionlist.layerid=e}),this.setiview()},setiview:function(){this.iview=new interaction_view.view.LayerRef({model:this})},setsyncmodel:function(){},filterlayers:function(){var e=this.get("iDetail"),t=e.layer_ids;e.layer_ids&&e.layer_ids.length>0&&(t=_.filter(t,function(e){return interaction_view.ilayerlist.get(e)})),e.layer_ids=t,this.set("iDetail",e)}}),interaction_view.view.LayerRef=interaction_view.view.Base.extend({events:{},render:function(e){},preload:function(){var e=this.model.get("iDetail");e.layer_ids&&e.layer_ids.length>0&&this.sendToPreload({file:null})},loadLayer:function(e){var t=this.getdetail();this.layerCheckList=_.clone(t.layer_ids),this.firstlayer=t.layer_ids?t.layer_ids[0]:null,this.preloadmodel=e;var n=require("interaction_view/view/layer");n=_g.mvc.createView(n),this.layerview=new n({model:this.model}),this.layerview.afterload()},afterlayerload:function(e){console.log(e);if(this.preloadmodel){this.layerCheckList=_.reject(this.layerCheckList,function(t){return t==e}),this.model.layer[e].iOverlaylist.each(function(e){e.iview.preloaded||e.iview.afterpreload()}),this.model.layer[e].iActionlist.each(function(e){e.iview.render()});var t=this.model.toJSON().iDetail.iHidden||!1;this.layerCheckList.length==0&&(this.slideel=this.$el.find(".layer-content").first(),this.slideel.children(".layer-item").first().show(),this.slidestyle=this.slideel.attr("style"),this.playAnimation(),this.firstlayer&&this.model.get("iType")=="LayerRef"&&(this.model.layer[this.firstlayer].isLayer=!0),this.preloadmodel.set("loaded",!0),this.preloadmodel.page.ipreloadlist.preloadcheck(null,!0,this.model))}},playLayer:function(){this.firstlayer&&interaction_view.play(this.model.layer[this.firstlayer])},playAnimation:function(){var e=this;this.$el.find(".layer-content").children().css("opacity",1);var t=this.getLayerContentSize(),n=this.getcommon();if(t.width==n.iWidth&&t.height==n.iHeight)return!1;var r=this.getMoveRange();console.log(r);var i=0,s=0,o,u;this.$el.find(".layer-content").first().draggable({start:function(e,t){o=i=t.position.left,u=s=t.position.top},drag:function(t,n){var i=n.position,u=e.getcommon(),a=e.checkMaskPos(i,{width:u.iWidth,height:u.iHeight});a&&(n.position=a);if(n.position.left-o!=0){if(r.x>0){var f=n.position.left-o;o=n.position.left;var l=Math.abs(n.position.left)/r.x;e.onBindingChangeTo({type:0,delta:f,deltarate:l,cdirection:0})}console.log("x zhou")}n.position.top-s!=0&&console.log("y zhou")},stop:function(t,n){e.onBindingChangeTo({type:1,delta:n.position.left-o,cdirection:0})}}),this.$el.addClass("hascontrols")},checkMaskPos:function(e,t){var n=this.getdetail(),r=!0,i=this.getLayerContentSize(),s=i.width,o=i.height;return e.left>0&&(e.left=0,r=!1),e.top>0&&(e.top=0,r=!1),Math.abs(e.left)+t.width>s&&(e.left=-(s-t.width),r=!1),Math.abs(e.top)+t.height>o&&(e.top=-(o-t.height),r=!1),r?null:{left:e.left,top:e.top}},onExecuteBindingForLayerRef:function(e){var t=this,n=this.getMoveRange();if(e.type==1)return;e.cdirection||n.x>0&&this.$el.find(".layer-content").first().css("left",-e.deltarate*n.x),e.cdirection&&n.y>0&&this.$el.find(".layer-content").first().css("top",-e.deltarate*n.y)},getMoveRange:function(){var e=this.getLayerContentSize(),t=e.width,n=e.height,r=this.getcommon();return{x:t-r.iWidth,y:n-r.iHeight}},getLayerContentSize:function(){var e=this.getdetail(),t={};if(!e.layer_ids||e.layer_ids.length>0){var n=_.map(e.layer_ids,function(e){return interaction_view.ilayerlist.get(e).toJSON()});return t.width=_.max(_.pluck(n,"layer_width")),t.height=_.max(_.pluck(n,"layer_height")),t}return null},stoplayer:function(){var e=this,t=this.getdetail();t.layer_ids&&t.layer_ids.length>0&&_.each(t.layer_ids,function(t){e.model.layer[t].iAnimationlist.timeline&&e.model.layer[t].iAnimationlist.timeline.pause(0),e.model.layer[t].iOverlaylist.resetViewStatus(),interaction_view.bezierPatch&&interaction_view.bezierPatch(e.model.layer[t])})},resetlayer:function(){var e=this,t=this.getdetail();t.layer_ids&&t.layer_ids.length>0&&(_.each(t.layer_ids,function(t){e.model.layer[t].iAnimationlist.resetAnimationStatus(),e.model.layer[t].iOverlaylist.resetViewStatus()}),this.slideel.attr("style",this.slidestyle),e.currentIndex=0)},resetOtherStatus:function(){this.resetlayer()}})}),define("interaction_view/model/layerslide",["interaction_view/model/layerref"],function(){interaction_view.model.LayerSlide=interaction_view.model.LayerRef.extend({defaults:{iType:"LayerSlide",iLock:!0,iVisibility:!0,iCommon:null,iDetail:null,iParent:"",iChild:"",iOptions:{createfocus:!0},iParentModel:null,iDraggable:!0,iResizable:!0,iTemplate:null,iParentdiv:".interaction-view",iAutoindex:!1,iSync:!1,iZindex:"-1",iUrl:null,iAutofocus:!1,iKeyscontrol:!0,callback:null},setiview:function(){this.iview=new interaction_view.view.LayerSlide({model:this})}}),interaction_view.view.LayerSlide=interaction_view.view.LayerRef.extend({render:function(e){var t=this,n=this.getdetail();this.currentSlideIndex=null,this.model.on("slideTo",function(e){console.log(e);if(t.currentSlideIndex!=null&&t.currentSlideIndex==e)return!1;if(t.currentSlideIndex!=null&&t.currentSlideIndex!=e){var r=n.layer_ids[t.currentSlideIndex];interaction_view.stopPlay(t.model.layer[r])}if(t.preloaded){var i=n.layer_ids[e];if(!t.model.layer[i])return;t.model.layer[i].isLayer=!0,interaction_view.play(t.model.layer[i]),t.currentSlideIndex=e,t.model.layer[i].playFinished=!0}})},playAnimation:function(){var e=this,t=0,n=this.getdetail(),r=n.iSlidetype;this.delay=Number(n.iInterval)||2,this.autoplay=n.iAutoplay;var i=n.iRepeat?-1:0;this.iFade=n.iFade||0,this.iRewind=n.iRewind,this.timeline=new TimelineMax({paused:!0,repeat:i,onComplete:this.setRewind()}),this.slideel=e.$el.children(".Element").find(".layer-content").first(),this.slidelength=n.layer_ids.length;if(this.slidelength<2)return!1;this.repeat=i,this.slipable=n.iSlipable,this.setTimeline(),this.autoplay?this.timeline.play(0):this.setSlideDisplay(0),this.slipable?(this.control(),this.$el.addClass("hascontrols")):this.slideel&&this.slideel.on("click",function(){e.$el.children(".Element").trigger("click")})},playLayer:function(){this.autoplay&&this.timeline&&this.timeline.play(0),this.slidelength>0&&this.model.trigger("slideTo",0)},setTimeline:function(){if(this.iFade=="Fade"||0)this.setFade();else if(this.iFade=="Slip")this.setSlip();else{if(this.iFade!="None")return;this.setNone()}this.slideel.children().first().css({opacity:1,left:0,top:0}).nextAll().css("opacity",0)},getSlipeInterval:function(e){},getLayerContentSize:function(){var e=this.getdetail(),t={};if(!e.layer_ids||e.layer_ids.length>0){var n=_.map(e.layer_ids,function(e){return interaction_view.ilayerlist.get(e).toJSON()});return t.width=_.max(_.pluck(n,"layer_width")),t.height=_.max(_.pluck(n,"layer_height")),t}return null},getStartPoint:function(e){return this.delay+(this.delay+.500002)*this.delay},getEndPoint:function(e){return(this.delay+.500002)*e+1e-5},getCurrentIndex:function(e){var t=this.timeline.duration(),n=t/this.slidelength;return parseInt(e/n,10)},testControl:function(e){var t=this,n=$(e).closest(".iView");if(n.hasClass("hasaction"))return!1;if(n){var r=n.attr("data-type");if(r=="Slide"||r=="CycleImage")if(n.attr("data-iSlipable"))return!1;return!0}return!0},resetOtherStatus:function(){this.resetlayer();var e=this,t=this.getdetail();if(!t.layer_ids||t.layer_ids.length==0)return;this.slideel.children().first().css({opacity:1,left:0,top:0}),this.autoplay=t.iAutoplay,e.currentIndex=0,this.timeline&&(this.timeline.pause(1e-5),this.autoplay?this.timeline.play(0):this.setSlideDisplay(0))}})}),define("interaction_view/model/Region",["interaction_view/model/base"],function(){interaction_view.model.Region=interaction_view.model.Base.extend({defaults:{iType:"Region",iLock:!0,iVisibility:!0,iCommon:{portait:{iStartx:400,iStarty:200,iWidth:200,iHeight:200},landscape:{iStartx:400,iStarty:200,iWidth:200,iHeight:200}},iDetail:{iAdapt:!1,iFullview:!1,iImg:null,iAnimation:[]},iParent:"",iChild:"",iOptions:{createfocus:!0},iParentModel:null,iDraggable:!0,iResizable:!0,iTemplate:null,iParentdiv:".interaction-view",iAutoindex:!1,iSync:!1,iZindex:"-1",iUrl:null,iAutofocus:!1,iKeyscontrol:!0,callback:null},setcollection:function(){iOverlaylist.get(this.id)||iOverlaylist.add(this)},setview:function(e){this.iview=new interaction_view.view.Region({model:this})},setsyncmodel:function(){}}),interaction_view.view.Region=interaction_view.view.Base.extend({events:{},render:function(e){interaction_view.setscrollnano(this.$el)}})}),define("interaction_view/model/binding",["interaction_view/model/base"],function(){interaction_view.model.Binding=interaction_view.model.Base.extend({defaults:{iType:"Binding",iLock:!0,iVisibility:!0,iCommon:{portait:{iStartx:400,iStarty:200,iWidth:200,iHeight:200},landscape:{iStartx:400,iStarty:200,iWidth:200,iHeight:200}},iDetail:{iAdapt:!1,iFullview:!1,iImg:null,iAnimation:[]},iParent:"",iChild:"",iOptions:{createfocus:!0},iParentModel:null,iDraggable:!0,iResizable:!0,iTemplate:null,iParentdiv:".interaction-view",iAutoindex:!1,iSync:!1,iZindex:"-1",iUrl:null,iAutofocus:!1,iKeyscontrol:!0,callback:null,iBackground:"rgba(62,189,255,0.5)",iResourcesProperties:[{id:"iImg",type:"single"}],iAnimationProperties:[{id:"iAnimation",type:"object"}]},setcollection:function(){iOverlaylist.get(this.id)||iOverlaylist.add(this)},setview:function(e){this.iview=new interaction_view.view.Binding({model:this})},setsyncmodel:function(){}}),interaction_view.view.Binding=interaction_view.view.Base.extend({events:{},renderDynamicElement:function(){},render:function(e){},preload:function(){},afterpreload:function(){var e=this,t=this.getdetail();this.bindings=t.iBindings;if(this.bindings.length>1){var n=this.getControlBinding();_.each(this.bindings,function(t){interaction_view.events.bindingEvents.push({id:t.id,page_id:t.page_id,direction:t.direction,func:function(t){e.executeBinding(e,t)}})})}this.preloaded=!0},getControlBinding:function(){return _.find(this.bindings,function(e){return e.isControl})?_.find(this.bindings,function(e){return e.isControl}):(this.bindings[0].isControl=!0,this.bindings[0])},getOperateBindings:function(){return _.reject(this.bindings,function(e){return e.isControl})},getBindingElement:function(e,t){var n;return interaction_view.ipagelist.getPage(e)||interaction_view.imasterlist.get(e)?n=interaction_view.ipagelist.getPage(e)||interaction_view.imasterlist.get(e):n=this.model.page,n.iOverlaylist.get(t)},getDirection:function(e,t){var n=this.getControlBinding();return t.id==n.id?e.direction?1:-1:e.id==n.id?t.direction?1:-1:t.direction&&e.direction?1:-1},executeBinding:function(e,t){var e=this;_.each(this.bindings,function(n){if(n.id==t.id)return;var r=e.getDirection(n,t),i=e.getBindingElement(n.page_id,n.id);i&&(t.direction=r,t.delta=r*t.delta,t.deltarate=r==1?t.deltarate:1-t.deltarate,i.iview.onExecuteBinding(t))})},resetStatus:function(){}})}),define("interaction_view/model/main",["interaction_view/model/action","interaction_view/model/animation_view","interaction_view/model/audio","interaction_view/model/chapter","interaction_view/model/cycleimage","interaction_view/model/image","interaction_view/model/page","interaction_view/model/doc","interaction_view/model/preload","interaction_view/model/richtext","interaction_view/model/slide","interaction_view/model/video","interaction_view/model/button","interaction_view/model/map","interaction_view/model/pay","interaction_view/model/link","interaction_view/model/layerref","interaction_view/model/layerslide","interaction_view/model/Region","interaction_view/model/binding"],function(){}),function(e,t,n){var r,i,s,o,u;o={paneClass:"pane",sliderClass:"slider",contentClass:"content",iOSNativeScrolling:!1,preventPageScrolling:!1,disableResize:!1,alwaysVisible:!1,flashDelay:1500,sliderMinHeight:20,sliderMaxHeight:null},r="Microsoft Internet Explorer"===t.navigator.appName&&/msie 7./i.test(t.navigator.appVersion)&&t.ActiveXObject,i=null,u=function(){var e,t;return e=n.createElement("div"),t=e.style,t.position="absolute",t.width="100px",t.height="100px",t.overflow="scroll",t.top="-9999px",n.body.appendChild(e),t=e.offsetWidth-e.clientWidth,n.body.removeChild(e),t},s=function(){function s(r,s){this.el=r,this.options=s,i||(i=u()),this.$el=e(this.el),this.doc=e(n),this.win=e(t),this.generate(),this.createEvents(),this.addEvents(),this.reset()}return s.prototype.preventScrolling=function(e,t){this.isActive&&("DOMMouseScroll"===e.type?("down"===t&&0<e.originalEvent.detail||"up"===t&&0>e.originalEvent.detail)&&e.preventDefault():"mousewheel"===e.type&&e.originalEvent&&e.originalEvent.wheelDelta&&("down"===t&&0>e.originalEvent.wheelDelta||"up"===t&&0<e.originalEvent.wheelDelta)&&e.preventDefault())},s.prototype.updateScrollValues=function(){var e;e=this.content[0],this.maxScrollTop=e.scrollHeight-e.clientHeight,this.contentScrollTop=e.scrollTop,this.maxSliderTop=this.paneHeight-this.sliderHeight,this.sliderTop=this.contentScrollTop*this.maxSliderTop/this.maxScrollTop},s.prototype.createEvents=function(){var e=this;this.events={down:function(t){return e.isBeingDragged=!0,e.offsetY=t.pageY-e.slider.offset().top,e.pane.addClass("active"),e.doc.bind("mousemove",e.events.drag).bind("mouseup",e.events.up),!1},drag:function(t){return e.sliderY=t.pageY-e.$el.offset().top-e.offsetY,e.scroll(),e.updateScrollValues(),e.contentScrollTop>=e.maxScrollTop?e.$el.trigger("scrollend"):0===e.contentScrollTop&&e.$el.trigger("scrolltop"),!1},up:function(){return e.isBeingDragged=!1,e.pane.removeClass("active"),e.doc.unbind("mousemove",e.events.drag).unbind("mouseup",e.events.up),!1},resize:function(){e.reset()},panedown:function(t){return e.sliderY=(t.offsetY||t.originalEvent.layerY)-.5*e.sliderHeight,e.scroll(),e.events.down(t),!1},scroll:function(t){e.isBeingDragged||(e.updateScrollValues(),e.sliderY=e.sliderTop,e.slider.css({top:e.sliderTop}),null!=t&&(e.contentScrollTop>=e.maxScrollTop?(e.options.preventPageScrolling&&e.preventScrolling(t,"down"),e.$el.trigger("scrollend")):0===e.contentScrollTop&&(e.options.preventPageScrolling&&e.preventScrolling(t,"up"),e.$el.trigger("scrolltop"))))},wheel:function(t){if(null!=t)return e.sliderY+=-t.wheelDeltaY||-t.delta,e.scroll(),!1}}},s.prototype.addEvents=function(){var e;this.removeEvents(),e=this.events,this.options.disableResize||this.win.bind("resize",e.resize),this.slider.bind("mousedown",e.down),this.pane.bind("mousedown",e.panedown).bind("mousewheel DOMMouseScroll",e.wheel),this.content.bind("scroll mousewheel DOMMouseScroll touchmove",e.scroll)},s.prototype.removeEvents=function(){var e;e=this.events,this.win.unbind("resize",e.resize),this.slider.unbind(),this.pane.unbind(),this.content.unbind("scroll mousewheel DOMMouseScroll touchmove",e.scroll).unbind("keydown",e.keydown).unbind("keyup",e.keyup)},s.prototype.generate=function(){var e,t,n,r,s;return n=this.options,r=n.paneClass,s=n.sliderClass,e=n.contentClass,!this.$el.find(""+r).length&&!this.$el.find(""+s).length&&this.$el.append('<div class="'+r+'"><div class="'+s+'" /></div>'),this.content=this.$el.children("."+e),this.content.attr("tabindex",0),this.slider=this.$el.find("."+s),this.pane=this.$el.find("."+r),i&&(t={right:-i},this.$el.addClass("has-scrollbar")),n.iOSNativeScrolling&&(null==t&&(t={}),t.WebkitOverflowScrolling="touch"),null!=t&&this.content.css(t),n.alwaysVisible&&this.pane.css({opacity:1,visibility:"visible"}),this},s.prototype.restore=function(){return this.stopped=!1,this.pane.show(),this.addEvents()},s.prototype.reset=function(){var e,t,n,s,o,u,a;return this.$el.find("."+this.options.paneClass).length||this.generate().stop(),this.stopped&&this.restore(),e=this.content[0],n=e.style,s=n.overflowY,r&&this.content.css({height:this.content.height()}),t=e.scrollHeight+i,u=this.pane.outerHeight(),a=parseInt(this.pane.css("top"),10),o=parseInt(this.pane.css("bottom"),10),o=u+a+o,a=Math.round(o/t*o),a<this.options.sliderMinHeight?a=this.options.sliderMinHeight:null!=this.options.sliderMaxHeight&&a>this.options.sliderMaxHeight&&(a=this.options.sliderMaxHeight),"scroll"===s&&"scroll"!==n.overflowX&&(a+=i),this.maxSliderTop=o-a,this.contentHeight=t,this.paneHeight=u,this.paneOuterHeight=o,this.sliderHeight=a,this.slider.height(a),this.events.scroll(),this.pane.show(),this.isActive=!0,this.pane.outerHeight(!0)>=e.scrollHeight&&"scroll"!==s?(this.pane.hide(),this.isActive=!1):this.el.clientHeight===e.scrollHeight&&"scroll"===s?this.slider.hide():this.slider.show(),this},s.prototype.scroll=function(){return this.sliderY=Math.max(0,this.sliderY),this.sliderY=Math.min(this.maxSliderTop,this.sliderY),this.content.scrollTop(-1*((this.paneHeight-this.contentHeight+i)*this.sliderY/this.maxSliderTop)),this.slider.css({top:this.sliderY}),this},s.prototype.scrollBottom=function(e){return this.reset(),this.content.scrollTop(this.contentHeight-this.content.height()-e).trigger("mousewheel"),this},s.prototype.scrollTop=function(e){return this.reset(),this.content.scrollTop(+e).trigger("mousewheel"),this},s.prototype.scrollTo=function(t){return this.reset(),t=e(t).offset().top,t>this.maxSliderTop&&(t/=this.contentHeight,this.sliderY=t*=this.maxSliderTop,this.scroll()),this},s.prototype.stop=function(){return this.stopped=!0,this.removeEvents(),this.pane.hide(),this},s.prototype.flash=function(){var e=this;return this.pane.addClass("flashed"),setTimeout(function(){e.pane.removeClass("flashed")},this.options.flashDelay),this},s}(),e.fn.nanoScroller=function(t){return this.each(function(){var n;(n=this.nanoscroller)||(n=e.extend({},o),t&&"object"==typeof t&&(n=e.extend(n,t)),this.nanoscroller=n=new s(this,n));if(t&&"object"==typeof t){e.extend(n.options,t);if(t.scrollBottom)return n.scrollBottom(t.scrollBottom);if(t.scrollTop)return n.scrollTop(t.scrollTop);if(t.scrollTo)return n.scrollTo(t.scrollTo);if("bottom"===t.scroll)return n.scrollBottom(0);if("top"===t.scroll)return n.scrollTop(0);if(t.scroll&&t.scroll instanceof e)return n.scrollTo(t.scroll);if(t.stop)return n.stop();if(t.flash)return n.flash()}return n.reset()})}}(jQuery,window,document),define("jquery.nanoscroller",["jquery"],function(){}),define("interaction_view/ui/main",["jquery","backbone","jquery.nanoscroller","text!interaction_view/template/message.js"],function(){var e=require("text!interaction_view/template/message.js");return{message:function(t,n,r){$("body").find(".msg").length==0&&$("body").append('<div class="msg"></div>'),r||(r=3e3),$(".msg").html(_.template(e,{type:t,msg:n})),$(".msg").fadeIn(),setTimeout(function(){$(".msg").fadeOut("slow"),$(".msg").remove()},r)},getRequest:function(e){var t=location.search,n={};if(t.indexOf("?")!=-1){var r=t.substr(1);strs=r.split("&");for(var i=0;i<strs.length;i++)n[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1])}return e?n[e]:n},setscrollnano:function(e){$(e).hasClass("nanoscrollbar")?$selector=$(e):$selector=$(e).find(".nanoscrollbar"),$selector.children(".nano").length==0&&$selector.wrapInner('<div class="nano"><div class="content"></div></div>'),$selector.children(".nano").nanoScroller(),$selector.children(".nano").children(".pane").css({visibility:"hidden"}),$selector.children(".nano").hover(function(){$(this).children(".pane").css({visibility:"visible"})},function(){$(this).children(".pane").css({visibility:"hidden"})})},deviceType:function(){return navigator.userAgent.match(/iPad/i)=="iPad"?"iPad":navigator.userAgent.match(/iPhone/i)=="iPhone"?"iPhone":navigator.userAgent.match(/Android/i)=="Android"?"Android":navigator.userAgent.match(/BlackBerry/i)=="BlackBerry"?"BlackBerry":"null"},getModelById:function(e,t){var n=null;return e.icollection.each(function(e){e.id==t&&(n=e);var r=interaction_view.getModelById(e,t);r&&(n=r)}),n},model2collection:function(e,t){e.has(t)&&e.icollection.add(e.get(t))},model2tree:function(e,t,n){e.has(t)&&(e.icollection.add(e.get(t)),e.icollection.each(function(e){e.has(n)&&interaction_view.model2tree(e,n,n)}))},getPageIds:function(){var e=[];return $(".reveal").find("section").each(function(){e.push($(this).attr("id"))}),e}}}),!function(e){var t=function(t,n){this.$element=e(t),this.options=n,this.init()};t.prototype={init:function(){_.bindAll(this)},_animate_loading:function(){if(!this.loading.is(":visible")){clearInterval(this.loadingTimer);return}e("div",this.loading).css("top",this.loadingFrame*-40+"px"),this.loadingFrame=(this.loadingFrame+1)%12},load:function(){this.loadingTimer=this.loadingFrame=1,this.$element.append(this.loading=e('<div id="jswait-loading" style="display:none;"><div></div></div>'),this.overlay=e('<div id="jswait-overlay" class="mask hide"></div>')),this.options.modal&&overlay.addClass("ui-widget-overlay"),clearInterval(this.loadingTimer),this.loading.show(),this.loadingTimer=setInterval(this._animate_loading,66),this.waited=!0},close:function(){this.waited&&(this.loading.remove(),this.overlay.remove(),this.loadingFrame=1,clearInterval(this.loadingTimer),this.waited=!1)}},e.fn.jswait=function(n){return this.each(function(){var r=e(this),i=r.data("jswait"),s=e.extend({},e.fn.jswait.defaults,typeof n=="object"&&n),o=typeof n=="string"?n:null;i||r.data("jswait",i=new t(this,s)),o?i[o]():i.load()})},e.fn.jswait.defaults={modal:!1},e.fn.jswait.Constructor=t}(window.jQuery),define("jswait",["jquery"],function(){}),function(e,t){var n="undefined"!=typeof Element&&"ALLOW_KEYBOARD_INPUT"in Element,r=function(){for(var e,n,r=[["requestFullscreen","exitFullscreen","fullscreenElement","fullscreenEnabled","fullscreenchange","fullscreenerror"],["webkitRequestFullscreen","webkitExitFullscreen","webkitFullscreenElement","webkitFullscreenEnabled","webkitfullscreenchange","webkitfullscreenerror"],["webkitRequestFullScreen","webkitCancelFullScreen","webkitCurrentFullScreenElement","webkitCancelFullScreen","webkitfullscreenchange","webkitfullscreenerror"],["mozRequestFullScreen","mozCancelFullScreen","mozFullScreenElement","mozFullScreenEnabled","mozfullscreenchange","mozfullscreenerror"]],i=0,s=r.length,o={};s>i;i++)if(e=r[i],e&&e[1]in t){for(i=0,n=e.length;n>i;i++)o[r[0][i]]=e[i];return o}return!1}(),i={request:function(e){var i=r.requestFullscreen;e=e||t.documentElement,/5\.1[\.\d]* Safari/.test(navigator.userAgent)?e[i]():e[i](n&&Element.ALLOW_KEYBOARD_INPUT)},exit:function(){t[r.exitFullscreen]()},toggle:function(e){this.isFullscreen?this.exit():this.request(e)},onchange:function(){},onerror:function(){},raw:r};return r?(Object.defineProperties(i,{isFullscreen:{get:function(){return!!t[r.fullscreenElement]}},element:{enumerable:!0,get:function(){return t[r.fullscreenElement]}},enabled:{enumerable:!0,get:function(){return!!t[r.fullscreenEnabled]}}}),t.addEventListener(r.fullscreenchange,function(e){i.onchange.call(i,e)}),t.addEventListener(r.fullscreenerror,function(e){i.onerror.call(i,e)}),e.screenfull=i,void 0):e.screenfull=!1}(window,document),define("screenfull",function(){}),define("interaction_view/ui/presentation",["interaction_view/main","jswait","screenfull","_g/ui"],function(){var e={init:function(){},play:function(t){var n=null;typeof t=="string"?n=interaction_view.ipagelist.getPage(t)||interaction_view.imasterlist.get(t):n=t,n.iOverlaylist.resetViewStatus(),n.playFinished==1&&(n.iAnimationlist.resetAnimationStatus(),n.playFinished=!1),n.iOverlaylist.each(function(e){e.media&&e.autoplay&&(e.get("iType")!="Audio"?(e.iview.$el.removeClass("hide"),e.hided=!1,setTimeout(function(){e.media.play()},100)):e.media.play())}),n.played=!1,n.iAnimationlist.setParams(),n.iAnimationlist.setPlay(),interaction_view.events.clearWaitClick(),interaction_view.mode=="Page"&&!interaction_view.masterplayed&&!n.isLayer&&(interaction_view.masterplayed=!0,interaction_view.play(interaction_view.imasterlist.at(0))),n.isLayer?interaction_view.events.onPageStart(n.iOverlaylist.pageid,n.iOverlaylist.layerid):interaction_view.events.onPageStart(n.id),interaction_view.mode=="Page"&&!n.isLayer&&interaction_view.ipagelist.getPage(n.id)&&e.setMasterDisplay(n),n.iAnimationlist.timeline&&n.iAnimationlist.timeline.play(0,!1),n.iOverlaylist.each(function(e){(e.get("iType")=="LayerRef"||e.get("iType")=="LayerSlide")&&e.iview.playLayer()}),n.playFinished=!0},stop:function(e){var t;typeof e=="string"?t=interaction_view.ipagelist.getPage(e):t=e,t.playFinished&&(t.iAnimationlist.timeline&&(t.iAnimationlist.timeline.pause(0),t.iOverlaylist.resetViewStatus(),typeof e=="string"&&$(".interaction-view").css("cursor","auto"),interaction_view.bezierPatch(e)),t.iOverlaylist.each(function(e){e.media&&(e.media.setCurrentTime(0),e.media.pause()),(e.get("iType")=="LayerRef"||e.get("iType")=="LayerSlide")&&e.iview.stoplayer()}))},setMasterDisplay:function(e){interaction_view.show_master=e.get("show_master")?!0:!1,interaction_view.show_master||interaction_view.mode=="Master"?$('.Presentation[id="'+e.id+'"]').find(".interaction-view").children(".iView.master").removeClass("masterhide"):$('.Presentation[id="'+e.id+'"]').find(".interaction-view").children(".iView.master").addClass("masterhide")},bezierPatch:function(e){var t;typeof e=="string"?t=interaction_view.ipagelist.getPage(e):t=e,t.iAnimationlist.each(function(e){_.include([301,302],e.get("iType"))&&e.toJSON().iDetail.autoRotate&&TweenMax.to(e._animation.obj,0,{rotation:"0_cw"})})},foredit:function(){},forpreview:function(){interaction_view.mode="Page",$("body").append('<div id="preloader"></div>'),$("body").prepend('<div class="loading progress progress-striped active"><div class="bar" style="width: 0%;"></div></div>'),$("body").jswait(),interaction_view.finishPagePreload=function(e){interaction_view.pagepreloadcheck||(interaction_view.masterplayed=!1,interaction_view.pagepreloadcheck=_.pluck(interaction_view.ipagelist.getPages(),"id"),interaction_view.pagepreloadcheck.push(interaction_view.imasterlist.at(0).id)),interaction_view.pagepreloadcheck=_.reject(interaction_view.pagepreloadcheck,function(t){return t==e});var t=interaction_view.ipagelist.getPage(e)||interaction_view.imasterlist.get(e);t.set("loaded",!0,{silent:!0}),interaction_view.donext(t),(_.filter(interaction_view.ipagelist.getPagesJSON(),function(e){return e.loaded==1}).length>3||interaction_view.pagepreloadcheck.length==0)&&interaction_view.imasterlist.at(0).get("loaded")&&(interaction_view.preloadended||(interaction_view.preloadended=!0));if(interaction_view.playstatus=="wait"&&interaction_view.preloadended){var n=interaction_view.ipagelist.getPage(interaction_view.currentPage);n.get("loaded")&&(console.log("start play:"+n.id),interaction_view.playstatus="play",$("body").jswait("close"),interaction_view.play(interaction_view.currentPage))}interaction_view.pagepreloadcheck.length==0&&$(".loading").remove()},interaction_view.setPreloadStatus=function(){var e=0,t=0;_.each(interaction_view.ipagelist.getPages(),function(n){t+=n.ipreloadlist.length,n.ipreloadlist.length>0&&(e+=n.ipreloadlist.where({loaded:!0}).length)}),t+=interaction_view.imasterlist.at(0).ipreloadlist.length,interaction_view.imasterlist.at(0).ipreloadlist.length>0&&(e+=interaction_view.imasterlist.at(0).ipreloadlist.where({loaded:!0}).length),$(".loading").children("div").css("width",String(e/t*100)+"%")},interaction_view.donext=function(e){e.iview.afterpreload()},interaction_view.play=e.play,interaction_view.stopPlay=e.stop,interaction_view.moveMaster=function(e,t){var n=$('.Presentation[id="'+e+'"]').find(".interaction-view").children(".iView.master").detach();$('.Presentation[id="'+t+'"]').find(".interaction-view").append(n)},interaction_view.bezierPatch=e.bezierPatch,interaction_view.slideChange=function(e){if(!Reveal)return;typeof e=="number"&&Reveal.slide(e);if(typeof e=="string"){var t=interaction_view.getModelById(interaction_view.iChapter,e);Reveal.slide(t.get("index"))}},interaction_view.firstPlay=!0},screencontrol:function(){var e=!1;window.screenLock=!1,$("a.fullscreenbtn").on("click",function(){screenfull.enabled&&!e?screenfull.request(document.documentElement):screenfull.exit()}),window.screenAutoAdapt=function(){if(window.screenLock)return;if(screenfull.isFullscreen){e=!0;var t=window.screen.width/window.screen.height>=interaction_view.size.x/interaction_view.size.y?window.screen.height/interaction_view.size.y:window.screen.width/interaction_view.size.x;console.log($("body > .reveal").height()),console.log($("body > .reveal").width()),console.log(window.screen.width),_g.ui.scale("body > .reveal",t)}else e=!1,_g.ui.scale("body > .reveal",1)},screenfull.onchange=screenAutoAdapt}};window.presentation=e}),define("interaction_view/ui/control",[],function(){var e={slideUp:function(){Reveal.up()},slideDown:function(){Reveal.down()},slideLeft:function(){var t=Reveal.getCurrentSlide().id,n=e.getLeft(t);n&&e.slideTo(n.id)},slideRight:function(){var t=Reveal.getCurrentSlide().id,n=e.getRight(t);n&&e.slideTo(n.id)},getRight:function(e){var t=interaction_view.ipagelist.getPage(e),n=t.get("group"),r=t.collection.parent,i=interaction_view.ipagelist.at(interaction_view.ipagelist.indexOf(r)+1);if(i){var s=i.icollection.at(0),o=s.get("group");return n!=o?!1:s}return!1},getLeft:function(e){var t=interaction_view.ipagelist.getPage(e),n=t.get("group"),r=t.collection.parent,i=interaction_view.ipagelist.at(interaction_view.ipagelist.indexOf(r)-1);if(i){var s=i.icollection.at(0),o=s.get("group");return n!=o?!1:s}return!1},getCurrent:function(){},slideTo:function(e){var t=interaction_view.ipagelist.getPage(e);indexh=t.collection.parent.collection.indexOf(t.collection.parent),indexv=t.collection.indexOf(t),Reveal.slide(indexh,indexv)}};return e}),define("interaction_view/ui/event",["_g/ui"],function(){var e={pageStartEvents:[],pageClickEvents:[],pageDblClickEvents:[],elementChangeToEvents:[],slideClickEvents:[],slideDblClickEvents:[],bindingEvents:[],init:function(){interaction_view.foredit?target=$(".interaction-view"):target=$(".slides"),target.on("click",function(t){e.testControl(t)&&e.onClickEvent()}),target.on("dblclick",function(t){e.onDblClickEvent(),t.preventDefault(),_g.ui.clearSelection()}),_g.getUrlParameterByName("-build")=="1"&&e.initWheelEvent()},wheelEvents:[],initWheelEvent:function(){var e=!1,t=null,n=!1,r=!1,i=function(t){console.log(t.wheelDeltaX);var i=$(t.target).closest(".iView");if(i.length>0){var s=i.attr("data-type");_.include(["LayerRef","LayerSlide","Slide","CycleImage"],s)?r=!0:r=!1}else r=!1;if(!e){console.log("wheelstart"),e=!0,n=!0,r&&i.children(".Element").trigger("wheelstart",t);var o=window.setInterval(function(){n?(console.log("wheelend"),n=!1,e=!1,window.clearInterval(o),i.children(".Element").trigger("wheelend",t)):n=!0},100)}else n=!1,console.log("wheelmove"),i.children(".Element").trigger("wheelmove",t)};window.addEventListener&&window.addEventListener("DOMMouseScroll",i,!1),window.onmousewheel=document.onmousewheel=i},testControl:function(e){var t=$(e.target).closest(".iView");if($(e.target).closest(".iView").hasClass("hasaction"))return!1;if(t){var n=t.attr("data-type");if(n=="Slide"||n=="CycleImage")if(t.attr("data-iSlipable"))return!1}return $(e.target).closest(".iLayerRef").length>0&&$(e.target).closest(".iLayerRef").parent(".iView").hasClass("hascontrols")?!1:!0},onPageStart:function(e,t){var n=_.filter(interaction_view.events.pageStartEvents,function(n){return n.page_id==e&&(t?n.layer_id==t:!0)});n.length>0&&_.each(n,function(e){e.func()})},onChangeTo:function(e,t,n){var r=_.filter(interaction_view.events.elementChangeToEvents,function(r){return r.page_id==e&&r.overlay_id==t&&r.index==n});r.length>0&&_.each(r,function(e){e.func()})},onClickEvent:function(){if(interaction_view.events.pageClickEvents.length>0){var t=_.filter(interaction_view.events.pageClickEvents,function(e){return e.type=="waitaction"});if(t.length>0)_.each(t,function(e){e.func()});else{var n=_.filter(interaction_view.events.pageClickEvents,function(e){return e.page_id==interaction_view.currentPage&&e.type=="page"});if(n.length>0)_.each(n,function(e){e.func()});else{var r=_.filter(interaction_view.events.pageClickEvents,function(e){return e.type=="master"});interaction_view.show_master&&_.each(r,function(e){e.func()})}}e.clearWaitClick()}},onDblClickEvent:function(){if(interaction_view.events.pageDblClickEvents.length>0){var e=_.filter(interaction_view.events.pageDblClickEvents,function(e){return e.page_id==interaction_view.currentPage&&e.type=="page"});if(e.length>0)_.each(e,function(e){e.func()});else{var t=_.filter(interaction_view.events.pageDblClickEvents,function(e){return e.type=="master"});interaction_view.show_master&&_.each(t,function(e){e.func()})}}},onSlideClickEvent:function(e,t,n,r,i){},onSlideDblClickEvent:function(e,t,n,r,i){},onBingChangeTo:function(e){var t=_.filter(interaction_view.events.bindingEvents,function(t){return t.id==e.id&&t.page_id==e.page_id});_.each(t,function(t){e.direction=t.direction,t.func(e)})},clearWaitClick:function(){interaction_view.events.pageClickEvents=_.reject(interaction_view.events.pageClickEvents,function(e){return e.type=="waitaction"})},clearAll:function(){interaction_view.events.pageClickEvents=[],interaction_view.events.pageDblClickEvents=[],interaction_view.events.pageStartEvents=[],interaction_view.events.bindingEvents=[],interaction_view.events.elementChangeToEvents=[]}};return e}),define("interaction_view/main",["interaction_view/model/main","interaction_view/ui/main","interaction_view/ui/presentation","interaction_view/ui/control","interaction_view/ui/event"],function(){var e=require("interaction_view/ui/main");interaction_view=$.extend({},interaction_view,e),interaction_view.control=require("interaction_view/ui/control"),interaction_view.events=require("interaction_view/ui/event"),interaction_view.start=function(){var e=interaction_view.doc.get("play_mode");interaction_view.play_mode=e,interaction_view.events.init(),interaction_view.presentate=new $.presentate(!0),Reveal.initialize({history:!0,center:!0,width:interaction_view.size.x,height:interaction_view.size.y,minScale:1,maxScale:1,transition:"none",keyboard:e==0?!0:{37:function(){interaction_view.control.slideLeft()},38:function(){interaction_view.control.slideUp()},39:function(){interaction_view.control.slideRight()},40:function(){interaction_view.control.slideDown()}},controls:e==0?!0:!1,progress:!0,theme:Reveal.getQueryHash().theme}),Reveal.addEventListener("overviewshown",function(e){$("aside.controls").addClass("slideoverview")}),Reveal.addEventListener("overviewhidden",function(e){$("aside.controls").removeClass("slideoverview")}),Reveal.addEventListener("ready",function(e){interaction_view.doc.toJSON().play_mode==0&&$("aside.controls").addClass("hide"),interaction_view.doc.toJSON().play_mode==1&&($("div.reveal .progress").addClass("hide"),$(".slide-control").hide(),$("aside.controls").addClass("hide")),interaction_view.playstatus="wait",section=e.currentSlide,interaction_view.currentPage=$(section).attr("id"),console.log("init page:"+interaction_view.currentPage);var t=require("interaction_view/view/master");interaction_view.imasterlist.at(0).addView("iview",t),_.each(interaction_view.ipagelist.getPages(),function(e){e.iview.afterload()}),interaction_view.imasterlist.at(0).iview.afterload()}),Reveal.addEventListener("slidechanged",function(e){section=e.currentSlide,current_id=$(section).attr("id"),interaction_view.currentPage=current_id,pre_id=$(e.previousSlide).attr("id"),interaction_view.moveMaster(pre_id,current_id),interaction_view.stopPlay(pre_id);var t=interaction_view.ipagelist.getPage(interaction_view.currentPage);t.get("loaded")&&interaction_view.imasterlist.at(0).get("loaded")?(interaction_view.playstatus="play",$("body").jswait("close"),$("body").find("#jswait-loading").remove(),interaction_view.play(current_id)):(interaction_view.playstatus="wait",!$("body").has("#jswait-loading").length>0&&$("body").jswait())})},interaction_view.init=function(){presentation.forpreview(),presentation.screencontrol(),window.iPageDirection="landscape",$("div.slides").children("section").remove();var e=require("interaction_view/model/doc");interaction_view.doc=new e({id:"doc"});if(typeof cbt_data!="undefined"){var t=interaction_view.doc.parse(cbt_data);interaction_view.doc.set(t),interaction_view.start()}else interaction_view.doc.fetch({success:function(e,t){interaction_view.start()}})}}),require(["revealJS","interaction_play/presentate","interaction_view/main","_g/base"],function(){_g.browserSupport({msie:9,chrome:1,safari:1,mozilla:1})?(interaction_view.init(),$(".return a").live("click",function(){var e=location.search,t={};if(e.indexOf("?")!=-1){var n=e.substr(1);strs=n.split("&");for(var r=0;r<strs.length;r++)t[strs[r].split("=")[0]]=unescape(strs[r].split("=")[1])}return t["from"]=="page"&&$(window.parent.document.getElementById("PreviewWindow")).remove(),!1})):window.location.href="/staticfs/admin-epub360/browser-old.html"}),define("diazo/js/app/main/interaction/cbtview0902",function(){});
5b22d5cff0b3fd262a81b1d81eb823523e212557
646dea688d45b8478fa63674f0d9e4b29884d4a2
/Data/EXO/EDGER/edgeR analysis of data.r
a30f4ddf11cf65786107e41e1b8816cc200c15f6
[]
no_license
HarleyRobinson/Honours2
ec95c23a78cc280fc32d5462bbb25a8d0a0340d3
0a75eeb0a872d2b83c08d2cd1e5ac0c87c61400f
refs/heads/master
2021-03-27T13:10:31.244358
2016-11-14T06:37:14
2016-11-14T06:37:14
50,013,122
0
0
null
null
null
null
UTF-8
R
false
false
1,648
r
edgeR analysis of data.r
# Data input # load the edgeR library library(edgeR) library(lumi) # read in the raw data rawdata <- read.delim("miRNA_raw_counts_CORRECT_NAMES.txt") # create a DGEList object. In this case, raw data is in columns 2 to 55, and unique identifiers are in 1 (miRNA name) y <- DGEList(counts=Cav1PN4[,1:6], genes=rownames(rawdata)) # Filtering and Normalization # compute the effective library size by using TMM normalization keep <- rowSums(cpm(y)>10) >=2 y <- y[keep,] y$samples$lib.size <- colSums(y$counts) y <- calcNormFactors(y) #make QC plots d <-cpm(y, normalized.lib.sizes=TRUE) d<-t(d) dist<-dist(d) hc<-hclust(dist) plot(hc) # Export the graph to a PDF pdf(file="dendrogramPC3Cav1Sub.pdf", paper="a4r") plot(hc) dev.off() # An MDS plot shows the biological coefficient of variation between the samples. The two # dimensions are the biggest and second biggest sources of variation within the data. Again, this plot # seems to suggest that the biggest differentiators of these samples are not related to the properties of # the genes tested. d <-t(d) plotMDS(d, col=c(rep(1,15), rep(2, 15), rep(1, 12), rep(2, 12))) legend("topright", legend = c("Exosome", "Pellet"), col = 1:2, pch = 15) plotMDS(d, col=c(rep(1,30), rep(2,24))) legend("topright", legend = c("HEK", "PC3"), col = 1:2, pch = 15) # Export the graph to a PDF pdf(file="MDSCavin1withSubPC3exo.pdf", paper="a4r") plotMDS(d, col=c(rep(1,15), rep(2, 15), rep(1, 12), rep(2, 12))) legend("topright", legend = c("Exosome", "Pellet"), col = 1:2, pch = 15) plotMDS(d, col=c(rep(1,30), rep(2,24))) legend("topright", legend = c("HEK", "PC3"), col = 1:2, pch = 15) dev.off()
1c6cf7d9a3b408e39b679b89fb5648dcc45190da
76ecf1a0cd569defadd07a07b60df6f5d5ab9d8e
/inst/doc/ReDaMoR.R
27339b84497acbff2a3660ca843ec4169aa9d755
[]
no_license
cran/ReDaMoR
3f12268a6dd9b8f8daf7d0f448e7b809b6748553
abc8c94f1d1cece130907c1bb0517ba3466baf13
refs/heads/master
2023-07-23T18:12:18.564979
2023-07-05T23:14:14
2023-07-05T23:14:14
251,642,241
0
0
null
null
null
null
UTF-8
R
false
false
3,010
r
ReDaMoR.R
## ----setup, include = FALSE--------------------------------------------------- library(knitr) library(ReDaMoR) knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) cranRef <- function(x){ sprintf( "[%s](https://CRAN.R-project.org/package=%s): %s", x, x, packageDescription(x)$Title ) } ## ---- eval=FALSE-------------------------------------------------------------- # install.packages("ReDaMoR") ## ---- eval=FALSE-------------------------------------------------------------- # devtools::install_github("patzaw/ReDaMoR") ## ---- eval=FALSE-------------------------------------------------------------- # library(ReDaMoR) # m <- model_relational_data() ## ---- eval=FALSE-------------------------------------------------------------- # m <- model_relational_data(recover_RelDataModel()) ## ----------------------------------------------------------------------------- hpo_model <- read_json_data_model( system.file("examples/HPO-model.json", package="ReDaMoR") ) plot(hpo_model) ## ----------------------------------------------------------------------------- ## Edit the model # m <- model_relational_data(hpo_model) ## ---- eval=FALSE-------------------------------------------------------------- # library(ReDaMoR) # model_relational_data() ## ----------------------------------------------------------------------------- confrontation_report <- confront_data( hpo_model, path=list.files( system.file("examples/HPO-subset", package="ReDaMoR"), full.names=TRUE ), returnData=TRUE ) ## ---- results='asis'---------------------------------------------------------- # view_confrontation_report(confrontation_report) # Use RStudio viewer format_confrontation_report_md( confrontation_report, title="Example: Confrontation with original data", level=1, numbered=FALSE ) %>% cat() ## ----------------------------------------------------------------------------- hpo_tables <- confrontation_report$data ## ---- results='asis'---------------------------------------------------------- hpo_tables$HPO_diseases <- hpo_tables$HPO_diseases %>% slice(1:100) hpo_tables$HPO_synonyms[1:10, "synonym"] <- NA hpo_tables$HPO_hp <- hpo_tables$HPO_hp %>% mutate(level=as.character(level)) confront_data(hpo_model, hpo_tables, verbose=FALSE) %>% format_confrontation_report_md( title="Example: Confrontation with altered data", level=1, numbered=FALSE ) %>% cat() ## ----------------------------------------------------------------------------- hpo_tables <- confrontation_report$data new_model <- df_to_model( list=names(hpo_tables), envir=as.environment(hpo_tables) ) new_model %>% auto_layout(lengthMultiplier=250) %>% plot() ## ----------------------------------------------------------------------------- # model_relational_data(new_model) ## ----------------------------------------------------------------------------- ge_model <- read_json_data_model( system.file("examples/GE-model.json", package="ReDaMoR") ) plot(ge_model)
d2826198d1f1b7251f78dec83265cacf4942acf7
44a919553acf39c6979767bb42f6b70fe5ecba83
/Perez_et_al_2022/3_optimization-criteria-LST.R
461a976a0a922b7391453760d29f48ee8bfac8dc
[ "MIT" ]
permissive
farkkilab/pubs
cb92d67132925cbebbf9b79744ed9a0c5020ccd7
0e76ee49aaba6583334ba3657366507673e638e9
refs/heads/master
2022-11-17T22:10:09.355688
2022-11-15T14:44:40
2022-11-15T14:44:40
234,320,206
6
3
null
null
null
null
UTF-8
R
false
false
16,901
r
3_optimization-criteria-LST.R
library(ggplot2) library(rpart) library(rpart.utils) library(rpart.plot) library(ggpubr) #Importing other function inside the repository extra.functions <- list.files("R/", full.names = TRUE) sapply(extra.functions, source) load("sysdata.rda") ####### Defining variables ########### outputfolder = "/home/fernpere/HRD/TCGA_analysis/find_HRD_signaturesHGSC_germlines//" #Mainly for plots ###### Reading input ####### #This are GRCh38 segments for OVA-TCGA (PanCanAtlas) segHRDTCGA <- read.table(file = "/home/fernpere/HRD/TCGA_analysis/find_HRD_signatures/HRD_samples-TCGAsegmentsHGSC_2021.txt", header=T) segHRPTCGA <- read.table(file = "/home/fernpere/HRD/TCGA_analysis/find_HRD_signatures/HRP_samples-TCGAsegmentsHGSC_2021.txt", header=T) #Plody information Ploidy_file <- read.table(file="/home/fernpere/HRD/TCGA_analysis/find_HRD_signatures/samplesHR_ploidy-purity2.txt", header = T, sep="\t") ##Preprocesing the segments from TCGA portal chrominfo = chrominfo_grch38 ploidy <- rep(2, nrow(segHRDTCGA)) segHRDTCGA <- cbind (segHRDTCGA, ploidy) ploidy <- rep(2, nrow(segHRPTCGA)) segHRPTCGA <- cbind (segHRPTCGA, ploidy) preprocessed_HRD_TCGA <- preparing.input(segHRDTCGA) preprocessed_HRP_TCGA <- preparing.input(segHRPTCGA) ### Sample TCGA-13-1511 (HRP), is an HRP outlier, we excluded### preprocessed_HRP_TCGA <- preprocessed_HRP_TCGA[!preprocessed_HRP_TCGA[,1] %in% c("TCGA-13-1511"),] ######################################################################################################################### ######################################################################################################################### #Plotting distribution of segments as in Popova et al. 2012 Figure 2A #Proportion of segments equal or greater than a given segment size ##### Density calculation of events of HRD #### Sizes <- c(seq(0.25,80, by=0.25)) all_samplesTCGAportal <- rbind(preprocessed_HRD_TCGA, preprocessed_HRP_TCGA) #Proportion of segments of a given size Proportions_segments_HRD <- segmentBySamples(preprocessed_HRD_TCGA, Sizes) Proportions_segments_HRP <- segmentBySamples(preprocessed_HRP_TCGA, Sizes) average_proportions_HRD <- log2(apply(Proportions_segments_HRD, FUN = mean, MARGIN = 1)) average_proportions_HRP <- log2(apply(Proportions_segments_HRP, FUN = mean, MARGIN = 1)) #Fitting a smoothing spline for the proportion of segments of given size yHRD <- average_proportions_HRD[1:160] xHRD <- as.numeric(names(average_proportions_HRD)[1:160]) loHRD <- smooth.spline(xHRD, yHRD, spar=0.5) yHRP <- average_proportions_HRP[1:160] xHRP <- as.numeric(names(average_proportions_HRP)[1:160]) loHRP <- smooth.spline(xHRP, yHRP, spar=0.5) #Plotting differences in distribution of segments for Sup.Figure2b svg(file=paste0(outputfolder, "HRP-HRD_segmentsProportions_average_HGSC.svg"), height = 6, width = 6, pointsize = 6) plot(Sizes,average_proportions_HRD,xlim = c(0,28), ylim=c(-10.6,-4), pch=16, xaxt="n", main="", xlab="Segment size, Mb", ylab="Log2(Average proportions)", type="p", cex=0.8, col="darkred", cex.axis = 1.8, cex.lab=2.8) points(Sizes,average_proportions_HRP, col="blue", pch=16, cex=0.8) lines(loHRP, col="blue") lines(loHRD, col="darkred") axis(side=1,at=seq(0,90,by=1), cex.axis=1.5) grid(nx = NULL, ny = NULL, col = "lightgray", lty = "dotted") abline(v=2, lty=2) dev.off() ######################################################################################################################################################### ################################################### Calculating best LSTs ############################################################################### ######################################################################################################################################################### ####### First generate vector with with size ######### chrominfo = chrominfo_grch38 LSTs_per_sampleTCGA_HRP <- LSTs(preprocessed_HRP_TCGA, chrominfo = chrominfo_grch38) LSTs_per_sampleTCGA_HRD <- LSTs(preprocessed_HRD_TCGA, chrominfo = chrominfo_grch38) ####### Iteration of parameters that define an LST, get the number of LSTs under those parameters######### mindistance_values <- c(1, 2, 3, 4) #In Mb, minimum AIs length for smoothing segsizes_values <- c(1:20) #Mb minimum size of consecutive AIs after smoothing tandemelements_Values = c(2,3) #Number of consecutive AIs after smoothing chrominfo = chrominfo_grch38 #In the next pair of dataframes will be stored the amount of LSTs under the parameters s,m,t #Just initialize them whit random numbers in the first two columns, letter will be removed the first first two columns LSTs_all_parameters_HRP <- data.frame(x=rep(1,length(LSTs_per_sampleTCGA_HRP)), y=rep(1,length(LSTs_per_sampleTCGA_HRP))) LSTs_all_parameters_HRD <- data.frame(x=rep(1,length(LSTs_per_sampleTCGA_HRD)), y=rep(1,length(LSTs_per_sampleTCGA_HRD))) for (m in mindistance_values){ m <- m * 1e6 #To Mb for (s in segsizes_values){ s <- s * 1e6 #To Mb print(paste("distance=",m,"segzises=",s)) for (t in tandemelements_Values){ LSTs_per_sampleTCGA_HRP <- LSTs(preprocessed_HRP_TCGA, mindistance = m, segsizes = s, tandemelements = t) LSTs_all_parameters_HRP <- cbind(LSTs_all_parameters_HRP,LSTs_per_sampleTCGA_HRP) LSTs_per_sampleTCGA_HRD <- LSTs(preprocessed_HRD_TCGA, mindistance = m, segsizes = s, tandemelements = t) LSTs_all_parameters_HRD <- cbind(LSTs_all_parameters_HRD,LSTs_per_sampleTCGA_HRD) } } } #Generate column names #Column names have the next structure: m1_t2_s5 #m means the minimum segment size for smoothing #t number of tandem elements #s minimum size of AI that is included in for a LSTs column_names <- c("x","y") for (m in mindistance_values){ for (s in segsizes_values){ for (t in tandemelements_Values){ #Column names name <- paste(paste("m", m, sep=""), paste("t", t, sep=""), paste("s", s, sep=""), sep="_") print(name) column_names <- c(column_names, name) } } } ######Add column and row names###### colnames(LSTs_all_parameters_HRP) <- column_names LSTs_all_parameters_HRP <- LSTs_all_parameters_HRP[,-c(1,2)] #Removing random numbers colnames(LSTs_all_parameters_HRD) <- column_names LSTs_all_parameters_HRD <- LSTs_all_parameters_HRD[,-c(1,2)] #Removing random numbers LSTs_all_parameters_HRD$samples <- row.names(LSTs_all_parameters_HRD) LSTs_all_parameters_HRP$samples <- row.names(LSTs_all_parameters_HRP) ############ Plotting each distribution of segments in sample by HR status ############### #Segments sizes per LSTs, considered with a minimum of 1Mb and two tandem segments #No a plot in manuscript m <- 1 t <- 2 average_proportions_HRD columns_to_get <- NULL for (s in segsizes_values){ column <- paste(paste("m", m, sep=""), paste("t", t, sep=""), paste("s", s, sep=""), sep="_") columns_to_get <- c(columns_to_get, column) } for (sample in 1:length(row.names(LSTs_all_parameters_HRD))){ if (sample == 1){ values_sample <- LSTs_all_parameters_HRD[sample,columns_to_get] plot(segsizes_values, values_sample, type="l", lwd=1.2, ylim=c(4,86), xlim=c(5,20), pch=20, xlab="Segment size, Mb", ylab="State transitions") }else{ values_sample <- LSTs_all_parameters_HRD[sample,columns_to_get] lines(segsizes_values, values_sample, type="l", lwd=1.2, pch=20) } } for (sample in 1:length(row.names(LSTs_all_parameters_HRP))){ values_sample <- LSTs_all_parameters_HRP[sample,columns_to_get] lines(segsizes_values, values_sample, type="l", lwd=1.2, pch=20, col="blue") } legend(15,80, c("HRD","HRP"), col = c("black","blue"), lty = 1) ################# Calculus of p values and accuracy for the difference in abundance of LSTs between HRD and HRP######## ######Function to use ############ calculate.pvalues.BA <- function(abundances.LSTs.HRD, abundances.LSTs.HRP, min.distances=mindistance_values, segments.sizes=segsizes_values, tandem.elements=2){ values_by_mindist <- NULL for (m in min.distances){ Pvalues_bySegments <- NULL ACC_bySegments <- NULL for (s in segments.sizes){ column <- paste(paste("m", m, sep=""), paste("t", tandem.elements, sep=""), paste("s", s, sep=""), sep="_") print(column) all.pvals <- NULL all.BA <- NULL #for (i in 1:1000){ #This for loop was used for jacknifing #HRD.samples.extract <- nrow(abundances.LSTs.HRD)-1 #HRP.samples.extract <- nrow(abundances.LSTs.HRP) - 1 HRP.samples.extract <- nrow(abundances.LSTs.HRP) HRD.samples.extract <- nrow(abundances.LSTs.HRD) abundances.LSTs.HRD.sample <- sample(abundances.LSTs.HRD[,column], HRD.samples.extract, replace = FALSE) #This was used for jacknifing sampling abundances.LSTs.HRP.sample <- sample(abundances.LSTs.HRP[,column], HRP.samples.extract, replace = FALSE) #This was used for jacknifing sampling test_u <- wilcox.test(abundances.LSTs.HRD.sample, abundances.LSTs.HRP.sample, alternative = "greater") pvals <- test_u$p.value all.pvals <- c(all.pvals, pvals) acc_iteration <- get_dispertion_acc(abundances.LSTs.HRD.sample, abundances.LSTs.HRP.sample) all.BA <- c(all.BA, acc_iteration) #} Pvalues_bySegments <- c(Pvalues_bySegments, mean(all.pvals)) ACC_bySegments <- c(ACC_bySegments, mean(all.BA)) } j <- data.frame(pvalues=Pvalues_bySegments, BA=ACC_bySegments, S_Mb = segments.sizes, mdist_Mb = as.numeric(c(rep(m,length(Pvalues_bySegments)))), values_by_tandem = rep(tandem.elements,length(Pvalues_bySegments))) values_by_mindist <- rbind(values_by_mindist, j) } values_by_mindist$logFDR <- (-1) * log10(values_by_mindist$pvalues) values_by_mindist$mdist_Mb <- as.factor(values_by_mindist$mdist_Mb) values_by_mindist$S_Mb <- as.factor(values_by_mindist$S_Mb) return(values_by_mindist) } #For each combination of parameters m l t# BA.pvals.LSTs.t2 <- calculate.pvalues.BA(LSTs_all_parameters_HRD, LSTs_all_parameters_HRP, tandem.elements=2) BA.pvals.LSTs.t3 <- calculate.pvalues.BA(LSTs_all_parameters_HRD, LSTs_all_parameters_HRP, tandem.elements=3, segments.sizes=c(1:12)) #Plotting accuracy and p.values of difference in abundance between HRD and HRP for two tandem AIs #For Sup.Figure 2d p <- ggplot(BA.pvals.LSTs.t2, aes(x=S_Mb, y=mdist_Mb)) p <- p + geom_point(aes(color=logFDR, size=BA)) + theme_classic() p <- p + scale_color_gradientn(name="-log10(p.val)", colours = c("blue3", "darkcyan", "red"), values=c(0,0.90,1), limits=c(3.8,12.5)) p <- p + scale_radius(breaks = c(0.75, 0.80, 0.85, 0.90), limits=c(0.58,0.91), range = c(2,7)) p <- p + theme(axis.text=element_text(size=rel(1.1)), strip.placement = "outside",strip.background = element_blank(), axis.text.x=element_text(size=rel(1.3)), axis.text.y=element_text(size=rel(1.3)), legend.text=element_text(size=rel(1.1)), legend.title=element_text(size=rel(1.2)), axis.title=element_text(size=rel(1.5))) p <- p + guides(colour = guide_colourbar(order = 1), size = guide_legend(keyheight = 1)) p <- p + ylab("Space between AIs (Mb)\n") + xlab("\nMinimun size of AIs (Mb)") print(p) ggsave(p, filename = paste0(outputfolder, "LSTs-windows_pvalues_dotplot_segmentsHGSC_t2.svg"), width = 20, height = 9, units = "cm") ggsave(p, filename = paste0(outputfolder, "LSTs-windows_pvalues_dotplot_segmentsHGSC_t2.png"), width = 20, height = 9, units = "cm") #Plotting accuracy and p.values of difference in abundance between HRD and HRP for three tandem AIs #For Sup.Figure 2e p <- ggplot(BA.pvals.LSTs.t3, aes(x=S_Mb, y=mdist_Mb)) p <- p + geom_point(aes(color=logFDR, size=BA)) + theme_classic() p <- p + scale_color_gradientn(name="-log10(p.val)", colours = c("blue3", "darkcyan", "red"), values=c(0,0.90,1), limits=c(3.8,12.5)) p <- p + scale_radius(breaks = c(0.75, 0.80, 0.85, 0.90), limits=c(0.58,0.91), range = c(2,7)) p <- p + theme(axis.text=element_text(size=rel(1.1)), strip.placement = "outside",strip.background = element_blank(), axis.text.x=element_text(size=rel(1.3)), axis.text.y=element_text(size=rel(1.3)), legend.text=element_text(size=rel(1.3)), legend.title=element_text(size=rel(1.3)), axis.title=element_text(size=rel(1.5))) p <- p + guides(colour = guide_colourbar(order = 1), size = guide_legend(keyheight = 1)) p <- p + ylab("Space between AIs (Mb)\n") + xlab("\nMinimun size of AIs (Mb)") print(p) ggsave(p, filename = paste0(outputfolder, "LSTs-windows_pvalues_dotplot_segmentsHGSC_t3.svg"), width = 20, height = 9, units = "cm") ggsave(p, filename = paste0(outputfolder, "LSTs-windows_pvalues_dotplot_segmentsHGSC_t3.png"), width = 20, height = 9, units = "cm") #Best values for distinguishing LSTs are segments longer than 9Mb and a space (smoothing) of 1Mb BA.pvals.LSTs.t2[which.max(BA.pvals.LSTs.t2$BA * BA.pvals.LSTs.t2$logFDR),] #Printing the accuracy of the Telli2016 for separating HRD or HRPcolum BA.pvals.LSTs.t2[BA.pvals.LSTs.t2$S_Mb == "10" & BA.pvals.LSTs.t2$mdist_Mb == "3",] #Printing the accuracy of the of distinguished best cutoffs (values) BA.pvals.LSTs.t2[BA.pvals.LSTs.t2$S_Mb == "12" & BA.pvals.LSTs.t2$mdist_Mb == "1",] ####### Boxplots to compare the separation between HRP and HRD samples using the new cutoff ########## #The best value before reported was "m3_t2_s10" status1 <- rep("HRD", length(LSTs_all_parameters_HRD[,"m3_t2_s10"])) status2 <- rep("HRP", length(LSTs_all_parameters_HRP[,"m3_t2_s10"])) Scars_definition <- rep("Previous", length(c(LSTs_all_parameters_HRD[,"m3_t2_s10"], LSTs_all_parameters_HRP[,"m3_t2_s10"]))) previosLSTS <- data.frame(HRDstatus=c(status1, status2), LSTs=c(LSTs_all_parameters_HRD[,"m3_t2_s10"], LSTs_all_parameters_HRP[,"m3_t2_s10"]), Scars_def=Scars_definition) #The best value here identified was "m1_t2_s11" Scars_definition2 <- rep("New proposal", length(c(LSTs_all_parameters_HRD[,"m1_t2_s9"], LSTs_all_parameters_HRP[,"m1_t2_s9"]))) newLSTS <- data.frame(HRDstatus=c(status1, status2), LSTs=c(LSTs_all_parameters_HRD[,"m1_t2_s9"], LSTs_all_parameters_HRP[,"m1_t2_s9"]), Scars_def=Scars_definition2) LSTs_scars_comparision <- rbind(previosLSTS, newLSTS) p <- ggplot(LSTs_scars_comparision, aes (x=HRDstatus, y=LSTs)) + geom_boxplot(alpha = 0.5, outlier.shape = NA) p <- p + facet_wrap(~Scars_def) p <- p + ylab("LSTs scars") + xlab("") p <- p + theme(axis.text=element_text(size=rel(1.5)), strip.placement = "outside",strip.background = element_blank(), axis.text.x=element_text(size=rel(1.3)), axis.text.y=element_text(size=rel(1.3)), legend.text=element_text(size=rel(1.4)), strip.text.x = element_text(size=rel(2.8)), legend.title=element_text(size=rel(2)), axis.title=element_text(size=rel(2.5)), panel.spacing = unit(1, "lines"), panel.border = element_rect(linetype = "solid", fill = NA), panel.background = element_rect(fill = "white"), panel.grid.major = element_line(size = 0.5, linetype = 'solid', colour = "lightgrey"), panel.grid.minor = element_line(size = 0.5, linetype = 'solid', colour = "lightgrey"), panel.grid.major.x = element_blank(), panel.grid.minor.x = element_blank()) p <- p + geom_point(aes(y=LSTs, color=HRDstatus), position= position_jitter(width= .3), size= 3, alpha = 0.7, show.legend = FALSE) p <- p + ylim(0,50) print(p) ggsave(p, filename = "/home/fernpere/HRD/Figures/LSTs-previous_new_scars_boxplot.svg", width = 36, height = 20, units = "cm") ggsave(p, filename = "/home/fernpere/HRD/Figures/LSTs-previous_new_scars_boxplot.png", width = 36, height = 20, units = "cm") ########################### Get cutoff for that separe LSTs for HRPs and HRDs ############################### LSTs_per_sampleTCGA_HRP <- LSTs(preprocessed_HRP_TCGA, segsizes=9e6, mindistance=1e6, tandemelements=2) LSTs_per_sampleTCGA_HRD <- LSTs(preprocessed_HRD_TCGA, segsizes=9e6, mindistance=1e6, tandemelements=2) dA <- data.frame(LSTs=LSTs_per_sampleTCGA_HRD, anyvalue=rep(2,length(LSTs_per_sampleTCGA_HRD)), status=rep("HRD",length(LSTs_per_sampleTCGA_HRD))) dB <- data.frame(LSTs=LSTs_per_sampleTCGA_HRP, anyvalue=rep(2,length(LSTs_per_sampleTCGA_HRP)), status=rep("HRP",length(LSTs_per_sampleTCGA_HRP))) dz <- rbind(dA,dB) fit <- rpart(status ~ ., data=dz, method='class', control=rpart.control(minsplit = 2, minbucket = 1, cp=0.001)) #Identify cutoff value <- rpart.subrules.table(fit)[1,5] cutoff <- as.numeric(value) cutoff #Cutoff is 13.5
12884727235ae90697bead1a556bda8d0f06dcf1
19db2fd88fa5278e7427807b177de0513ddbb6a3
/R.functions/alltimerecord.R
385d1e2eb891e9f471d45c842cbaa6058abfc1a0
[]
no_license
dmrust/engsoccerdata
86e6b57cc1050d42677c73cc3b8ff2cf32771241
1fd9e37c6637d2180837ab4460c5f4ba7547f47b
refs/heads/master
2021-01-16T22:13:08.762163
2014-10-10T23:43:53
2014-10-10T23:43:53
null
0
0
null
null
null
null
UTF-8
R
false
false
900
r
alltimerecord.R
### Function to List the all-time records of a team alltimerecord<-function (df, teamname) { library(dplyr) library(tidyr) hrec<-df %>% filter(home==teamname) %>% summarise(P = n(), W=sum(result=="H"), D=sum(result=="D"), L=sum(result=="A"), GF = sum(hgoal), GA = sum(vgoal), GD=sum(goaldif)) vrec<-df %>% filter(visitor==teamname) %>% summarise(P = n(), W=sum(result=="A"), D=sum(result=="D"), L=sum(result=="H"), GF = sum(vgoal), GA = sum(hgoal), GD=GF-GA,) temp<-rbind(hrec,vrec,hrec+vrec) rownames(temp)<-c("home", "away", "total") return(temp) } #Examples alltimerecord(df, "Aston Villa") alltimerecord(df, "Arsenal") alltimerecord(df, "Liverpool") alltimerecord(df, "Manchester United") alltimerecord(df, "York City") alltimerecord(df, "Rochdale") alltimerecord(df, "Birmingham City") alltimerecord(df, "Leeds City")
e3fdd4b45b9a0c8375ae07dc96d24ae6d67859b2
b59cc783d2da2f32737432c1b13cf72c5802f067
/man/Oral.Rd
c389daba49bc956841522c48d8b4dcca8d7fc6fd
[]
no_license
jdsimkin04/shinyinla
9a16007b375975a3f96b6ca29a1284aa6cafb180
e58da27a2a090557058b2a5ee63717b116216bf7
refs/heads/master
2023-06-05T08:34:34.423593
2021-06-24T00:27:04
2021-06-24T00:27:04
330,322,338
0
1
null
null
null
null
UTF-8
R
false
true
554
rd
Oral.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/INLA-package.R \docType{data} \name{Oral} \alias{Oral} \title{~~ data name/kind ... ~~} \format{ A data frame with 544 observations on the following 3 variables. \describe{ \item{region}{a numeric vector} \item{E}{a numeric vector} \item{Y}{a numeric vector} } } \description{ ~~ A concise (1-5 lines) description of the dataset. ~~ } \references{ Rue, H and Held, L. (2005) \emph{Gaussian Markov Random Fields - Theory and Applications} Chapman and Hall } \keyword{datasets}
087c3b7cae149070d6457bd58f3cc04f0bb2c76a
9f8d324923a02ceda5637d5b6b230eb2c661e820
/man/createVarSyntax.Rd
1422d5c2bf6d761bb361881e6569971c62d0aeb0
[]
no_license
wang-ze/MplusAutomation
bff30512541b3ff3fddb50044c2f2d3f7666f47e
46e329d2ce403c88e0177906543d950947ca1ff1
refs/heads/master
2020-04-02T10:35:44.741395
2018-10-01T16:53:37
2018-10-01T16:53:37
null
0
0
null
null
null
null
UTF-8
R
false
true
608
rd
createVarSyntax.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/createModels.R \name{createVarSyntax} \alias{createVarSyntax} \title{Create Mplus syntax for variable names} \usage{ createVarSyntax(data) } \arguments{ \item{data}{An \code{R} dataset.} } \value{ A character vector of the variable names for Mplus } \description{ This is a simple function designed to take a dataset in \code{R} and translate it into a set of variable names for Mplus. } \examples{ MplusAutomation:::createVarSyntax(mtcars) } \seealso{ \code{\link{prepareMplusData}} } \keyword{internal}
83d6f6cb6c0738e8d1cd34c1e98ed3d25636d71d
5bacfd2bd5fad918a06fbe5334a8447e855495d0
/model/prep-data.R
92255635b0bf90bbe828974785b47f34d7ea2a74
[]
no_license
CoryMcCartan/us-house-18
6464ec20d3ff767b3f9ba9f50cc3c2fbb014b3de
68ec2376e9b2001c51e8085e985618774fdd3c79
refs/heads/master
2022-04-14T07:57:50.165690
2020-03-11T02:06:50
2020-03-11T02:06:50
113,709,747
0
0
null
null
null
null
UTF-8
R
false
false
4,307
r
prep-data.R
# DATA PREPARATION library(Hmisc) library(pollstR) library(tidyverse) library(lubridate) election.day = as.Date("2018-11-06") # Past Presidential approval president = read.csv("data/past_pres_approval_raw.csv", sep="\t") %>% transmute(approval=Approving / 100, date=mdy(End.Date), president=President, party=Party) %>% filter(year(date) >= 1970, year(date) <= 2030) %>% arrange(date) write.csv(president, "data/past_pres_approval.csv", row.names=F) # Current polling polls = pollster_charts_polls("2018-national-house-race")[["content"]] %>% filter(partisanship == "Nonpartisan") %>% transmute(dem = Democrat / 100, gop = Republican / 100, other = Other / 100, undecided = Undecided / 100, n_resp = observations, n_side = round((dem + gop) * n_resp), n_dem = round(dem * n_resp), pollster = survey_house, firm.id = as.numeric(as.factor(pollster)), date = ymd(end_date), type = recode(sample_subpopulation, `Registered Voters`="RV", `Likely Votesrs`="LV")) %>% as.data.frame # drop missing data polls = polls[complete.cases(polls),] # week IDs start.day = min(polls$date) end.day = max(polls$date) n.weeks = ceiling(as.numeric(election.day - start.day) / 7) polls$week = floor(as.numeric(election.day - polls$date) / 7) # output write.csv(polls, "data/current_polls.csv", row.names=F) # past polling past.polls = read.csv("data/raw_past_polling.csv") %>% filter(type_simple == "House-G", location == "US") election.dates = unique(mdy(past.polls$electiondate)) lgt = function(x) log(x / (1-x)) past.polls %<>% transmute(year = year, n_resp = samplesize, dem = cand1_pct/(cand1_pct + cand2_pct), logit = lgt(dem), weeks.until = round(as.numeric( mdy(electiondate) - mdy(polldate)) / 7)) %>% group_by(year, weeks.until) %>% summarise(lgt = wtd.mean(logit, sqrt(n_resp)), sd = sqrt(wtd.var(logit, sqrt(n_resp)))) %>% filter(!is.na(sd), sd > 0) %>% as.data.frame # manually add more data new.pp = data.frame(year=c(1974, 1982, 1994), weeks.until=0, lgt=c(lgt(0.56/0.86), c(0.54/0.9), 0), sd=NA) election.dates = c(election.dates, ymd("1974-11-01", "1982-11-01", "1994-11-01")) past.polls = rbind(past.polls, new.pp) # Merge economy = read.csv("data/economy.csv", na.strings=".") %>% transmute(date = ymd(DATE), unemp = as.numeric(UNRATE) / 100, gdp = as.numeric(A939RX0Q048SBEA_PC1) / 100, infl = as.numeric(CPIAUCSL_PC1) / 100, earn = as.numeric(AHETPI_PC1) / 100) %>% filter(year(date) > 1970) congress = read.csv("data/congress_approval.csv") control = read.csv("data/party_control.csv") %>% mutate(midterm = ifelse((elect.year %% 4) == 2, 1, 0)) fundamentals = data.frame(year=year(election.dates), approval=0, unemp=0, gdp=0, earn=0) for (i in 1:length(election.dates)) { d = election.dates[i] appr = (president %>% filter(abs(date - d) < 120 & abs(date - d) > 30) %>% summarise(m = mean(approval)))$m econ = economy %>% filter(abs(date - d) < 120 & abs(date - d) > 30) %>% summarise(unemp = mean(unemp), gdp = mean(gdp), earn = mean(earn)) fundamentals[i,2] = log(appr / (1 - appr)) fundamentals[i,3] = econ$unemp fundamentals[i,4] = econ$gdp fundamentals[i,5] = econ$earn } code = function(x) 2*x - 1 combined = past.polls %>% left_join(control, by=c("year"="elect.year")) %>% left_join(fundamentals, by=c("year")) %>% transmute(year, weeks_until=weeks.until, logit_intent=lgt, sd_intent=sd, seats=dem.seats, before=dem.before, pres=code(dem.pres), house=code(dem.house), midterm=midterm, appr=approval, unemp, gdp, earn) # manually add 1974 and fix 2014 combined$weeks_until[combined$year==2014][1] = 0 combined[combined$year==1974, c("seats", "before", "pres", "house", "midterm")] = c(291, 242, -1, 1, 1) write.csv(combined, "data/combined.csv", row.names=F)
6e30af7bce154626d05a91492075294a7baea557
778cb2c2de4a80efa6e7ca006961759bbd12a028
/zone_detailed.R
7b0345454b6951bfa67fa19318785fa2c9311122
[]
no_license
victor-gallet/kaggle-kobe
6fb73ff522d75d5ed0e047cdea782e853721ed8c
0de2be4e2d058e1a1f5baaa252ce221c895f81b5
refs/heads/master
2016-09-12T09:14:10.304519
2016-06-02T19:09:51
2016-06-02T19:09:51
58,809,155
0
0
null
null
null
null
UTF-8
R
false
false
3,284
r
zone_detailed.R
library(ggplot2) library(dplyr) library('png') shots = read.csv("data/data.csv", stringsAsFactors = T) train = shots[!is.na(shots$shot_made_flag),] test = shots[is.na(shots$shot_made_flag),] courtplot <- function(feat) { feat <- substitute(feat) train %>% ggplot(aes(x = loc_x, y = loc_y)) + geom_point(aes_q(color = feat), alpha = 0.7, size = 3) + theme_void() + ggtitle(paste(feat)) } train$shot_zone_detailed <- NA train$shot_zone_detailed[train$loc_x <= -220 & train$loc_y <= 100 & train$shot_type == "3PT Field Goal"] = "1" train$shot_zone_detailed[train$loc_x >= -220 & train$loc_x <= -150 & train$loc_y <= 100 & train$shot_type == "2PT Field Goal"] = "2" train$shot_zone_detailed[train$loc_x < -90 & train$shot_type == "3PT Field Goal" & train$loc_y > 100] = "3" train$shot_zone_detailed[train$loc_x < 90 & train$loc_x > -90 & train$shot_type == "3PT Field Goal"] = "4" train$shot_zone_detailed[train$loc_x < 70 & train$loc_x > -70 & train$loc_y > 150 & train$shot_type == "2PT Field Goal"] = "6" train$shot_zone_detailed[train$loc_x > 70 & train$shot_type == "3PT Field Goal"] = "7" train$shot_zone_detailed[train$loc_x < 90 & train$loc_x > -90 & train$loc_y > 90 & train$loc_y < 150 & train$shot_type == "2PT Field Goal"] = "10" train$shot_zone_detailed[sqrt(train$loc_x^2 + train$loc_y^2) < 90] = "12" train$shot_zone_detailed[train$loc_x < 220 & train$loc_x > 150 & train$loc_y <= 100] = "13" train$shot_zone_detailed[train$loc_x > 220 & train$loc_y < 100 & train$shot_type == "3PT Field Goal"] = "14" train$shot_zone_detailed[is.na(train$shot_zone_detailed) & train$loc_y > 100 & train$loc_x > -210 & train$loc_x < 70] = "5" train$shot_zone_detailed[is.na(train$shot_zone_detailed) & train$loc_y > 100 & train$loc_x >= 70 & train$loc_x < 210] = "8" train$shot_zone_detailed[is.na(train$shot_zone_detailed) & train$loc_y <= 100 & train$loc_x < 0] = "9" train$shot_zone_detailed[is.na(train$shot_zone_detailed) & train$loc_y <= 100 & train$loc_x > 0] = "11" train$shot_zone_detailed = as.factor(train$shot_zone_detailed) courtplot(shot_zone_detailed) summary(train$shot_zone_detailed) ## Construction mean_x = aggregate(train$loc_x, list(train$shot_zone_detailed), na.rm = TRUE, mean) mean_y = aggregate(train$loc_y, list(train$shot_zone_detailed), na.rm = TRUE, mean) mean_xy = data.frame(mean_x$Group.1, mean_x$x, mean_y$x) pourcentage_shot = as.data.frame(prop.table(table(train$shot_made_flag, train$shot_zone_detailed), 2)) shot_made_by_zone = as.data.frame(table(train$shot_made_flag, train$shot_zone_detailed)) plot(1, type="n", xlab="", ylab="", xlim=c(-235, 235), ylim=c(-30, 400)) lim <- par() rasterImage(courtimg, lim$usr[1], lim$usr[3], lim$usr[2], lim$usr[4]) grid() for (zone in 1:14) { x = mean_xy[mean_xy$mean_x.Group.1 == zone,]$mean_x.x y = mean_xy[mean_xy$mean_x.Group.1 == zone,]$mean_y.x text_pourcentage = pourcentage_shot[pourcentage_shot$Var1 == 1 & pourcentage_shot$Var2 == zone,]$Freq success_shot = shot_made_by_zone[shot_made_by_zone$Var2 == zone & shot_made_by_zone$Var1 == 1,]$Freq missed_shot = shot_made_by_zone[shot_made_by_zone$Var2 == zone & shot_made_by_zone$Var1 == 0,]$Freq text(x, y, sprintf("%d%% \n %d / %d", round(text_pourcentage * 100), success_shot, success_shot + missed_shot)) }
e2a71063b9ff7232d19a769d7b1a9dbacc7b3f01
66103bd7268a8f6bb811141c759f58515e962428
/src/interface_r/R/reexports.R
a3724247f389a271607eba8ba26816a4ad21dcd8
[ "BSD-3-Clause", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
pnijhara/h2o4gpu
38a6f17cfd61f712bb709de187127a67ee36e106
6257112c134136471420b68241f57190a445b67d
refs/heads/master
2022-07-03T03:08:53.108604
2020-04-29T16:44:46
2020-04-29T16:44:46
260,985,697
0
0
Apache-2.0
2020-05-04T12:23:05
2020-05-03T17:38:46
null
UTF-8
R
false
false
138
r
reexports.R
#' @export magrittr::`%>%` #' @export reticulate::use_condaenv #' @export reticulate::use_python #' @export reticulate::use_virtualenv
63a122dda0f343fc84dc42c024a59c5fbbdb207e
6464efbccd76256c3fb97fa4e50efb5d480b7c8c
/paws/man/codecommit_get_pull_request.Rd
ddb380bdf8e9a5d221e66e79fddf57527580456f
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
johnnytommy/paws
019b410ad8d4218199eb7349eb1844864bd45119
a371a5f2207b534cf60735e693c809bd33ce3ccf
refs/heads/master
2020-09-14T23:09:23.848860
2020-04-06T21:49:17
2020-04-06T21:49:17
223,286,996
1
0
NOASSERTION
2019-11-22T00:29:10
2019-11-21T23:56:19
null
UTF-8
R
false
true
624
rd
codecommit_get_pull_request.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/codecommit_operations.R \name{codecommit_get_pull_request} \alias{codecommit_get_pull_request} \title{Gets information about a pull request in a specified repository} \usage{ codecommit_get_pull_request(pullRequestId) } \arguments{ \item{pullRequestId}{[required] The system-generated ID of the pull request. To get this ID, use ListPullRequests.} } \description{ Gets information about a pull request in a specified repository. } \section{Request syntax}{ \preformatted{svc$get_pull_request( pullRequestId = "string" ) } } \keyword{internal}
b9afee20218629fef1510e9541a4a76fe39cdd1d
17fd4de354250e4f9b5d4b00bd04bf21971c7425
/data_analysis.R
bee6eeee8b3069a15328beb46794bd7df1e7715e
[ "MIT" ]
permissive
martinfriedrichsmanthey/Red_List_Fish_Data
14dd752d5902e4179a6f075f07572f51af5f92ca
151cde81dbdbf74d49060e2d984ff5de4d87258d
refs/heads/main
2023-07-18T14:05:55.184607
2021-08-31T13:19:06
2021-08-31T13:19:06
377,147,853
0
0
null
null
null
null
UTF-8
R
false
false
6,613
r
data_analysis.R
#### fish population trends for Red List in Germany ##### initial settings #### ### path to data dat_dir<-"C:/Users/zf53moho/Documents/NFDI4BioDiv/Data/Fish Data/Fischdaten_Datenbank/Red_List_Fish_Data/clean_data/" save_dir<-"C:/Users/zf53moho/Documents/NFDI4BioDiv/Data/Fish Data/Fischdaten_Datenbank/Red_List_Fish_Data/modelling_results/" setwd(dat_dir) ### packages library(brms) library(rstan) library(foreach) library(doParallel) rstan_options(auto_write = TRUE) options(mc.cores = parallel::detectCores()) #8 ##### load and prepare data #### main_dat<-read.csv("clean_data.csv") #centre year, month_year and day_year main_dat$factor_year<- as.factor(main_dat$year) main_dat$scaled_year <- scale(main_dat$year, scale=F) main_dat$index_year<-main_dat$year - 2003 main_dat$scaled_year_day <- scale(main_dat$year_day) main_dat$scaled_year_month <- scale(main_dat$year_month) specs<- unique(main_dat$species) ### list all species specs<-specs[order(specs)] #### general infos #### Rhat should be less than 1.1 #### we could predict trends for each site and species and plot them #### plot the random slopes for each species to see the variation among sites # sd(scaled_year) 0.19 0.03 0.14 0.25 #### use the predict function to predict the amount of species for a certain day with certain effort within a year #### pirateplots to visualise the data #### include seasonality --> I(year_day^2) ---> models do not converge #### the -1 in front of the model formula removes the intercept #### factor year only for visualization #### the offset(log(effort_m)) indicates that we assume that we would catch the twice the amount of species if we double the effort #setup parallel backend to use many processors #cores=detectCores() #cl <- makeCluster(cores[1]-3) #not to overload your computer #registerDoParallel(cl) #p<-foreach(i=1:length(specs), .packages="brms") %dopar% for (i in 1:length(specs)) { tmp_spec<-subset(main_dat,main_dat$species==specs[i]) #### model to find trends per year for each species if(file.exists(paste0(save_dir,"factor_",specs[i],".rds"))==FALSE) { mod_factor_year <- brm(n_individuals ~ -1 + factor_year + year_day + offset(log(effort_m)) +(1|unique_ID), data = tmp_spec, family = negbinomial()) saveRDS(mod_factor_year, file = paste0(save_dir,"factor_",specs[i],".rds")) rm(mod_factor_year) } #### model for overall trend if(file.exists(paste0(save_dir,"index_",specs[i],".rds"))==FALSE) { mod_index_year <- brm(n_individuals ~ index_year + year_day + offset(log(effort_m)) + (1+scaled_year|unique_ID), data = tmp_spec, family = negbinomial()) saveRDS(mod_index_year, file = paste0(save_dir,"index_",specs[i],".rds")) rm(mod_index_year) } rm(tmp_spec) } mod_factor_year <- brm(n_individuals ~ -1 + factor_year + year_day + offset(log(effort_m)) +(1|unique_ID), data = tmp_spec, family = negbinomial()) saveRDS(mod_factor_year, file = paste0(save_dir,"factor_",specs[3],".rds")) mod_index_year <- brm(n_individuals ~ index_year + year_day + offset(log(effort_m)) + (1+scaled_year|unique_ID), data = tmp_spec, family = negbinomial()) saveRDS(mod_index_year, file = paste0(save_dir,"index_",specs[3],".rds")) #### simplest model for 1 species and all years #Family: negbinomial #Links: mu = log; shape = identity #Formula: n_individuals ~ scaled_year + year_day + year_day^2 + (1 + scaled_year | unique_ID) #Data: tmp_spec (Number of observations: 1066) #Samples: 4 chains, each with iter = 2000; warmup = 1000; thin = 1; #total post-warmup samples = 4000 # #Group-Level Effects: # ~unique_ID (Number of levels: 259) # Estimate Est.Error l-95% CI u-95% CI Rhat Bulk_ESS Tail_ESS #sd(Intercept) 2.54 0.14 2.27 2.83 1.00 1047 1957 #sd(scaled_year) 0.79 0.12 0.56 1.03 1.00 1028 2148 #cor(Intercept,scaled_year) -0.65 0.11 -0.84 -0.42 1.00 1100 2148 # #Population-Level Effects: # Estimate Est.Error l-95% CI u-95% CI Rhat Bulk_ESS Tail_ESS #Intercept 2.01 0.31 1.42 2.61 1.00 2381 3021 #scaled_year 1.03 0.10 0.84 1.22 1.00 2469 2771 #year_day 0.00 0.00 0.00 0.01 1.00 5124 3414 # #Family Specific Parameters: # Estimate Est.Error l-95% CI u-95% CI Rhat Bulk_ESS Tail_ESS #shape 0.47 0.03 0.41 0.53 1.01 1209 3017 # #Samples were drawn using sampling(NUTS). For each parameter, Bulk_ESS #and Tail_ESS are effective sample size measures, and Rhat is the potential #scale reduction factor on split chains (at convergence, Rhat = 1). #### simplest model for 1 species and all years fit1_all_years_method <- brm(n_individuals ~ scaled_year + year_day + offset(log(effort_m)) + (1+scaled_year|unique_ID), data = tmp_spec, family = negbinomial()) ##### random slopes for scaled year (1+scaled...) fit1_all_years_method plot(fit1_all_years_method) fixef(fit1_all_years_method) ?brm #fit1_all_years_factor_seasonality <- brm(n_individuals ~ -1 + factor_year + year_day + I(year_day^2) + offset(log(effort_m)) +(1|unique_ID), data = tmp_spec, family = negbinomial()) #### the -1 removes the intercept #### factor year only for visualization #fit1_all_years_factor_seasonality #plot(fit1_all_years_factor_seasonality) #fixef(fit1_all_factor_seasonality) ##### models with seasonality do not converge ### model for eals tmp_anguilla<- subset(main_dat,main_dat$species==specs[7]) tmp_anguilla_all_years <- brm(n_individuals ~ scaled_year, data = tmp_anguilla, family = negbinomial()) tmp_anguilla_all_years #Family: negbinomial #Links: mu = log; shape = identity #Formula: n_individuals ~ scaled_year #Data: tmp_anguilla (Number of observations: 12197) #Samples: 4 chains, each with iter = 2000; warmup = 1000; thin = 1; #total post-warmup samples = 4000 # #Population-Level Effects: # Estimate Est.Error l-95% CI u-95% CI Rhat Bulk_ESS Tail_ESS #Intercept 2.28 0.02 2.24 2.31 1.00 3979 2176 #scaled_year -0.33 0.02 -0.36 -0.29 1.00 3857 2893 # #Family Specific Parameters: # Estimate Est.Error l-95% CI u-95% CI Rhat Bulk_ESS Tail_ESS #shape 0.27 0.00 0.26 0.27 1.00 4301 3320 # #Samples were drawn using sampling(NUTS). For each parameter, Bulk_ESS #and Tail_ESS are effective sample size measures, and Rhat is the potential #scale reduction factor on split chains (at convergence, Rhat = 1).
198ff94b3d6080b9d974250e8cff66c811fe6821
364f92a555ab90d567c425de039cb3f050956842
/Downstream_processing/Culex_DESeq.R
881de927cd183a2e3ef0a399d13c632e7afbded3
[]
no_license
mcadamme/Culex_RNAseq_Chemosensory
57c79388f6be70579faf329c5eaeddf15e04285d
a9d379a309ddf4b7e37b22e184656fd4de4cfbd7
refs/heads/master
2021-04-26T23:16:28.358939
2021-03-02T15:08:42
2021-03-02T15:08:42
123,960,205
0
1
null
null
null
null
UTF-8
R
false
false
26,439
r
Culex_DESeq.R
#script to run DESeq2 #10/20/2020 MF ##Install DESeq2 #if (!requireNamespace("BiocManager", quietly = TRUE)) #install.packages("BiocManager") #BiocManager::install("DESeq2") #BiocManager::install('EnhancedVolcano') #Load Libraries library(DESeq2); library(pheatmap); library(ashr); library(EnhancedVolcano); library(magrittr); library(ggfortify); library(reshape2); library(ggplot2); library(GOplot); library(arm) #set working directory hiQual_Ex<-("/media/fritzlab/EE9C16C89C168AEB/Noreuil/trimmed_pairs/DGE_GenAligned_SamFiles/highQual_exon/") setwd(hiQual_Ex) #Load in read counts and assign them sample labels outputPrefix<-("Culex_DEseq") sampleFiles<-c("M1-1_S1_htseq","M1-2_S2_htseq","M1-3_S3_htseq","M1-4_S4_htseq","M2-1_S5_htseq","M2-2_S6_htseq","M2-3_S7_htseq","M2-4_S8_htseq","M4-1_S13_htseq","M4-2_S14_htseq","M4-3_S15_htseq","M4-4_S16_htseq") sampleNames<-c("BG_Gravid1", "BG_Gravid2", "BG_Gravid3", "BG_Gravid4", "BG_Parous1", "BG_Parous2", "BG_Parous3", "BG_Parous4", "AG1", "AG2", "AG3", "AG4") sampleCondition<-c("CALgravidF", "CALgravidF", "CALgravidF", "CALgravidF", "CALparousF", "CALparousF", "CALparousF", "CALparousF", "PipEvanF", "PipEvanF", "PipEvanF", "PipEvanF") sampleTable<-data.frame(sampleName=sampleNames, fileName=sampleFiles, condition=sampleCondition) treatments<-c("CALgravidF", "CALparousF", "PipEvanF") #Create DESeq Data - CHANGE DIRECTORY ddsHTSeq <- DESeqDataSetFromHTSeqCount(sampleTable = sampleTable, directory = hiQual_Ex, design= ~ condition) colData(ddsHTSeq)$condition <- factor(colData(ddsHTSeq)$condition, levels=treatments) dim(ddsHTSeq)#getting num genes in dataset and verifying num samples #Prefilter so only genes with at least 10 reads in at least 4 samples are considered keep <- rowSums(counts(ddsHTSeq) >= 10) >= 4 ddsHTSeq <- ddsHTSeq[keep,] dim(ddsHTSeq)#new filtered num genes in dataset and verifying num samples ddsHTSeq$condition <- factor(ddsHTSeq$condition, levels = treatments) #Looking at distr of filtered count data across samples librarySizes <- colSums(counts(ddsHTSeq)) barplot(librarySizes, names=names(librarySizes), las=2, ylim = c(0,1.6e+07), main="Barplot of library sizes") logcounts <- log2(counts(ddsHTSeq) + 1) head(logcounts) #Any difference between per gene counts for each of the sample groups? statusCol <- as.numeric(factor(ddsHTSeq$condition)) + 1 # make a colour vector boxplot(logcounts, xlab="", ylab="Log2(Counts)", las=2, col=statusCol) #Adding median log counts abline(h=median(as.matrix(logcounts)), col="blue") #Looking at PCA of the data - Do treatments cluster together? rlogcounts <- rlog(counts(ddsHTSeq))#transforming data to make it approximately homoskedastic, n < 30 so rlog is better select = order(rowMeans(rlogcounts), decreasing=TRUE)[1:12710] #This select variable is here because I modified the numbers of genes included in the PCA - from 500-12710. #The percent variation explained by each PC changes with the number of genes included, but not THAT much. #At lower numbers of genes, PhysStat can be predicted by PC1 better than PC2, but this changes as I increase to include more. #Because I couldn't decide on a sensible cutoff for the number of genes to include, I used the full dataset. highexprgenes_counts <- rlogcounts[select,] colnames(highexprgenes_counts)<- ddsHTSeq$condition data_for_PCA <- t(highexprgenes_counts) dim(data_for_PCA) #run PCA pcDat <- prcomp(data_for_PCA, center = T) #basic plot autoplot(pcDat) #plot for pub pdf("Fig2_PCA_Treatments.pdf",width=6,height=6,paper='special') autoplot(pcDat, data = ddsHTSeq$colData, colour=as.numeric(factor(ddsHTSeq$condition)), shape=FALSE, label.size=6, xlim = c(-0.4, 0.5)) + theme_bw() dev.off() #test of whether PCs can predict strain and physState Treats <- as.character(c("BG_grav", "BG_grav", "BG_grav", "BG_grav", "BG_par", "BG_par", "BG_par", "BG_par", "AG2", "AG2", "AG2", "AG2")) PC1 <- as.character(pcDat$x[,1]) PC2 <- as.character(pcDat$x[,2]) PC3 <- as.character(pcDat$x[,3]) Strain <- as.character(c("BG", "BG", "BG", "BG", "BG", "BG", "BG", "BG", "AG", "AG", "AG", "AG")) PhysStat <- as.character(c("grav", "grav", "grav", "grav", "hs", "hs", "hs", "hs", "hs", "hs", "hs", "hs")) dat_for_glm <- data.frame(cbind(Treats, Strain, PhysStat, PC1, PC2, PC3), row.names = NULL) summary(dat_for_glm) str(dat_for_glm) dat_for_glm$PC1 <- as.numeric(as.character(dat_for_glm$PC1)) dat_for_glm$PC2 <- as.numeric(as.character(dat_for_glm$PC2)) dat_for_glm$PC3 <- as.numeric(as.character(dat_for_glm$PC3)) #Are PCs 1,2,3 capable of separating samples by strain? Model_strain_PC1 <- bayesglm(Strain ~ PC1, data=dat_for_glm, family="binomial") summary(Model_strain_PC1) simulates <- coef(sim(Model_strain_PC1, n.sims = 10000)) head(simulates, 10) plot(density(simulates[,2]), main = "Model_strain_PC1", xlab = "Posterior.open", ylab = "Density") quantile(simulates[,2], c(0.025, 0.975))#gives the 95% credible intervals, which don't overlap with zero #This indicates that PC1 is capable of separating our samples by strain. Model_strain_PC2 <- bayesglm(Strain ~ PC2, data=dat_for_glm, family="binomial") summary(Model_strain_PC2) simulates <- coef(sim(Model_strain_PC2, n.sims = 10000)) head(simulates, 10) plot(density(simulates[,2]), main = "Model_strain_PC2", xlab = "Posterior.open", ylab = "Density") quantile(simulates[,2], c(0.025, 0.975))#PC2 - overlaps zero Model_strain_PC3 <- bayesglm(Strain ~ PC3, data=dat_for_glm, family="binomial") summary(Model_strain_PC3) simulates <- coef(sim(Model_strain_PC3, n.sims = 10000)) head(simulates, 10) plot(density(simulates[,2]), main = "Model_strain_PC3", xlab = "Posterior.open", ylab = "Density") quantile(simulates[,2], c(0.025, 0.975))#PC3 - overlaps zero #Are PCs 1,2,3 capable of separating samples by physState? Model_PhysStat_PC1 <- bayesglm(PhysStat ~ PC1, data=dat_for_glm, family="binomial") summary(Model_PhysStat_PC1) simulates <- coef(sim(Model_PhysStat_PC1, n.sims = 10000)) head(simulates, 10) plot(density(simulates[,2]), main = "Model_PhysStat_PC1", xlab = "Posterior.open", ylab = "Density") quantile(simulates[,2], c(0.025, 0.975))#PC1 & PhysStat - overlaps zero. Model_PhysStat_PC2 <- bayesglm(PhysStat ~ PC2, data=dat_for_glm, family="binomial") summary(Model_PhysStat_PC2) simulates <- coef(sim(Model_PhysStat_PC2, n.sims = 10000)) head(simulates, 10) plot(density(simulates[,2]), main = "Model_PhysStat_PC2", xlab = "Posterior.open", ylab = "Density") quantile(simulates[,2], c(0.025, 0.975))#PC2 & PhysStat - does not overlap zero Model_PhysStat_PC3 <- bayesglm(PhysStat ~ PC3, data=dat_for_glm, family="binomial") summary(Model_PhysStat_PC3) simulates <- coef(sim(Model_PhysStat_PC3, n.sims = 10000)) head(simulates, 10) plot(density(simulates[,2]), main = "Model_PhysStat_PC3", xlab = "Posterior.open", ylab = "Density") quantile(simulates[,2], c(0.025, 0.975))#PC3 & PhysStat - overlaps zero #Note that the PCA shows that BG_Parous4 is fairly different from the other BG parous treatments - should I drop it? See end of script for code to do this - in the end, I did not for the paper. ####Differential Expression Analysis ##First with all data dds<-DESeq(ddsHTSeq) res<-results(dds) resultsNames(dds) ###getting normalized filtered read counts dds <- estimateSizeFactors(dds) Norm_counts <- counts(dds, normalized=TRUE) cormat <- cor(Norm_counts, method = "spearman")#looking at correlation coefficients for gene expression values between treatments. #Function to Get upper triangle of the correlation matrix get_upper_tri <- function(cormat){ cormat[lower.tri(cormat)]<- NA return(cormat) } upper_tri <- get_upper_tri(cormat) # Melt the correlation matrix melted_cormat <- melt(upper_tri, na.rm = TRUE) # Create a ggheatmap ggheatmap <- ggplot(melted_cormat, aes(Var2, Var1, fill = value))+ geom_tile(color = "white")+ scale_fill_gradient2(low = "white", high = "red", mid = "pink", midpoint = 0.95, limit = c(0.90,1), space = "Lab", name="Spearman\nCorrelation") + theme_minimal()+ # minimal theme theme(axis.text.x = element_text(angle = 45, vjust = 1, size = 12, hjust = 1)) + xlab("") + ylab("")+ coord_fixed() # Print the heatmap print(ggheatmap) #write.csv(as.data.frame(Norm_counts), #file="Normalized_ReadCounts_AllTreats.csv") #Norm_Rownames <- data.frame(rownames(Norm_counts)) #Norm_Rownames$Descriptor <- "NA" #CALsOnly <- cbind(Norm_Rownames, (data.frame(Norm_counts[,c(1:8)]))) #write.table(as.data.frame(CALsOnly), #file="Normalized_ReadCounts_CALsOnly.txt", row.names = F, sep = "\t") #CalParVPip<- cbind(Norm_Rownames, (data.frame(Norm_counts[,c(-1,-2,-3,-4)]))) #write.table(as.data.frame(CalParVPip), #file="Normalized_ReadCounts_CalParVPip.txt", row.names = F, sep = "\t") ###Gravid F vs. Parous F--Use LFC for gene ranking and visualization, and use the p-values from the non-LFC resLFC <- lfcShrink(dds, contrast = c("condition", "CALgravidF", "CALparousF"), type="ashr") #Look at summary values summary(resLFC) #how many significantly DE genes? Looked at adjusted pvals of 0.1 and 0.05. Added a FC cutoff for shrunken FCs of 1.5x, as well. sum(resLFC$padj < 0.1 & abs(resLFC$log2FoldChange) > 0.58, na.rm=TRUE) sum(resLFC$padj < 0.05, na.rm=TRUE) sum(resLFC$padj < 0.05 & abs(resLFC$log2FoldChange) > 0.58, na.rm=TRUE) #getting numbers of up and down regulated genes upReg <- subset(resLFC, padj < 0.05 & log2FoldChange > 0.58)#LFC > 1.5 or upReg in gravid nrow(upReg) head(upReg) downReg <- subset(resLFC, padj < 0.05 & log2FoldChange < -0.58)#LFC < 1.5 or downReg in gravid nrow(downReg) head(downReg) #Create plots based on LFCshrunken dataset, which minimizes noise from low read counts pdf("plotMA_gravidVparous.pdf",width=6,height=6,paper='special') plotMA(resLFC, ylim=c(-3,3)) dev.off() #plotting differences in gene expression using lfcShrink output. pdf("EV_gravidVparous.pdf",width=8,height=6,paper='special') #gene names after selectLab are all diff exp genes EnhancedVolcano(resLFC, lab = rownames(resLFC), x = 'log2FoldChange', y = 'pvalue', #selectLab = c('CPIJ003142', 'CPIJ004468', 'CPIJ004690', 'CPIJ008018', 'CPIJ008747', 'CPIJ010041', 'CPIJ011084', 'CPIJ011244', #'CPIJ015908','CPIJ018848', 'CPIJ003456', 'CPIJ004365', 'CPIJ004417', 'CPIJ008256', 'CPIJ012990', 'CPIJ014981'), selectLab = NA, #drawConnectors = TRUE, xlim = c(-1.5, 1.5), ylim = c(0,30), pCutoff = 10e-6, FCcutoff = 0.58, pointSize = 2.0, labSize = 5.0) dev.off() #Looking at genes using the standard frequentist framework with a false discovery rate correction. res05 <- results(dds, alpha=0.05, contrast = c("condition", "CALgravidF", "CALparousF"))#results here are largely consistent with the shrunken LFC framework above without the LFC threshold argument. summary(res05) #note there are quite a few with "low" counts (mean count < 88), total significant = 556 compared with the 544 above. #non-LFC dataset filtering sum(res05$padj < 0.05 & abs(resLFC$log2FoldChange) > 0.58, na.rm=TRUE) # Note the small difference between LFC shrunken and "standard" analyses are normal - inconsistencies between them are typically minimal and have been described: https://support.bioconductor.org/p/110307/ #getting full gene lists with different LFCs and padj - from lfcShrink and results. Note that genes themselves are the same, what differ (mildly) are the statistics. full_genes_CalgravidF_CalparousF <- data.frame(c(paste(resLFC@rownames, sep = "", "-RA")), resLFC@listData$log2FoldChange, resLFC@listData$padj)#paste adds VB format to IDs write.table(full_genes_CalgravidF_CalparousF, file = "CALgravidF_v_CALparousF_AllGenes_LFCS.txt", col.names = F, row.names = F, sep = "\t") full_genes_CalgravidF_CalparousF <- data.frame(c(paste(res05@rownames, sep = "", "-RA")), res05@listData$log2FoldChange, res05@listData$padj)#paste adds VB format to IDs write.table(full_genes_CalgravidF_CalparousF, file = "CALgravidF_v_CALparousF_AllGenes_nonLFCS.txt", col.names = F, row.names = F, sep = "\t") #Saving a list of significant DE genes resSig <- subset(resLFC, padj < 0.05 & abs(log2FoldChange) > 0.58) write.table(data.frame(c(paste(resSig@rownames, sep = "", "-RA")), resSig@listData$log2FoldChange, resSig@listData$padj), file="CALgravidF_v_CALparousF_LFCS_padj05.txt", col.names = F, row.names = F, sep = "\t") resSig <- subset(res05, padj < 0.05 & abs(log2FoldChange) > 0.58) write.table(data.frame(c(paste(resSig@rownames, sep = "", "-RA")), resSig@listData$log2FoldChange, resSig@listData$padj), file="CALgravidF_v_CALparousF_nonLFCS_padj05.txt", col.names = F, row.names = F, sep = "\t") ###Parous F vs. pipiens #######Here looking at full dataset including the BG_parous4 outlier resLFC <- lfcShrink(dds, contrast = c("condition", "PipEvanF", "CALparousF"), type="ashr") #Look at summary values summary(resLFC) #how many significantly DE genes? The default p-value cutoff is 0.1 & adding a log2FoldChange cutoff (1.5), as well. sum(resLFC$padj < 0.1 & abs(resLFC$log2FoldChange) > 0.58, na.rm=TRUE) sum(resLFC$padj < 0.05, na.rm=TRUE) sum(resLFC$padj < 0.05 & abs(resLFC$log2FoldChange) > 0.58, na.rm=TRUE) upReg <- subset(resLFC, padj < 0.05 & log2FoldChange > 0.58)#LFC > 1.5 or upReg in Pip nrow(upReg) head(upReg) downReg <- subset(resLFC, padj < 0.05 & log2FoldChange < -0.58)#LFC < 1.5 or downReg in Pip nrow(downReg) head(downReg) #Create plots based on the LFC, which minimizes noise from low read counts pdf("plotMA_parousVpip.pdf",width=6,height=6,paper='special') plotMA(resLFC, ylim=c(-3,3)) dev.off() pdf("EV_parousVpip.pdf",width=8,height=6,paper='special') #gene labels commented out for selectLab are sig DE sensory genes. EnhancedVolcano(resLFC, lab = rownames(resLFC), x = 'log2FoldChange', y = 'pvalue', #selectLab = c("CPIJ001730", "CPIJ002108", "CPIJ002109", "CPIJ002111", "CPIJ004145","CPIJ007617", #"CPIJ009568", "CPIJ010367", "CPIJ010787", "CPIJ012716","CPIJ012717", "CPIJ012719", #"CPIJ013976", "CPIJ014525", "CPIJ016479","CPIJ016949", "CPIJ016966", "CPIJ019610", #"CPIJ016433", "CPIJ011564", "CPIJ014330","CPIJ002605", "CPIJ002618", "CPIJ002628", #"CPIJ007315", "CPIJ004067"), selectLab = NA, #drawConnectors = TRUE, xlim = c(-10, 10), ylim = c(0,200), pCutoff = 10e-6, FCcutoff = 0.58, pointSize = 2.0, labSize = 2.0) dev.off() #Looking at DGE from "standard" analysis. res05 <- results(dds, alpha=0.05, contrast = c("condition", "PipEvanF", "CALparousF")) summary(res05) sum(res05$padj < 0.05 & abs(resLFC$log2FoldChange) > 0.58, na.rm=TRUE) #getting full gene list full_genes_CalparousF_PipF <- data.frame(c(paste(resLFC@rownames, sep = "", "-RA")), resLFC@listData$log2FoldChange, resLFC@listData$padj)#paste adds VB format to IDs write.table(full_genes_CalparousF_PipF, file = "CALparousF_v_PipEvanF_AllGenes_LFCS.txt", col.names = F, row.names = F, sep = "\t") full_genes__CalparousF_PipF <- data.frame(c(paste(res05@rownames, sep = "", "-RA")), res05@listData$log2FoldChange, res05@listData$padj)#paste adds VB format to IDs write.table(full_genes_CalparousF_PipF, file = "CALparousF_v_PipEvanF_AllGenes_nonLFCS.txt", col.names = F, row.names = F, sep = "\t") #Save a list of significant DE genes with 1.5x change or greater resSig <- subset(resLFC, padj < 0.05 & abs(log2FoldChange) > 0.58) write.table(data.frame(c(paste(resSig@rownames, sep = "", "-RA")), resSig@listData$log2FoldChange, resSig@listData$padj), file="CALparousF_v_PipEvanF_LFCS_padj05.txt", row.names = F, col.names = F, sep = "\t") resSig <- subset(res05, padj < 0.05 & abs(log2FoldChange) > 0.58 ) write.table(data.frame(c(paste(resSig@rownames, sep = "", "-RA")), resSig@listData$log2FoldChange, resSig@listData$padj), file="CALparousF_v_PipEvanF_nonLFCS_padj05.txt", row.names = F, col.names = F, sep = "\t") #####This contrast is not that interesting, but looked at it anyway. Will be useful to verify those 16 genes that look important to suppressing host-seeking in BG gravid. ###Gravid F vs. pipiens resLFC <- lfcShrink(dds, contrast = c("condition", "PipEvanF", "CALgravidF"), type="ashr") #Look at summary values summary(resLFC) #how many significantly DE genes? The default p-value cutoff is 0.1. Added a log2foldchange cutoff of 1.5x, as well. sum(resLFC$padj < 0.1 & abs(resLFC$log2FoldChange) > 0.58, na.rm=TRUE) sum(resLFC$padj < 0.05, na.rm=TRUE) sum(resLFC$padj < 0.05 & abs(resLFC$log2FoldChange) > 0.58, na.rm=TRUE) upReg <- subset(resLFC, padj < 0.05 & log2FoldChange > 0.58)#LFC > 1.5 or upReg in Pip nrow(upReg) head(upReg) downReg <- subset(resLFC, padj < 0.05 & log2FoldChange < -0.58)#LFC < 1.5 or downReg in Pip nrow(downReg) head(downReg) #Create plots based on the LFC, which minimizes noise from low read counts pdf("plotMA_gravidVPipEvanF.pdf",width=6,height=6,paper='special') plotMA(resLFC, ylim=c(-3,3)) dev.off() pdf("EV_gravidVPipEvanF.pdf",width=8,height=6,paper='special') EnhancedVolcano(resLFC, lab = rownames(resLFC), x = 'log2FoldChange', y = 'pvalue', #selectLab = c('CPIJ003456'), selectLab = NA, xlim = c(-1.5, 1.5), ylim = c(0,30), pCutoff = 10e-6, FCcutoff = 0.58, pointSize = 2.0, labSize = 5.0) dev.off() #Standard analysis - non LFC data res05 <- results(dds, alpha=0.05, contrast = c("condition", "PipEvanF", "CALgravidF")) summary(res05) sum(res05$padj < 0.05 & abs(resLFC$log2FoldChange) > 0.58, na.rm=TRUE) #getting full gene list full_genes_CalgravidF_PipEvanF <- data.frame(c(paste(resLFC@rownames, sep = "", "-RA")), resLFC@listData$log2FoldChange, resLFC@listData$padj)#paste adds VB format to IDs write.table(full_genes_CalgravidF_PipEvanF, file = "CALgravidF_v_PipEvanF_AllGenes_LFCS.txt", col.names = F, row.names = F, sep = "\t") full_genes_CalgravidF_PipEvanF <- data.frame(c(paste(res05@rownames, sep = "", "-RA")), res05@listData$log2FoldChange, res05@listData$padj)#paste adds VB format to IDs write.table(full_genes_CalgravidF_PipEvanF, file = "CALgravidF_v_PipEvanF_AllGenes_nonLFCS.txt", col.names = F, row.names = F, sep = "\t") #Save a list of significant DE genes resSig <- subset(resLFC, padj < 0.05 & abs(log2FoldChange) > 0.58) write.table(data.frame(c(paste(resSig@rownames, sep = "", "-RA")), resSig@listData$log2FoldChange, resSig@listData$padj), file="CALgravidF_v_PipEvanF_LFCS_padj05.txt", row.names = F, col.names = F, sep = "\t") resSig <- subset(res05, padj < 0.05 & abs(log2FoldChange) > 0.58 ) write.table(data.frame(c(paste(resSig@rownames, sep = "", "-RA")), resSig@listData$log2FoldChange, resSig@listData$padj), file="CALGravidF_v_PipEvanF_nonLFCS_padj05.txt", row.names = F, col.names = F, sep = "\t") #VennDiag DEGs dat_1 <- read.table("CALgravidF_v_CALparousF_LFCS_padj05.txt", header = F) dat_2 <- read.table("CALparousF_v_PipEvanF_LFCS_padj05.txt", header = F) dat_3 <- read.table("CALgravidF_v_PipEvanF_LFCS_padj05.txt", header = F) l1 <- dat_1[, c(1,2)] l2 <- dat_2[, c(1,2)] l3 <- dat_3[, c(1,2)] VennDiag <- GOVenn(l1,l2,l3, label=c('BG1 gravid v parous','AG2 v BG1 parous','AG2 v BG1 gravid'), plot = F) print(VennDiag$plot) ######After looking at the first PCA, I wasn't sure about whether to drop BG_parous4. In the end, I did not because it did not greatly impact the numbers of differentially expressed genes I recovered. #Load in read counts and assign them sample labels outputPrefix<-("Culex_DEseq_dropped") sampleFiles<-c("M1-1_S1_htseq","M1-2_S2_htseq","M1-3_S3_htseq","M1-4_S4_htseq","M2-1_S5_htseq","M2-2_S6_htseq","M2-3_S7_htseq","M4-1_S13_htseq","M4-2_S14_htseq","M4-3_S15_htseq","M4-4_S16_htseq") sampleNames<-c("BG_Gravid1", "BG_Gravid2", "BG_Gravid3", "BG_Gravid4", "BG_Parous1", "BG_Parous2", "BG_Parous3", "AG1", "AG2", "AG3", "AG4") sampleCondition<-c("CALgravidF", "CALgravidF", "CALgravidF", "CALgravidF", "CALparousF", "CALparousF", "CALparousF", "PipEvanF", "PipEvanF", "PipEvanF", "PipEvanF") sampleTable<-data.frame(sampleName=sampleNames, fileName=sampleFiles, condition=sampleCondition) treatments<-c("CALgravidF", "CALparousF", "PipEvanF") #Create DESeq Data ddsHTSeq_dropped <- DESeqDataSetFromHTSeqCount(sampleTable = sampleTable, directory = hiQual_Ex, design= ~ condition) colData(ddsHTSeq_dropped)$condition <- factor(colData(ddsHTSeq_dropped)$condition, levels=treatments) dim(ddsHTSeq_dropped)#getting num genes in dataset and verifying num samples #Prefilter so only genes with atleast 10 reads in atleast 4 samples are considered. keep <- rowSums(counts(ddsHTSeq_dropped) >= 10) >= 4 ddsHTSeq_dropped <- ddsHTSeq_dropped[keep,] dim(ddsHTSeq_dropped)#new filtered num genes in dataset and verifying num samples ddsHTSeq_dropped$condition <- factor(ddsHTSeq_dropped$condition, levels = treatments) #new pca rlogcounts_dropped <- rlog(counts(ddsHTSeq_dropped)) #run PCA pcDat_dropped <- prcomp(t(rlogcounts_dropped)) #basic plot autoplot(pcDat_dropped) #plot for pub pdf("PCA_Treatments_dropped.pdf",width=6,height=6,paper='special') autoplot(pcDat_dropped, data = ddsHTSeq_dropped$colData, colour=as.numeric(factor(ddsHTSeq_dropped$condition)), shape=FALSE, label.size=6, xlim = c(-0.4, 0.5)) + theme_bw() dev.off() ####This is the DeSeq2 analysis BG_gravid v BG_parous without the BG_parous4 dds_dropped<-DESeq(ddsHTSeq_dropped) res_dropped<-results(dds_dropped) ###Gravid F vs. Parous F--Use LFC for gene ranking and visualization, and use the p-values from the non-LFC resLFC_dropped <- lfcShrink(dds_dropped, contrast = c("condition", "CALgravidF", "CALparousF"), type="ashr") #Look at summary values summary(resLFC_dropped) #how many significantly DE genes? The default p-value cutoff is 0.1 sum(resLFC_dropped$padj < 0.1 & abs(resLFC_dropped$log2FoldChange) > 0.58, na.rm=TRUE) sum(resLFC_dropped$padj < 0.05, na.rm=TRUE) sum(resLFC_dropped$padj < 0.05 & abs(resLFC_dropped$log2FoldChange) > 0.58, na.rm=TRUE) #Look at genes when changing the p-value cutoff--Use p-values from the non LFC data res05_dropped <- results(dds_dropped, alpha=0.05, contrast = c("condition", "CALgravidF", "CALparousF")) summary(res05_dropped) sum(res05_dropped$padj < 0.05 & abs(resLFC_dropped$log2FoldChange) > 0.58, na.rm=TRUE) #Create plots based on the LFC, which minimizes noise from low read counts pdf("plotMA_gravidVparous_dropped.pdf",width=6,height=6,paper='special') plotMA(resLFC_dropped, ylim=c(-3,3)) dev.off() #Save a list of significant DE genes resSig_dropped <- subset(res05_dropped, padj < 0.05 & abs(log2FoldChange) > 0.58) write.csv(as.data.frame(resSig_dropped), file="CALgravidF_v_CALparousF_dropped_nonLFCS_padj05.csv") resSig_dropped <- subset(resLFC_dropped, padj < 0.05 & abs(log2FoldChange) > 0.58) write.csv(as.data.frame(resSig_dropped), file="CALgravidF_v_CALparousF_dropped_LFCS_padj05.csv") pdf("EV_gravidVparous_dropped.pdf",width=8,height=6,paper='special') EnhancedVolcano(resLFC_dropped, lab = rownames(resLFC_dropped), x = 'log2FoldChange', y = 'pvalue', #selectLab = c('CPIJ003456'), selectLab = NA, xlim = c(-1.5, 1.5), ylim = c(0,30), pCutoff = 10e-6, FCcutoff = 0.58, pointSize = 2.0, labSize = 5.0) dev.off() ######Here rerunning DeSeq2 for Parous v pip without BG_parous 4 outlier resLFC_dropped <- lfcShrink(dds_dropped, contrast = c("condition", "PipEvanF", "CALparousF"), type="ashr") #Look at summary values summary(resLFC_dropped) #how many significantly DE genes? The default p-value cutoff is 0.1 sum(resLFC_dropped$padj < 0.1 & abs(resLFC_dropped$log2FoldChange) > 0.58, na.rm=TRUE) sum(resLFC_dropped$padj < 0.05, na.rm=TRUE) sum(resLFC_dropped$padj < 0.05 & abs(resLFC_dropped$log2FoldChange) > 0.58, na.rm=TRUE) #Look at genes when changing the p-value cutoff--Use p-values from the non LFC data res05_dropped <- results(dds_dropped, alpha=0.05, contrast = c("condition", "PipEvanF", "CALparousF")) summary(res05_dropped) sum(res05_dropped$padj < 0.05 & abs(resLFC_dropped$log2FoldChange) > 0.58, na.rm=TRUE) #Create plots based on the LFC, which minimizes noise from low read counts pdf("plotMA_parousVpip_dropped.pdf",width=6,height=6,paper='special') plotMA(resLFC_dropped, ylim=c(-3,3)) dev.off() pdf("EV_parousVpip_dropped.pdf",width=8,height=6,paper='special') EnhancedVolcano(resLFC_dropped, lab = rownames(resLFC_dropped), x = 'log2FoldChange', y = 'pvalue', #selectLab = c('CPIJ003456'), selectLab = NA, xlim = c(-10, 10), ylim = c(0,200), pCutoff = 10e-6, FCcutoff = 0.58, pointSize = 2.0, labSize = 5.0) dev.off() #Save a list of significant DE genes resSig_dropped <- subset(res05_dropped, padj < 0.05 & abs(log2FoldChange) > 0.58) write.csv(as.data.frame(resSig_dropped), file="CALparousF_v_PipEvanF_dropped_nonLFCS_padj05.csv") resSig_dropped <- subset(resLFC_dropped, padj < 0.05 & abs(log2FoldChange) > 0.58) write.csv(as.data.frame(resSig_dropped), file="CALparousF_v_PipEvanF_dropped_LFC_padj05.csv")
d2f9dbce06db49fb92872cf48dd598fad1a430f8
0a4dc06265e93a689dd43d0341395bb170957122
/R/vis_hom_time_series.R
1e835037d9e84073a8a6308202607778c7b5da22
[]
no_license
MariekeDirk/Dimming-Brightening
119f4feb9bda39079ad335de978370e2179c7367
2dd010c021cacda225f99fbcbaf3de5123306ca7
refs/heads/master
2020-09-13T22:09:42.833154
2020-03-16T08:57:48
2020-03-16T08:57:48
222,917,938
0
0
null
null
null
null
UTF-8
R
false
false
1,673
r
vis_hom_time_series.R
#'Visualize homogenized time series from Climatol #'@description plots the homogenized time series with the interactive plotly library. #'@param id staid of the station #'@param brks break points from climatol #'@param h_series homogenized time series #'@param o_series original series from ECAD #'@export plot_hom_series<-function(id,brks=break_points,h_series=hom_series,o_series=series_comb){ var<-paste0("sta_id",id) #break points for this station I<-which(brks$Code==var) if(length(I)==0){ message(paste0("No break points in this series, try for example ", tail(gsub("sta_id","",unique(break_points$Code)),n=1))) return(FALSE) } time_series<-h_series[,1]; names(time_series) <- "time" time_series$time<-as.Date(time_series$time) original_series<-data.frame(o_series[which(o_series$STAID==id),]$month_year, o_series[which(o_series$STAID==id),]$QQm ) names(original_series) <- c("time","original") homogenized_series<-h_series[[var]]; names(homogenized_series) <- "homogenized" homogenized_series <- data.frame(time_series,homogenized_series) df<-full_join(original_series,homogenized_series,by="time") df_long<-tidyr::gather(df,"series","measurement",-time) df_long$series<-as.factor(df_long$series) #plotting routine p<- ggplot2::ggplot(df_long,aes(time,measurement,color=series)) + ggplot2::geom_line() + ggplot2::scale_color_manual(values = c("red", "darkgrey")) if(length(I)!=0){ p <- p + ggplot2::geom_vline(xintercept = break_points$Date[I],colour="red",linetype=2) }else{message("no breaks found")} plotly::ggplotly(p,dynamicTicks = TRUE) }
5887490e37583fc176dff5688731393595d12dc7
2a7e77565c33e6b5d92ce6702b4a5fd96f80d7d0
/fuzzedpackages/gasper/man/laplacian_mat.Rd
db1d8191194d8ed7105ef90736d3fd741d987780
[]
no_license
akhikolla/testpackages
62ccaeed866e2194652b65e7360987b3b20df7e7
01259c3543febc89955ea5b79f3a08d3afe57e95
refs/heads/master
2023-02-18T03:50:28.288006
2021-01-18T13:23:32
2021-01-18T13:23:32
329,981,898
7
1
null
null
null
null
UTF-8
R
false
true
318
rd
laplacian_mat.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/laplacian_mat.R \name{laplacian_mat} \alias{laplacian_mat} \title{Laplacian matrix.} \usage{ laplacian_mat(W) } \arguments{ \item{W}{Adjacency matrix.} } \description{ Compute the (unormalized) laplacian matrix from the adjacency matrix. }
38d812b4586dd42d6fbcdc51646ec4628062cdfe
0f0246cb0dc295f6bb01b70ff4a0182f08e82922
/R/FitIndices.R
31b2c7cf752c497293a95331f11f316f9fe1c44a
[]
no_license
Kucharssim/LCAapp
4c0ee6d7a14c4ce634ff2e91a359906e8e605aad
69c5318c2f1c14f043a5d71c2f5ba035b98d84b5
refs/heads/master
2021-06-13T07:23:46.958035
2021-05-24T10:42:50
2021-05-24T10:42:50
91,227,492
3
2
null
2021-05-24T10:42:51
2017-05-14T07:36:09
R
UTF-8
R
false
false
3,580
r
FitIndices.R
nParamsDf <- function(k, tab.d){ # compute the number of estimated parameters # and degrees of freedom # # Args: # k: number of classes in the model # tab.d: the dummy data # # Returns a vector of df and n of parameters lev <- Levels(tab.d) # vector of levels n.params <- (k-1) + k*sum(lev-1) # number of parameters df <- prod(lev) - 1 - n.params # df return(c(df, n.params)) } chigSq <- function(d, theta, pi){ # Compute Chi^2 and G^2 # # Args: # d: dummy data # theta: the conditional probabilities # pi: class sizes # # Returns: vector of Ch^2 and G^2 n <- nrow(d) observed <- table(d) expected <- Expected(pi, theta, n) chi <- sum(((observed-expected)^2)/expected) g <- 2 * sum(observed*log(observed/expected), na.rm=TRUE) return(c(chi, g)) } Expected <- function(pi, theta, n=NA){ # Compute the expected counts # # Args: # pi: the class sizes # theta: the conditional probabilities # n: sample size # # Returns a table with expected counts # Loop over classes tab <- lapply(1:length(pi), function(class) { # Get the probabilities of responses given current class probs <- lapply(theta, function(x){ t(t(x[class,])) }) # Compute cross-product of the first two items p.table <- (probs[[1]] %*% t(probs[[2]])) # If there are more items, add dimensions if(length(probs)>2){ for(i in 3:length(probs)){ # Compute the outer products p.table <- drop( p.table %o% probs[[i]] ) } } # Multiply the resulting probabilty table by sample size to get counts return(p.table * n * pi[class]) }) # Sum the expected counts over all classes and return return(Reduce("+", tab)) } aicbic <- function(llik, n.params, n){ # Compute AIC and BIC # # Args: # llik: log-likelihood # n.params: number of parameters # n: sample size # # Returns: AIC and BIC aic <- -2*llik + 2*n.params bic <- -2*llik + log(n)*n.params c(aic, bic) } entropy <- function(p){ # Compute the Entropy of class separation (Muthen & Muthen, 2006) # # Args: # p: probabtilities oa class membership # # Returns: entropy of class separation (bounded at <0,1>) k <- ncol(p) if(k<=1){ warning("Cannot compute entropy for 1 class model") return(1) } n <- nrow(p) log.p <- log(p) log.p[log.p==-Inf] <- 0 ent <- sum(p * log.p) ent <- 1 + (ent/(n*log(k))) # Output return(ent) } fitMeasures <- function(d, rawd, model){ # Wrapper for the fit functions # # Args: # d: dummy data # rawd: raw data # model: the output of the emLCA # # Output: n of classes, chi^2, G^2, df, n of parameters, # AIC, BIC, Entropy classes <- model$classes df.n.params <- nParamsDf(classes, d) chi.g <- chigSq(rawd, model$theta, model$pi) aicbic <- aicbic(model$llik, df.n.params[2], nrow(model$posterior)) entropy <- entropy(model$posterior) c(classes, round(chi.g, 2), df.n.params, round(c(aicbic, entropy), 2)) } multiFitMeasures <- function(d, rawd, models){ # Compute the fitmeasures for multiple models # # Args: # d: dummy data # rawd: raw data # models: the optimal models # # Returns a table with the fit measures per model tab <- sapply(models, function(model){ fitMeasures(d, rawd, model) }) tab <- t(tab) colnames(tab) <- c("classes","Chi Square", "G Square", "df", "n of params", "AIC", "BIC", "Entropy") return(tab) }
d39361f19fe6a1dde1aabd345aec07d8e1c74f22
2c1ab15c29ec9db51a129292a7d52e6a518f551d
/man/predict.ranktree.Rd
8eb0b679006e4317cb621b735bba743fa4086c4f
[]
no_license
cran/ConsRankClass
cc65611f9a25f821d9233af298d032d80963038f
33f18bd53c9446c0b020042ff957798c93d1c138
refs/heads/master
2023-08-14T16:56:42.821373
2021-09-28T09:10:02
2021-09-28T09:10:02
368,585,748
0
0
null
null
null
null
UTF-8
R
false
true
1,519
rd
predict.ranktree.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/predict.ranktree.R \name{predict.ranktree} \alias{predict.ranktree} \title{Predict the median rankings for new observations} \usage{ \method{predict}{ranktree}(object, newx, ...) } \arguments{ \item{object}{An object of the class "ranktree"} \item{newx}{A dataframe of the same nature of the predictor dataframe with which the tree has been built} \item{\dots}{System reserved (No specific usage)} } \value{ A list containing: \tabular{lll}{ rankings \tab \tab the fit in terms of rankings\cr orderings \tab \tab the fit in terms of orderings\cr info\tab \tab dataframe containing the terminal nodes in which the new x fall down, then the new x and the fit (in terms of rankings) } } \description{ Predict the median rankings in a tree-based structure built with \code{ranktree} for new observations } \examples{ \donttest{ data(EVS) EVS$rankings[is.na(EVS$rankings)] <- 3 set.seed(654) training=sample(1911,1434) tree <- ranktree(EVS$rankings[training,],EVS$predictors[training,],decrmin=0.001,num=50) #use the function predict ro predict rankings for new predictors rankfit <- predict(tree,newx=EVS$predictors[-training,]) #fit in terms of rankings rankfit$rankings #fit in terms of orderings rankfit$orderings # information about the fit (terminal node, predictor and fit (in terms of rankings)) rankfit$info } } \seealso{ \code{\link{ranktree}} \code{\link{validatetree}} } \author{ Antonio D'Ambrosio \email{antdambr@unina.it} }
bb21bd0079565daed475d071fa787f17aea179ef
667cd59f9059f566b5c4ac2c76b1b8b6f09f50d5
/ma415project2R.R
6e0ead74f1bcfabe9a00c152fc28da827968a768
[]
no_license
carlyrosewilling/MA415Proj2
99f1161bff22a223cd63948d78b95a3fe99eb8ca
531bb5ed59378b587d365e7b18b0cc8f3c498c4b
refs/heads/master
2021-05-07T13:56:07.343239
2020-12-21T23:25:48
2020-12-21T23:25:48
109,762,378
0
0
null
null
null
null
UTF-8
R
false
false
27,164
r
ma415project2R.R
# Setting up some libraries we'll need options(java.parameters = "- Xmx1024m") library(tidyverse) library(stringr) library(lubridate) library(xlsx) library(gridExtra) # For Cape May # These sections of code will repeat for each location, so I'm only commenting once # First we set up the urls of the buoy data tables from the NDBC website str1 <- "http://www.ndbc.noaa.gov/view_text_file.php?filename=44009h" str2 <- ".txt.gz&dir=data/historical/stdmet/" years <- c(1984:2016) urls <- str_c(str1, years, str2, sep = "") # Now that we havve urls, let's say what the filenames for each year will be filenames <- str_c("cm", years, sep = "") # And how many we have N <- length(urls) for (i in 1:N){ # For each year of our data, get the table from that url and call it "file" assign(filenames[i], read_table(urls[i], col_names = TRUE)) file <- get(filenames[i]) # Before 1998 the year column is only 2 digits, YY, so let's get those to all match colnames(file)[1] <-"YYYY" # If the first year entry is 2 digits, put 19 in front of it if(nchar(file[1,1]) == 2 & file[1,1] > 50 ) { file[1] <- lapply(file[1], function(x){str_c(19, x, sep = "")}) } # Since we turned it into a string by doing that, let's get it back to a number file$YYYY <- as.numeric(file$YYYY) # And then make sure everything else is numbers file$MM <- as.numeric(file$MM) file$DD <- as.numeric(file$DD) file$hh <- as.numeric(file$hh) file$ATMP <- as.numeric(file$ATMP) file$WTMP <- as.numeric(file$WTMP) # Early years didn't have a minutes column # For those with minutes, we want to add it in with an entry at zero # Otherwise, we only want 0 minutes if possible # But some years have entries at 50 minutes instead if(is.element("mm", colnames(file))) { file$mm <- as.numeric(file$mm) file <- file %>% filter(mm == 00 | mm == 50) } else { file$mm <- 00 } # Pulling out just the columns we care about, then making the date column file <- file %>% select(YYYY, MM, DD, hh, mm, ATMP, WTMP) file$date <- make_datetime(year = file$YYYY, month = file$MM, day = file$DD, hour = file$hh, min = file$mm) # Putting our temporary 'file' into the main dataframe for this location if(i == 1){ CM <- file } else{ CM <- rbind.data.frame(CM, file) } } # Now we have a few other actions to perform # We filter out so we have just one entry for each day, the closest to noon CM <- filter(CM, hh == 12 & mm == 00 | hh == 11 & mm == 50) # Then make the time difference column CM$timediff <- make_datetime(hour = CM$hh, min = CM$mm) - make_datetime(hour = 12, min = 00) # Then we'll filter down to the columns we really want, recode the NAs, # and rename the columns CM <- select(CM, date, timediff, ATMP, WTMP) CM$ATMP <- apply(CM[,3], MARGIN = 2, function(x){ifelse(x == 999.0, NA, x)}) CM$ATMP <- apply(CM[,3], MARGIN = 2, function(x){ifelse(x == 99.0, NA, x)}) CM$WTMP <- apply(CM[,4], MARGIN = 2, function(x){ifelse(x == 999.0, NA, x)}) CM$WTMP <- apply(CM[,4], MARGIN = 2, function(x){ifelse(x == 99.0, NA, x)}) colnames(CM)[3] <- "air_temp" colnames(CM)[4] <- "sea_temp" colnames(CM)[1] <- "date_time" colnames(CM)[2] <- "time_diff" # There are a few more columns to put in CM$team_num <- 1 CM$reading_type <- "buoy" CM$Lat <- 38.5 CM$Lon <- 74.7 # And then reordering the columns CM <- CM[c("team_num", "reading_type", "date_time", "time_diff", "Lat", "Lon", "sea_temp", "air_temp")] # Then we do it all again for the next location # Molasses Reef str1 <- "http://www.ndbc.noaa.gov/view_text_file.php?filename=mlrf1h" str2 <- ".txt.gz&dir=data/historical/stdmet/" years <- c(1987:2016) urls <- str_c(str1, years, str2, sep = "") filenames <- str_c("mr", years, sep = "") N <- length(urls) for (i in 1:N){ assign(filenames[i], read_table(urls[i], col_names = TRUE)) file <- get(filenames[i]) colnames(file)[1] <-"YYYY" if(nchar(file[1,1]) == 2 & file[1,1] > 50 ) { file[1] <- lapply(file[1], function(x){str_c(19, x, sep = "")}) } file$YYYY <- as.numeric(file$YYYY) file$MM <- as.numeric(file$MM) file$DD <- as.numeric(file$DD) file$hh <- as.numeric(file$hh) file$ATMP <- as.numeric(file$ATMP) file$WTMP <- as.numeric(file$WTMP) if(is.element("mm", colnames(file))) { file$mm <- as.numeric(file$mm) file <- file %>% filter(mm == 00 | mm == 50) } else { file$mm <- 00 } file <- file %>% select(YYYY, MM, DD, hh, mm, ATMP, WTMP) file$date <- make_datetime(year = file$YYYY, month = file$MM, day = file$DD, hour = file$hh, min = file$mm) if(i == 1){ MR <- file } else{ MR <- rbind.data.frame(MR, file) } } MR<-filter(MR, hh==12 & mm == 00 | hh == 11 & mm == 50) MR$timediff <- make_datetime(hour = MR$hh, min = MR$mm) - make_datetime(hour = 12, min = 00) MR<-select(MR, date, timediff, ATMP, WTMP) MR$ATMP <- apply(MR[,3], MARGIN = 2, function(x){ifelse(x == 999.0, NA, x)}) MR$ATMP <- apply(MR[,3], MARGIN = 2, function(x){ifelse(x == 99.0, NA, x)}) MR$WTMP <- apply(MR[,4], MARGIN = 2, function(x){ifelse(x == 999.0, NA, x)}) MR$WTMP <- apply(MR[,4], MARGIN = 2, function(x){ifelse(x == 99.0, NA, x)}) colnames(MR)[3] <- "air_temp" colnames(MR)[4] <- "sea_temp" colnames(MR)[1] <- "date_time" colnames(MR)[2] <- "time_diff" MR$team_num <- 1 MR$reading_type <- "buoy" MR$Lat <- 25.0 MR$Lon <- 80.4 MR <- MR[c("team_num", "reading_type", "date_time", "time_diff", "Lat", "Lon", "sea_temp", "air_temp")] # Georges Bank str1 <- "http://www.ndbc.noaa.gov/view_text_file.php?filename=44011h" str2 <- ".txt.gz&dir=data/historical/stdmet/" years <- c(1984:2013, 2015, 2016) urls <- str_c(str1, years, str2, sep = "") filenames <- str_c("gb", years, sep = "") N <- length(urls) for (i in 1:N){ assign(filenames[i], read_table(urls[i], col_names = TRUE)) file <- get(filenames[i]) colnames(file)[1] <-"YYYY" if(nchar(file[1,1]) == 2 & file[1,1] > 50 ) { file[1] <- lapply(file[1], function(x){str_c(19, x, sep = "")}) } file$YYYY <- as.numeric(file$YYYY) file$MM <- as.numeric(file$MM) file$DD <- as.numeric(file$DD) file$hh <- as.numeric(file$hh) file$ATMP <- as.numeric(file$ATMP) file$WTMP <- as.numeric(file$WTMP) if(is.element("mm", colnames(file))) { file$mm <- as.numeric(file$mm) file <- file %>% filter(mm == 00 | mm == 50) } else { file$mm <- 00 } file <- file %>% select(YYYY, MM, DD, hh, mm, ATMP, WTMP) file$date <- make_datetime(year = file$YYYY, month = file$MM, day = file$DD, hour = file$hh, min = file$mm) if(i == 1){ GB <- file } else{ GB <- rbind.data.frame(GB, file) } } GB<-filter(GB, hh==12 & mm == 00 | hh == 11 & mm == 50) GB$timediff <- make_datetime(hour = GB$hh, min = GB$mm) - make_datetime(hour = 12, min = 00) GB <- select(GB, date, timediff, ATMP, WTMP) GB$ATMP <- apply(GB[,3], MARGIN = 2, function(x){ifelse(x == 999.0, NA, x)}) GB$ATMP <- apply(GB[,3], MARGIN = 2, function(x){ifelse(x == 99.0, NA, x)}) GB$WTMP <- apply(GB[,4], MARGIN = 2, function(x){ifelse(x == 999.0, NA, x)}) GB$WTMP <- apply(GB[,4], MARGIN = 2, function(x){ifelse(x == 99.0, NA, x)}) colnames(GB)[3] <- "air_temp" colnames(GB)[4] <- "sea_temp" colnames(GB)[1] <- "date_time" colnames(GB)[2] <- "time_diff" GB$team_num <- 1 GB$reading_type <- "buoy" GB$Lat <- 41.1 GB$Lon <- 66.6 GB <- GB[c("team_num", "reading_type", "date_time", "time_diff", "Lat", "Lon", "sea_temp", "air_temp")] # Mid-Gulf str1 <- "http://www.ndbc.noaa.gov/view_text_file.php?filename=42001h" str2 <- ".txt.gz&dir=data/historical/stdmet/" years <- c(1984:2016) urls <- str_c(str1, years, str2, sep = "") filenames <- str_c("mg", years, sep = "") N <- length(urls) for (i in 1:N){ assign(filenames[i], read_table(urls[i], col_names = TRUE)) file <- get(filenames[i]) colnames(file)[1] <-"YYYY" if(nchar(file[1,1]) == 2 & file[1,1] > 50 ) { file[1] <- lapply(file[1], function(x){str_c(19, x, sep = "")}) } file$YYYY <- as.numeric(file$YYYY) file$MM <- as.numeric(file$MM) file$DD <- as.numeric(file$DD) file$hh <- as.numeric(file$hh) file$ATMP <- as.numeric(file$ATMP) file$WTMP <- as.numeric(file$WTMP) if(is.element("mm", colnames(file))) { file$mm <- as.numeric(file$mm) file <- file %>% filter(mm == 00 | mm == 50) } else { file$mm <- 00 } file <- file %>% select(YYYY, MM, DD, hh, mm, ATMP, WTMP) file$date <- make_datetime(year = file$YYYY, month = file$MM, day = file$DD, hour = file$hh, min = file$mm) if(i == 1){ MG <- file } else{ MG <- rbind.data.frame(MG, file) } } MG <- filter(MG, hh == 12 & mm == 00 | hh == 11 & mm == 50) MG$timediff <- make_datetime(hour = MG$hh, min = MG$mm) - make_datetime(hour = 12, min = 00) MG <- select(MG, date, timediff, ATMP, WTMP) MG$ATMP <- apply(MG[,3], MARGIN = 2, function(x){ifelse(x == 999.0, NA, x)}) MG$ATMP <- apply(MG[,3], MARGIN = 2, function(x){ifelse(x == 99.0, NA, x)}) MG$WTMP <- apply(MG[,4], MARGIN = 2, function(x){ifelse(x == 999.0, NA, x)}) MG$WTMP <- apply(MG[,4], MARGIN = 2, function(x){ifelse(x == 99.0, NA, x)}) colnames(MG)[3] <- "air_temp" colnames(MG)[4] <- "sea_temp" colnames(MG)[1] <- "date_time" colnames(MG)[2] <- "time_diff" MG$team_num <- 1 MG$reading_type <- "buoy" MG$Lat <- 25.9 MG$Lon <- 89.7 MG <- MG[c("team_num", "reading_type", "date_time", "time_diff", "Lat", "Lon", "sea_temp", "air_temp")] # Finally, we need to put these dataframes into an xlsx file write.xlsx2(CM, "group1data.xlsx", sheetName = "Cape May - Buoy # 44009") write.xlsx2(MR, "group1data.xlsx", sheetName = "Molasses Reef - Buoy # MLRF1", append = TRUE) write.xlsx2(GB, "group1data.xlsx", sheetName = "Georges Bank - Buoy # 44011", append = TRUE) write.xlsx2(MG, "group1data.xlsx", sheetName = "Mid Gulf - Buoy # 42001", append = TRUE) # Seasonal Data Visualization # First we want to create a new dataframe that has separate month columns for each buoy CM.seasons <- mutate(CM, month = month(CM$date_time)) MR.seasons <- mutate(MR, month = month(MR$date_time)) GB.seasons <- mutate(GB, month = month(GB$date_time)) MG.seasons <- mutate(MG, month = month(MG$date_time)) # Next we want to create separate data frames for each season # We approximated each season to 3 months: # Winter = January, February, and March # Spring = April, May, and June # Summer = July, August, and September # Fall = October, November, and December CM.winter <- filter(CM.seasons, month == 1 | month == 2 | month == 3) CM.spring <- filter(CM.seasons, month == 4 | month == 5 | month == 6) CM.summer <- filter(CM.seasons, month == 7 | month == 8 | month == 9) CM.fall <- filter(CM.seasons, month == 10 | month == 11 | month == 12) MR.winter <- filter(MR.seasons, month == 1 | month == 2 | month == 3) MR.spring <- filter(MR.seasons, month == 4 | month == 5 | month == 6) MR.summer <- filter(MR.seasons, month == 7 | month == 8 | month == 9) MR.fall <- filter(MR.seasons, month == 10 | month == 11 | month == 12) GB.winter <- filter(GB.seasons, month == 1 | month == 2 | month == 3) GB.spring <- filter(GB.seasons, month == 4 | month == 5 | month == 6) GB.summer <- filter(GB.seasons, month == 7 | month == 8 | month == 9) GB.fall <- filter(GB.seasons, month == 10 | month == 11 | month == 12) MG.winter <- filter(MG.seasons, month == 1 | month == 2 | month == 3) MG.spring <- filter(MG.seasons, month == 4 | month == 5 | month == 6) MG.summer <- filter(MG.seasons, month == 7 | month == 8 | month == 9) MG.fall <- filter(MG.seasons, month == 10 | month == 11 | month == 12) # Then, I want to assign plots of each season for each buoy to names winter.CM <- ggplot() + geom_point(data = CM.winter, aes(y = air_temp, x = date_time), color = "darkslategray4") + geom_smooth(data = CM.winter, aes(y = air_temp, x = date_time), color = "darkslategray", method = "lm", se = FALSE) + labs(x = "Year", y = "Air Temperature (°C)", title = "Year vs. Air Temperature, Winter Months in Cape May") spring.CM <- ggplot() + geom_point(data = CM.spring, aes(y = air_temp, x = date_time), color = "darkorchid1") + geom_smooth(data = CM.spring, aes(y = air_temp, x = date_time), color = "darkorchid4", method = "lm", se = FALSE) + labs(x = "Year", y = "Air Temperature (°C)", title = "Year vs. Air Temperature, Spring Months in Cape May") summer.CM <- ggplot() + geom_point(data = CM.summer, aes(y = air_temp, x = date_time), color = "goldenrod1") + geom_smooth(data = CM.summer, aes(y = air_temp, x = date_time), color = "goldenrod4", method = "lm", se = FALSE) + labs(x = "Year", y = "Air Temperature (°C)", title = "Year vs. Air Temperature, Summer Months in Cape May") fall.CM <- ggplot() + geom_point(data = CM.fall, aes(y = air_temp, x = date_time), color = "darkorange2") + geom_smooth(data = CM.fall, aes(y = air_temp, x = date_time), color = "darkorange4", method = "lm", se = FALSE) + labs(x = "Year", y = "Air Temperature (°C)", title = "Year vs. Air Temperature, Fall Months in Cape May") winter.MR <- ggplot() + geom_point(data = MR.winter, aes(y = air_temp, x = date_time), color = "darkslategray4") + geom_smooth(data = MR.winter, aes(y = air_temp, x = date_time), color = "darkslategray", method = "lm", se = FALSE) + labs(x = "Year", y = "Air Temperature (°C)", title = "Year vs. Air Temperature, Winter Months in Molasses Reef") spring.MR <- ggplot() + geom_point(data = MR.spring, aes(y = air_temp, x = date_time), color = "darkorchid1") + geom_smooth(data = MR.spring, aes(y = air_temp, x = date_time), color = "darkorchid4", method = "lm", se = FALSE) + labs(x = "Year", y = "Air Temperature (°C)", title = "Year vs. Air Temperature, Spring Months in Molasses Reef") summer.MR <- ggplot() + geom_point(data = MR.summer, aes(y = air_temp, x = date_time), color = "goldenrod1") + geom_smooth(data = MR.summer, aes(y = air_temp, x = date_time), color = "goldenrod4", method = "lm", se = FALSE) + labs(x = "Year", y = "Air Temperature (°C)", title = "Year vs. Air Temperature, Summer Months in Molasses Reef") fall.MR <- ggplot() + geom_point(data = MR.fall, aes(y = air_temp, x = date_time), color = "darkorange2") + geom_smooth(data = MR.fall, aes(y = air_temp, x = date_time), color = "darkorange4", method = "lm", se = FALSE) + labs(x = "Year", y = "Air Temperature (°C)", title = "Year vs. Air Temperature, Fall Months in Molasses Reef") winter.GB <- ggplot() + geom_point(data = GB.winter, aes(y = air_temp, x = date_time), color = "darkslategray4") + geom_smooth(data = GB.winter, aes(y = air_temp, x = date_time), color = "darkslategray", method = "lm", se = FALSE) + labs(x = "Year", y = "Air Temperature (°C)", title = "Year vs. Air Temperature, Winter Months in Georges Bank") spring.GB <- ggplot() + geom_point(data = GB.spring, aes(y = air_temp, x = date_time), color = "darkorchid1") + geom_smooth(data = GB.spring, aes(y = air_temp, x = date_time), color = "darkorchid4", method = "lm", se = FALSE) + labs(x = "Year", y = "Air Temperature (°C)", title = "Year vs. Air Temperature, Spring Months in Georges Bank") summer.GB <- ggplot() + geom_point(data = GB.summer, aes(y = air_temp, x = date_time), color = "goldenrod1") + geom_smooth(data = GB.summer, aes(y = air_temp, x = date_time), color = "goldenrod4", method = "lm", se = FALSE) + labs(x = "Year", y = "Air Temperature (°C)", title = "Year vs. Air Temperature, Summer Months in Georges Bank") fall.GB <- ggplot() + geom_point(data = GB.fall, aes(y = air_temp, x = date_time), color = "darkorange2") + geom_smooth(data = GB.fall, aes(y = air_temp, x = date_time), color = "darkorange4", method = "lm", se = FALSE) + labs(x = "Year", y = "Air Temperature (°C)", title = "Year vs. Air Temperature, Fall Months in Georges Bank") winter.MG <- ggplot() + geom_point(data = MG.winter, aes(y = air_temp, x = date_time), color = "darkslategray4") + geom_smooth(data = MG.winter, aes(y = air_temp, x = date_time), color = "darkslategray", method = "lm", se = FALSE) + labs(x = "Year", y = "Air Temperature (°C)", title = "Year vs. Air Temperature, Winter Months in Mid Gulf") spring.MG <- ggplot() + geom_point(data = MG.spring, aes(y = air_temp, x = date_time), color = "darkorchid1") + geom_smooth(data = MG.spring, aes(y = air_temp, x = date_time), color = "darkorchid4", method = "lm", se = FALSE) + labs(x = "Year", y = "Air Temperature (°C)", title = "Year vs. Air Temperature, Spring Months in Mid Gulf") summer.MG <- ggplot() + geom_point(data = MG.summer, aes(y = air_temp, x = date_time), color = "goldenrod1") + geom_smooth(data = MG.summer, aes(y = air_temp, x = date_time), color = "goldenrod4", method = "lm", se = FALSE) + labs(x = "Year", y = "Air Temperature (°C)", title = "Year vs. Air Temperature, Summer Months in Mid Gulf") fall.MG <- ggplot() + geom_point(data = MG.fall, aes(y = air_temp, x = date_time), color = "darkorange2") + geom_smooth(data = MG.fall, aes(y = air_temp, x = date_time), color = "darkorange4", method = "lm", se = FALSE) + labs(x = "Year", y = "Air Temperature (°C)", title = "Year vs. Air Temperature, Fall Months in Mid Gulf") # Finally, we want to arrange each plot so that they appear side by side for each buoy, # with appropriate titles and labels grid.arrange(winter.CM, spring.CM, summer.CM, fall.CM, ncol=2) grid.arrange(winter.MR, spring.MR, summer.MR, fall.MR, ncol=2) grid.arrange(winter.GB, spring.GB, summer.GB, fall.GB, ncol=2) grid.arrange(winter.MG, spring.MG, summer.MG, fall.MG, ncol=2) # I also calculated the corellation coefficients for each season over time # against the air temperature for each buoy # Making sure dates are numerics CM.winter$date_time <- as.numeric(CM.winter$date_time) CM.spring$date_time <- as.numeric(CM.spring$date_time) CM.summer$date_time <- as.numeric(CM.summer$date_time) CM.fall$date_time <- as.numeric(CM.fall$date_time) # Inserting into the correlation function cor(CM.winter$air_temp, CM.winter$date_time, use = "complete.obs") cor(CM.spring$air_temp, CM.spring$date_time, use = "complete.obs") cor(CM.summer$air_temp, CM.summer$date_time, use = "complete.obs") cor(CM.fall$air_temp, CM.fall$date_time, use = "complete.obs") MR.winter$date_time <- as.numeric(MR.winter$date_time) MR.spring$date_time <- as.numeric(MR.spring$date_time) MR.summer$date_time <- as.numeric(MR.summer$date_time) MR.fall$date_time <- as.numeric(MR.fall$date_time) cor(MR.winter$air_temp, MR.winter$date_time, use = "complete.obs") cor(MR.spring$air_temp, MR.spring$date_time, use = "complete.obs") cor(MR.summer$air_temp, MR.summer$date_time, use = "complete.obs") cor(MR.fall$air_temp, MR.fall$date_time, use = "complete.obs") GB.winter$date_time <- as.numeric(GB.winter$date_time) GB.spring$date_time <- as.numeric(GB.spring$date_time) GB.summer$date_time <- as.numeric(GB.summer$date_time) GB.fall$date_time <- as.numeric(GB.fall$date_time) cor(GB.winter$air_temp, GB.winter$date_time, use = "complete.obs") cor(GB.spring$air_temp, GB.spring$date_time, use = "complete.obs") cor(GB.summer$air_temp, GB.summer$date_time, use = "complete.obs") cor(GB.fall$air_temp, GB.fall$date_time, use = "complete.obs") MG.winter$date_time <- as.numeric(MG.winter$date_time) MG.spring$date_time <- as.numeric(MG.spring$date_time) MG.summer$date_time <- as.numeric(MG.summer$date_time) MG.fall$date_time <- as.numeric(MG.fall$date_time) cor(MG.winter$air_temp, MG.winter$date_time, use = "complete.obs") cor(MG.spring$air_temp, MG.spring$date_time, use = "complete.obs") cor(MG.summer$air_temp, MG.summer$date_time, use = "complete.obs") cor(MG.fall$air_temp, MG.fall$date_time, use = "complete.obs") # Data Visuals for Air Temp and Sea Temp Correlation # CM Air and Sea CM.AirSea <- ggplot(data = CM) + geom_point(mapping = aes(x = sea_temp, y = air_temp), color="lightblue") + labs(title="Cape May Air Temperature vs. Sea Temperature", x="Sea Temperature (°C)", y="Air Temperature (°C)") # MR Air and Sea MR.AirSea <- ggplot(data = MR) + geom_point(mapping = aes(x = sea_temp, y = air_temp), color="darkolivegreen1") + labs(title="Molasses Reef Air Temperature vs. Sea Temperature", x="Sea Temperature (°C)", y="Air Temperature (°C)") # MG Air and Sea MG.AirSea <- ggplot(data = MG) + geom_point(mapping = aes(x = sea_temp, y = air_temp), color="lightpink1") + labs(title="Mid Gulf Air Temperature vs. Sea Temperature", x="Sea Temperature (°C)", y="Air Temperature (°C)") # GB Air and Sea GB.AirSea <- ggplot(data = GB) + geom_point(mapping = aes(x = sea_temp, y = air_temp), color="khaki") + labs(title="Georges Bank Air Temperature vs. Sea Temperature", x="Sea Temperature (°C)", y="Air Temperature (°C)") # Make the Plots Readable and Comparable with gridExtra grid.arrange(CM.AirSea, MR.AirSea, MG.AirSea, GB.AirSea, ncol=2) #Descriptive Statistics #Each descriptive statistics block contains a summary statement to retrieve the #minumum, maximum, mean, and median. The sd() argument produces the standard deviation #and the cor() finds the correlation between the air_temp and sea_temp for the given block #descriptive statistics for Cape May (all years) summary(CM$air_temp) sd(CM$air_temp, na.rm=TRUE) summary(CM$sea_temp) sd(CM$sea_temp, na.rm=TRUE) cor(CM$air_temp, CM$sea_temp, use = "complete.obs") #descriptive statistics for Cape May (1984) CM1984 <- CM %>% filter(date_time >= as.Date("1984-01-01") & date_time <= as.Date("1984-12-31")) #this filter statement takes data only from the first complete year of available data, #and creates a new corresponding variable so that the first year can be compared to the most #recent year of available data summary(CM1984$air_temp) sd(CM1984$air_temp, na.rm=TRUE) summary(CM1984$sea_temp) sd(CM1984$sea_temp, na.rm=TRUE) cor(CM1984$air_temp, CM1984$sea_temp, use = "complete.obs") #descriptive statistics for Cape May (2015) CM2015 <- CM %>% filter(date_time >= as.Date("2015-01-01") & date_time <= as.Date("2015-12-31")) #this filter statement takes data only from the most recent complete year of data #and creates a new corresponding variable so that the most recent year can be compared to the #first year of available data summary(CM2015$air_temp) sd(CM2015$air_temp, na.rm=TRUE) summary(CM2015$sea_temp) sd(CM2015$sea_temp, na.rm=TRUE) cor(CM2015$air_temp, CM2015$sea_temp, use = "complete.obs") #Cape May T-Test #Using the previously created variables, T-Tests are run for difference in means in both #air temperature and sea temperature. This translates to seeing if there is a significant #difference in temperature between the first year and the most recent year t.test(CM2015$air_temp, CM1984$air_temp) t.test(CM2015$sea_temp, CM1984$sea_temp) #The code described above is repeated for all of the buoys. #descriptive statistics for Molasses Reef (all years) summary(MR$air_temp) sd(MR$air_temp, na.rm=TRUE) summary(MR$sea_temp) sd(MR$sea_temp, na.rm=TRUE) cor(MR$air_temp, MR$sea_temp, use = "complete.obs") #descriptive statistics for Molasses Reef (1987) MR1988 <- MR %>% filter(date_time >= as.Date("1988-01-01") & date_time <= as.Date("1988-12-31")) summary(MR1988$air_temp) sd(MR1988$air_temp, na.rm=TRUE) summary(MR1988$sea_temp) sd(MR1988$sea_temp, na.rm=TRUE) cor(MR1988$air_temp, MR1988$sea_temp, use = "complete.obs") #descriptive statistics for Molasses Reef (2015) MR2015 <- MR %>% filter(date_time >= as.Date("2015-01-01") & date_time <= as.Date("2015-12-31")) summary(MR2015$air_temp) sd(MR2015$air_temp, na.rm=TRUE) summary(MR2015$sea_temp) sd(MR2015$sea_temp, na.rm=TRUE) cor(MR2015$air_temp, MR2015$sea_temp, use = "complete.obs") #Molasses Reef T-Test t.test(MR2015$air_temp, MR1988$air_temp) t.test(MR2015$sea_temp, MR1988$sea_temp) #descriptive statistics for Georges Bank (all years) summary(GB$air_temp) sd(GB$air_temp, na.rm=TRUE) summary(GB$sea_temp) sd(GB$sea_temp, na.rm=TRUE) cor(GB$air_temp, GB$sea_temp, use = "complete.obs") #descriptive statistics for Georges Bank (1985) GB1985 <- GB %>% filter(date_time >= as.Date("1985-01-01") & date_time <= as.Date("1985-12-31")) summary(GB1985$air_temp) sd(GB1985$air_temp, na.rm=TRUE) summary(GB1985$sea_temp) sd(GB1985$sea_temp, na.rm=TRUE) cor(GB1985$air_temp, GB1985$sea_temp, use = "complete.obs") #descriptive statistics for Georges Bank (2015) GB2015 <- GB %>% filter(date_time >= as.Date("2015-01-01") & date_time <= as.Date("2015-12-31")) summary(GB2015$air_temp) sd(GB2015$air_temp, na.rm=TRUE) summary(GB2015$sea_temp) sd(GB2015$sea_temp, na.rm=TRUE) cor(GB2015$air_temp, GB2015$sea_temp, use = "complete.obs") #Georges Bank T-Test t.test(GB2015$air_temp, GB1985$air_temp) t.test(GB2015$sea_temp, GB1985$sea_temp) #descriptive statistics for Mid Gulf (all years) summary(MG$air_temp) sd(MG$air_temp, na.rm=TRUE) summary(MG$sea_temp) sd(MG$sea_temp, na.rm=TRUE) cor(MG$air_temp, MG$sea_temp, use = "complete.obs") #descriptive statistics for Mid Gulf (1984) MG1984 <- MG %>% filter(date_time >= as.Date("1984-01-01") & date_time <= as.Date("1984-12-31")) summary(MG1984$air_temp) sd(MG1984$air_temp, na.rm=TRUE) summary(MG1984$sea_temp) sd(MG1984$sea_temp, na.rm=TRUE) cor(MG1984$air_temp, MG1984$sea_temp, use = "complete.obs") #descriptive statistics for Mid Gulf (2015) MG2015 <- MG %>% filter(date_time >= as.Date("2015-01-01") & date_time <= as.Date("2015-12-31")) summary(MG2015$air_temp) sd(MG2015$air_temp, na.rm=TRUE) summary(MG2015$sea_temp) sd(MG2015$sea_temp, na.rm=TRUE) cor(MG2015$air_temp, MG2015$sea_temp, use = "complete.obs") #Mid Gulf T-Test t.test(MG2015$air_temp, MG1984$air_temp) t.test(MG2015$sea_temp, MG1984$sea_temp)
42826ad3b868f5dd246c2901e0264403c2917595
7b5f3f514a0d2f0be2af7fabce40a92fc66e11e3
/plot1.r
fbc61de461c83daa479dcdd1d29d74c442db16b0
[]
no_license
xianyang-wong/ExData_Plotting2
95c7d188e6d05f59614b464d8254dea63b50af29
07f9dae311fbdd19884ba85cd4ef85067eae9059
refs/heads/master
2021-01-19T00:13:08.150000
2015-04-23T13:47:00
2015-04-23T13:47:00
34,458,316
0
0
null
null
null
null
UTF-8
R
false
false
543
r
plot1.r
# Loads data if non-existent if (!"NEI" %in% ls()) { NEI <- readRDS("summarySCC_PM25.rds") } if (!"SCC" %in% ls()) { SCC <- readRDS("Source_Classification_Code.rds") } par("mar"=c(5.1, 4.5, 4.1, 2.1)) png(filename = "plot1.png", width = 480, height = 480, units = "px") totalEmissions <- aggregate(NEI$Emissions, list(NEI$year), FUN = "sum") plot(totalEmissions, type = "l", xlab = "Year", main = "Total Emissions in the United States from 1999 to 2008", ylab = expression('Total PM'[2.5]*" Emission")) dev.off()
0b11268846a576afa812d00a590feaa55579b7f9
0c6ff19387075346018f41f6e15b1e7e4759fbf9
/word2vec_eval.R
ac18c7cde051f708e6b4a781c47bfa95fe777d9e
[]
no_license
Sandy-HE/Tag_analysis
03db4829b6608b14ae5040da3dd43ec3e7f4d2de
16a70d5832ed0096c842136351eae7f1b71778ce
refs/heads/master
2021-03-31T16:13:25.470609
2020-06-12T04:57:18
2020-06-12T04:57:18
248,118,726
0
0
null
null
null
null
UTF-8
R
false
false
3,397
r
word2vec_eval.R
#Date: 2020-05-18 #To compare glove performance with word2vec, meanwhile keep the same corpus. #We use text2vec pruned_vocab to provide the input of word2vec #read back the processing result of word2vec to do evaluation #word2vec part run by "wvbyword2vec.py" library("data.table") #get pruned_vocab from text2vec analysis(combined with lastfm_tags_analysis.R) #based pruned_vocab, clean tags dataset and save csv file termfilter <- function(termlist){ term = termlist[termlist %in% pruned_vocab$term] paste(term,collapse =";") } token1= lapply(tokens, termfilter) #temp2 = as.data.frame(do.call(rbind,token1)) temp1 = train[,"track_id"] temp1$prunedtag= token1 fwrite(temp1, file="allprunedtags_emo_only.csv") #====read back the result of word2vec processing #'phrase_emo_only_cbow_D64.csv' wordvec_df <- fread("phrase_7685_cbow_D64.csv") wordvec_df <- fread("phrase_7685_sg_D32.csv") wordvec_df <- fread("phrase_emo_only_cbow_D4.csv") wordvec_df <- fread("phrase_emo_only_sg_D32.csv") d=32 wordvec_df <- wordvec_df[-1,] colnames(wordvec_df)[d+1]<-"term" word_vectors <- as.matrix(wordvec_df[,1:d]) rownames(word_vectors) <- wordvec_df$term eterms_df <- fread("./emotion_terms_list3.csv") sub_wordvec <- subset(word_vectors, rownames(word_vectors) %in% eterms_df$term) sub_wordvec <- sub_wordvec[order(rownames(sub_wordvec)),] #====Obtain ground truth data for valence-arousal-dominant rating==== #Warriner VAD rating, value range is [1,9] baseline_df = fread("Warriner_avd_ratings.csv") baseline_df = baseline_df[,c("Word","V.Mean.Sum","A.Mean.Sum","D.Mean.Sum")] baseline_df = baseline_df[baseline_df$Word %in% rownames(sub_wordvec),] #Normalized to [-1,1]. Given range [-n,n], scale to [-1,1]. (x-(-n))*2/2n-1 baseline_mt = as.matrix(baseline_df[,2:3]) baseline_mt= (baseline_mt-1)*2/8-1 rownames(baseline_mt) <- baseline_df$Word #====nMDS -- reduce to 2D or 3D word vectors==== #calculate pairwise-rows cosine similarity and generate a similarity matrix library(vegan) library(lsa) termsim_mt <-lsa::cosine(t(sub_wordvec)) termdis_mt <- max(termsim_mt)-termsim_mt mds_model<-metaMDS(termdis_mt, k=3) mds_terms <- mds_model$points mds_terms <- mds_terms[rownames(mds_terms) %in% baseline_df$Word ,] proc <- procrustes(baseline_mt,mds_terms) #plot(proc) summary(proc) mds_model<-metaMDS(termdis_mt, k=2) #stressplot(mds_model,termdis_mt) mds_terms <- mds_model$points mds_terms <- mds_terms[rownames(mds_terms) %in% baseline_df$Word ,] #mds_terms_exchange <- mds_terms[,c("MDS2","MDS1")] proc <- procrustes(baseline_mt,mds_terms) #plot(proc) summary(proc) #====visualization==== plot(mds_terms, type= 'n') text(mds_terms,rownames(mds_terms),cex=.7) #====Scherer baseline==== scherer_cord = as.data.frame(fread("scherer_emotion_coord.csv")) eterms_df <- fread("./emotion_terms_list.csv") sub_wordvec <- subset(word_vectors, rownames(word_vectors) %in% eterms_df$term) sub_wordvec <- sub_wordvec[order(rownames(sub_wordvec)),] scherer_cord$norm1_x = (scherer_cord$x)/230 scherer_cord$norm1_y = (scherer_cord$y)/230 scherer_cord_new <- scherer_cord[scherer_cord$term %in% rownames(sub_wordvec),] scherer_cord_new2 <- as.matrix(scherer_cord_new[,-c(1,2,3)]) mds_terms <- mds_terms[rownames(mds_terms) %in% scherer_cord_new$term ,] proc <- procrustes(scherer_cord_new2,mds_terms)
fa9f57b64ce1aa40a5bfcb691992432f8ddcc159
f73a7a320623e36c620cdd028a335b237f51e660
/man/GDPR_list.Rd
ee68fa3352ca62f183f54753f05658fd8a3dbfea
[ "CC-BY-4.0", "CC0-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
jonocarroll/tidyGDPR
5393e6e691dbc2a3e0b2867814e4a0744d537cef
92f4029e110027561dcd7cc148a5fff60151541d
refs/heads/master
2020-03-18T15:42:20.935164
2018-05-26T03:20:15
2018-05-26T03:20:15
134,924,332
12
0
null
null
null
null
UTF-8
R
false
true
550
rd
GDPR_list.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/stored_data.R \docType{data} \name{GDPR_list} \alias{GDPR_list} \title{GDPR Regulations Recitals as a list} \format{An object of class \code{list} of length 11.} \source{ \url{http://openscience.adaptcentre.ie/projects/GDPRtEXT/} Made available under the \href{https://creativecommons.org/licenses/by/4.0/}{CC-by-4.0} license } \usage{ GDPR_list } \description{ The GDPR full regulations stored as a list, converted from raw JSON via \link{fromJSON}. } \keyword{datasets}
79dca4b0b90d7520e6559ada1e10b167f7a74b9e
c6230d85e6ee06dc26e63fc756ecfbf81f1cfe94
/R/theme.R
f77a85cad90350188c73ec001b90076a30019ad7
[ "Apache-2.0" ]
permissive
bcgov/cccharts
48a3df6e09862326d08059978b92cc924f16cd2a
474e1360e0470728797bc304595c556b05812694
refs/heads/master
2021-01-11T05:34:05.178166
2020-12-16T23:02:21
2020-12-16T23:02:21
69,051,799
10
4
Apache-2.0
2020-04-15T00:37:10
2016-09-23T18:44:37
R
UTF-8
R
false
false
2,269
r
theme.R
# Copyright 2016 Province of British Columbia # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and limitations under the License. #' Theme #' #' ggplot2 theme for cccharts plots #' #' @param facet A flag indicating whether to use the theme for facetted graphs. #' @param map A flag indicating whether to use the theme for maps. #' @param base_family Base font family for plotting #' @seealso \code{\link[envreportutils]{theme_soe}} and #' \code{\link[envreportutils]{theme_soe_facet}} #' @export theme_cccharts <- function(facet = FALSE, map = FALSE, base_family = "") { if (facet) { theme <- envreportutils::theme_soe_facet(base_family = base_family) } else theme <- envreportutils::theme_soe(base_family = base_family) theme <- theme + theme( plot.title = element_text(size = rel(1.2)), axis.title.y = element_text(size = 14), axis.title.x = element_blank(), axis.text.x = element_text(size = 14), axis.text.y = element_text(size = 12), axis.line = element_blank(), panel.grid.major.x = element_blank(), panel.grid.minor.x = element_blank(), panel.border = element_rect(colour = "grey50", fill = NA), panel.background = element_rect(colour = "grey50", fill = NA), legend.position = ("bottom"), legend.title = element_text(size = 12, face = "bold"), legend.text = element_text(size = 11), legend.direction = ("horizontal"), legend.key = element_rect(color = "white", fill = NA), strip.text.x = element_text(size = 12) ) if (map) { theme <- theme + theme( panel.grid = element_blank(), panel.border = element_blank(), panel.background = element_rect(color = "white", fill = NA), axis.title = element_blank(), axis.text = element_blank(), axis.ticks = element_blank() ) } theme }
b5f06ca51f35828f37b1fc7744092c4a8d34eebf
70d6e1ca3c30d64d88fff068628774cfbeb2f307
/listenEnv.R
d7f8e485472b4ba602ad27ee687c50c05aba0d89
[]
no_license
josousa82/Course-R-Introduction-W3
7db9ffd343646ec31e6fa2a8e18c6c7fc9d24c2d
b2f64a186f847e0912287486f13233f7d68048af
refs/heads/master
2021-09-03T18:35:17.020997
2018-01-11T04:10:11
2018-01-11T04:10:11
115,117,724
0
0
null
null
null
null
UTF-8
R
false
false
144
r
listenEnv.R
listEnv <- function (){ g <- globalenv() while (environmentName(g) != 'R_EmptyEnv') { g <- parent.env(g); cat(str(g, give.attr = F)) } }
9da070a8ee1fb1705ee356ceb79cb2f55393b05b
fcf46fdb7479a9f3df87446a720ca301a72888d5
/graphLASSO.R
c8b7e627cbef61c5144220b1778a7abafbd2a8f8
[]
no_license
devcao/LOCOpath_repo
b080ac685f04f0f22f88c5667293e2e73a797045
2c6b0b5553e9298e6c30cf3bfe25348e31625088
refs/heads/master
2022-12-28T19:35:24.549883
2020-10-19T02:53:55
2020-10-19T02:53:55
null
0
0
null
null
null
null
UTF-8
R
false
false
18,357
r
graphLASSO.R
# This file contains basic code for graphical LASSO ###### Loading some useful package, not all required ######## require(glasso) require(CVglasso) require(LOCOpath) require(huge) #source('graphLASSO.R') source('NetTS.R') require(igraph) ####################################### ########## A mofifiled version of the huge.plot function in huge package ############## huge.plot_v1 = function (G, epsflag = FALSE, graph.name = "default", cur.num = 1, location = NULL, ...) { # A mofifiled version of the huge.plot function in huge package # All arguments the same as huge.plot, check huge.plot for more details gcinfo(FALSE) if (missing(location)) location = tempdir() oldlocation = getwd() a setwd(location) g = graph.adjacency(as.matrix(G != 0), mode = "undirected", diag = FALSE) layout.grid = layout.fruchterman.reingold(g) if (epsflag == TRUE) postscript(paste(paste(graph.name, cur.num, sep = ""), "eps", sep = "."), width = 8, height = 8) plot(g, layout = layout.grid, edge.color = "gray50", vertex.color = "red", vertex.size = 2, vertex.label = NA, ...) rm(g, location) gc() if (epsflag == TRUE) dev.off() setwd(oldlocation) } ### 2 functoins to make the imgage function in R generate correct matrix plot ### rotate <- function(x) t(apply(x, 2, rev)) # working function#\ image_v1 = function(mat,...){image(rotate(mat),...)} # new version of the image_funcion ###### graphical model variable screen ####### simu_graph_screen = function(n = 100, p = 50, type = 'A', Iter = 250){ # graphical model variable screen, output will be used to generete ROC curve # Args: # n, p; int, sample size and dimension of matrix # type: allow 2 options ('A', 'C'), 2 types of matices # Iter: int, number if iterations, use defualt 50 # Returns: # A List of: Theta_list: a list of all randomly generated precision matrix # glasso_results: a list of glasso estimates # LOCO_results: a list of calulated LOCO variable importance Theta_list = list() glasso_results = list() LOCO_results = list() for (i in 1:Iter){ #aa = chol(Sigma) Theta = generate_precision(p=p, type = type) Theta_list[[i]] = Theta Sigma=solve(Theta) Mu=rep(0,p) X=rmvn(n=n, mu = Mu,sigma = Sigma) S <- var(X) a = CVglasso(X=X, S=S) glasso_results[[i]] = a$Omega TS_sigma = graph_TS(S = S, n_rho = 50) LOCO_results[[i]] = TS_sigma #TS_sd = TS_sigma/sum(TS_sigma, na.rm=TRUE) #diag(TS_sd) = 0 #results[i, 1] = mean( (Theta != 0) == (a$Omega != 0) ) #results[i, 2] = mean( (Theta != 0) == (ifelse(TS_sd>thresh, 1,0) != 0) ) cat('Now:',i, '\n') } return(list(Theta_list = Theta_list, glasso_results = glasso_results, LOCO_results = LOCO_results)) } ###### generate 2 types of precision matrix as described in GRASS paper ####### generate_precision = function(p=50, type = 'A'){ # Generate 2 types of precision matrix as described in GRASS paper # Args: # p: int, dimension of matrix # type: allow 2 options ('A', 'C'), 2 types of matices # Returns: matrix, precision matrix # if(type == 'A'){ A = matrix(ifelse(runif(p*p, min=0,max=1)<=0.01, 1, 0), p, p) non_0_edge = which(A == 1, arr.ind=TRUE) upper_edge = non_0_edge[which((non_0_edge[,2] - non_0_edge[,1]) > 0), ] if(is.matrix(upper_edge)){ lower_edge = upper_edge lower_edge[,1] = upper_edge[,2]; lower_edge[,2] = upper_edge[,1] random_vector = runif(dim(upper_edge)[1], min=-0.3,max=0.7) A_prime = matrix(0, p, p) A_prime[upper_edge] = random_vector A_prime[lower_edge] = random_vector diag(A_prime) = 1 }else{ lower_edge[1] = upper_edge[2]; lower_edge[2] = upper_edge[1] random_vector = runif(1, min=-0.3,max=0.7) A_prime = matrix(0, p, p) A_prime[upper_edge[1],upper_edge[2]] = random_vector A_prime[upper_edge[2],upper_edge[1]] = random_vector diag(A_prime) = 1 } lam_min = min(eigen(A_prime)$values) Theta = A_prime + (0.1-lam_min)*diag(rep(1,p)) Theta = Theta / Theta[1,1] }else if (type == 'C'){ A_prime = matrix(0, p, p) for(i in 1:(p-2)){ random_value = runif(2, min=-0.3,max=0.7) A_prime[i,i+1] = random_value[1] A_prime[i,i+2] = random_value[2] A_prime[i+1,i] = A_prime[i,i+1] A_prime[i+2,i] = A_prime[i,i+2] } lam_min = min(eigen(A_prime)$values) Theta = A_prime + (0.1-lam_min)*diag(rep(1,p)) Theta = Theta / Theta[1,1] }else{ stop("Only support type = 'A' or 'C' for now" ) } return(Theta) } ###### graphical model variable screen (my own version, not for the GRASS paper) ####### simu_graph_screen_v2 = function(Theta, Iter = 200){ # graphical model variable screen, output will be used to generete ROC curve # Args: # THeta: matrix, the true precision matrix # Iter: int, number if iterations, use defualt 50 # Returns: # A List of: Theta_list: a list of all randomly generated precision matrix # glasso_results: a list of glasso estimates # LOCO_results: a list of calulated LOCO variable importance Sigma=solve(Theta) Theta_list = list() glasso_results = list() LOCO_results = list() for (i in 1:Iter){ Theta_list[[i]] = Theta Mu=rep(0,p) X=rmvn(n=100, mu = Mu,sigma = Sigma) S<- var(X) a = CVglasso(X=X, S=S) glasso_results[[i]] = a$Omega TS_sigma = graph_TS(S = S, n_rho = 50) LOCO_results[[i]] = TS_sigma #TS_sd = TS_sigma/sum(TS_sigma, na.rm=TRUE) #diag(TS_sd) = 0 #results[i, 1] = mean( (Theta != 0) == (a$Omega != 0) ) #results[i, 2] = mean( (Theta != 0) == (ifelse(TS_sd>thresh, 1,0) != 0) ) cat('Now:',i, '\n') } return(list(Theta_list = Theta_list, glasso_results = glasso_results, LOCO_results = LOCO_results)) } #### A wrapper function to calculate all precision matrix LOCO statistic for all entries of a precision matrix ### graph_TS = function(S, ...){ # A wrapper function to calculate all LOCO statistic for all entries of a matrix # Args: # S: matrix, emprical covariance matrix # ..., arguments for ExactNet.TS.Graph # Returns: matrix of LOCO statistic p = dim(S)[1] TS = matrix(NA, p, p) for (i in 1:(p-1)){ for (j in seq(i+1, p)){ #for (i in 1:(p)){ # for (j in seq(1, p)){ cat(i, j, '\n') try({ ts = ExactNet.TS.Graph(S, c1 = i, c2 = j, ...) }) TS[i,j] = ts; TS[j,i] = ts; } } return(TS) } #### A wrapper function to calculate all covariance matrix LOCO statistic for all entries of of a matrix ### graph_TS_sigma = function(S, ...){ # A wrapper function to calculate all LOCO statistic for all entries of a covariance matrix # Args: # S: matrix, emprical covariance matrix # ..., arguments for ExactNet.TS.Graph.Sigma # Returns: matrix of LOCO statistic p = dim(S)[1] TS = matrix(NA, p, p) for (i in 1:(p-1)){ for (j in seq(i+1, p)){ #for (i in 1:(p)){ # for (j in seq(1, p)){ cat(i, j, '\n') try({ ts = ExactNet.TS.Graph.Sigma(S, c1 = i, c2 = j, ...) }) TS[i,j] = ts; TS[j,i] = ts; } } return(TS) } #### A function to transform the outputs of graphical LASSO code #### to a matrix so we can compute the LOCO statistic easier trans_lars_matrix = function(obj, use.glasso = FALSE){ # Args: # obj: cound be glasso output or graphLASSO.path output # use.glasso: if obj is glasso output, use FALSE. Otherwise, set to be TRUE # Return: a matrix,, each row contains the upper triangle value for a fixed lambda if (use.glasso){ p = dim(obj$wi)[1] n_lam = dim(obj$wi)[3] beta_hat = matrix(0, n_lam, p*(p-1)/2) for(i in 1:n_lam){ mat_temp = obj$wi[,,i] beta_hat[i, ] = mat_temp[upper.tri(mat_temp, diag = FALSE)] } }else{ p = dim(obj$wi[[1]])[1] n_lam = length(obj$rholist) beta_hat = matrix(0, n_lam, p*(p-1)/2) for(i in 1:n_lam){ mat_temp = obj$wi[[i]] beta_hat[i, ] = mat_temp[upper.tri(mat_temp, diag = FALSE)] } } return(beta_hat) } ######### Our own version of graphical LASSO ######## graphLASSO = function(S, lambda, maxIt = 100, tol = 1e-6, use.lars=FALSE){ # Our own version of graphical LASSO # Args: # S: int. sample covariance matrix # lambda: positive float, the regularization parameter # maxIt: int, default 100, maximum itersion allowed # tol: float, tolerance criterion, if results between 2 itersion are < tol, quit from intersion # use.lars: use lars or glment as backend. TRUE for lars, FALSE for glmnet # Defulat FALSE (recommened), glmnet runs faster than lars # Returns: # A list of: lambda: lambda value, # W: estimated covariance matrix # Theta: estimated precision matrix, invert of W p = dim(S)[1] W = S + diag(rep(lambda, p)) W_old = W i = 0 while (i < maxIt){ i = i+1 for (j in p:1){ sub_index = (1:p)[-j] eigen_obj = eigen(W[sub_index, sub_index], symmetric = TRUE) V = eigen_obj$vectors d = eigen_obj$values X = V %*% diag(sqrt(d)) %*% t(V) # W_11^(-1/2) * s_12 Y = V %*% diag( 1/sqrt(d) ) %*% t(V) %*% S[sub_index,j] if(use.lars){ lars_obj = lars(X, Y, type='lasso', intercept=FALSE, normalize=FALSE, use.Gram = FALSE) b = predict(lars_obj, s=lambda, type='coefficients', mode='lambda')$coefficients }else{ b = coef( glmnet(X,Y,lambda = lambda/(p-1), intercept = FALSE, standardize = FALSE) )[-1] } W[sub_index, j] = W[sub_index, sub_index] %*% b W[j, sub_index] = t(W[sub_index, j]) } #print(W) if( norm(W-W_old, type = '1') < tol ){ break } W_old = W } if (i == maxIt){ warning('Maximum number of iteration reached, glasso may not converge.') } return(list(lambda=lambda, W = W, Theta = solve(W))) } ###### Our own version of graphical LASSO, with constraint Sigma_{c1,c2} = 0 ####### graphLASSO.c = function(S, lambda, c1, c2, maxIt = 100, tol = 1e-6, use.lars=FALSE){ # Our own version of graphical LASSO, with constraint Sigma_{c1,c2} = 0 # Args: # S: int. sample covariance matrix # lambda: positive float, the regularization parameter # c1, c2: int, specify the correspoing entry of under constraint Sigma_{c1,c2} = 0 # maxIt: int, default 100, maximum itersion allowed # tol: float, tolerance criterion, if results between 2 itersion are < tol, quit from intersion # use.lars: use lars or glment as backend. TRUE for lars, FALSE for glmnet # Defulat FALSE (recommened), glmnet runs faster than lars # Returns: # A list of: lambda: lambda value, # W: estimated covariance matrix # Theta: estimated precision matrix, invert of W if(c1==c2){ stop('wrong input of c1,c2, must be different') }else{ c1=min(c1,c2) c2=max(c1,c2) } p = dim(S)[1] W = S + diag(rep(lambda, p)) W_old = W i = 0 while (i < maxIt){ i = i+1 for (j in p:1){ if(j == c2){ sub_index = (1:p)[-c(c1,c2)] eigen_obj = eigen(W[sub_index, sub_index], symmetric = TRUE) V = eigen_obj$vectors d = eigen_obj$values X = V %*% diag(sqrt(d)) %*% t(V) # W_11^(-1/2) * s_12 Y = V %*% diag( 1/sqrt(d) ) %*% t(V) %*% S[sub_index,j] if(use.lars){ lars_obj = lars(X, Y, type='lasso', intercept=FALSE, normalize=FALSE, use.Gram = FALSE) b = predict(lars_obj, s=lambda, type='coefficients', mode='lambda')$coefficients }else{ b = coef( glmnet(X,Y,lambda = lambda/(p-2), intercept = FALSE, standardize = FALSE) )[-1] } #w_12_constraint = W[sub_index, sub_index] %*% b W[sub_index, j] = W[sub_index, sub_index] %*% b W[j, sub_index] = t(W[sub_index, j]) W[c1, j] = 0 W[j, c1] = 0 }else if (j == c1){ sub_index = (1:p)[-c(c1,c2)] eigen_obj = eigen(W[sub_index, sub_index], symmetric = TRUE) V = eigen_obj$vectors d = eigen_obj$values X = V %*% diag(sqrt(d)) %*% t(V) # W_11^(-1/2) * s_12 Y = V %*% diag( 1/sqrt(d) ) %*% t(V) %*% S[sub_index,j] if(use.lars){ lars_obj = lars(X, Y, type='lasso', intercept=FALSE, normalize=FALSE, use.Gram = FALSE) b = predict(lars_obj, s=lambda, type='coefficients', mode='lambda')$coefficients }else{ b = coef( glmnet(X,Y,lambda = lambda/(p-2), intercept = FALSE, standardize = FALSE) )[-1] } W[sub_index, j] = W[sub_index, sub_index] %*% b W[j, sub_index] = t(W[sub_index, j]) W[c2, j] = 0 W[j, c2] = 0 }else{ sub_index = (1:p)[-j] eigen_obj = eigen(W[sub_index, sub_index], symmetric = TRUE) V = eigen_obj$vectors d = eigen_obj$values X = V %*% diag(sqrt(d)) %*% t(V) # W_11^(-1/2) * s_12 Y = V %*% diag( 1/sqrt(d) ) %*% t(V) %*% S[sub_index,j] if(use.lars){ lars_obj = lars(X, Y, type='lasso', intercept=FALSE, normalize=FALSE, use.Gram = FALSE) b = predict(lars_obj, s=lambda, type='coefficients', mode='lambda')$coefficients }else{ b = coef( glmnet(X,Y,lambda = lambda/(p-1), intercept = FALSE, standardize = FALSE) )[-1] } W[sub_index, j] = W[sub_index, sub_index] %*% b W[j, sub_index] = t(W[sub_index, j]) } } #print(W) if( norm(W-W_old, type = '1') < tol ){ break } W_old = W } if (i == maxIt){ warning('Maximum number of iteration reached, glasso may not converge.') } return(list(lambda=lambda, W = W, Theta = solve(W))) } #################################################################################### ##### Wrapper function the graphLASSO function, genereate graph LASSO solution path ########## graphLASSO.path = function(S, rholist = NULL, n_rho = 10, ...){ # Wrapper function the graphLASSO function, genereate graph LASSO solution path # Args: # S: matrix, sample covariance matrix # rholist: vector, sequence of rho, default NULL, if specified, need to be a vector # n_rho: int, length of the sequnce of rho, default 10 # Returns: a list of: # w: list of estimated covariance matrix # wi: list of estimated precision matrix # rholist: a vector of sequence of rho # if (is.null(rholist)) { rholist = seq(max(abs(S))/n_rho, max(abs(S)), length = n_rho) } w = list(); wi = list() i = 0 for (rho in rholist){ i = i + 1 glasso_obj = graphLASSO(S = S, lambda = rho, ...) w[[i]] = glasso_obj$W wi[[i]] = glasso_obj$Theta } return(list(w = w, wi = wi, rholist = rholist)) } # Wrapper function the graphLASSO.c function, genereate graph LASSO solution path under constraint Sigma_{c1,c2} = 0 ####### graphLASSO.path.c = function(S, rholist = NULL, n_rho = 10, ...){ # Args: # S: matrix, sample covariance matrix # rholist: vector, sequence of rho, default NULL, if specified, need to be a vector # n_rho: int, length of the sequnce of rho, default 10 # ..., other arguments for function graphLASSO.c # Returns: a list of: # w: list of estimated covariance matrix # wi: list of estimated precision matrix # rholist: a vector of sequence of rho # if (is.null(rholist)) { rholist = seq(max(abs(S))/n_rho, max(abs(S)), length = n_rho) } w = list(); wi = list() i = 0 for (rho in rholist){ i = i + 1 glasso_obj = graphLASSO.c(S = S, lambda = rho, ...) w[[i]] = glasso_obj$W wi[[i]] = glasso_obj$Theta } return(list(w = w, wi = wi, rholist = rholist)) } # Wrapper function the glasso, genereate graph LASSO solution path ####### glassopath.g = function(S, rholist = NULL, n_rho = 10, ...){ # Args: # S: matrix, sample covariance matrix # rholist: vector, sequence of rho, default NULL, if specified, need to be a vector # n_rho: int, length of the sequnce of rho, default 10 # ..., other arguments for function glasso # Returns: a list of: # w: list of estimated covariance matrix # wi: list of estimated precision matrix # rholist: a vector of sequence of rho # if (is.null(rholist)) { rholist = seq(max(abs(S))/n_rho, max(abs(S)), length = n_rho) } p = dim(S)[1] w = list(); wi = list() i = 0 for (rho in rholist){ i = i + 1 glasso_obj = glasso(s = S, rho = rho, ...) w[[i]] = glasso_obj$w wi[[i]] = glasso_obj$wi } return(list(w = w, wi = wi, rholist = rholist)) } # Constriant version: wrapper function the glasso function, genereate graph LASSO solution path under constraint Sigma_{c1,c2} = 0 ####### glassopath.c = function(S, c1 = 1, c2 = 2, large_pen = 10e4, rholist = NULL, n_rho = 10, ...){ # Args: # S: matrix, sample covariance matrix # c1, c2: int, specify the correspoing entry of under constraint Sigma_{c1,c2} = 0 # large_pen: the penalty on the (c1,c2) entry of S, should be large number # just use the default 10^4 unless you are experimenting # rholist: vector, sequence of rho, default NULL, if specified, need to be a vector # n_rho: int, length of the sequnce of rho, default 10 # ..., other arguments for function glasso # Returns: a list of: # w: list of estimated covariance matrix # wi: list of estimated precision matrix # rholist: a vector of sequence of rho # if (is.null(rholist)) { rholist = seq(max(abs(S))/n_rho, max(abs(S)), length = n_rho) } p = dim(S)[1] w = list(); wi = list() i = 0 for (rho in rholist){ i = i + 1 rho_matrix = matrix(rho, p, p) rho_matrix[c1,c2] = large_pen rho_matrix[c2,c1] = large_pen glasso_obj = glasso(s = S, rho = rho_matrix, ...) w[[i]] = glasso_obj$w wi[[i]] = glasso_obj$wi } return(list(w = w, wi = wi, rholist = rholist)) }
0d886aa62c53258df8cc597f8ff2fc96c2996c7b
a4e4aa76c902101fe5a475db1a4c2fafb2e55e9d
/대덕 wordcloud/daedeok.R
90d34bfb0bb4085ad68fa6df58a2c6db74c450dc
[]
no_license
joeychoi12/NC_Project
76f2777d8d9563a65e714887bacebaf313ceb040
36e5eac6d61b16989216d0c9ff1875b4961a6524
refs/heads/master
2020-06-16T07:51:42.060661
2019-08-13T08:01:04
2019-08-13T08:01:04
195,516,735
0
0
null
null
null
null
UTF-8
R
false
false
1,965
r
daedeok.R
#대덕특구 WordCloud setwd("c:/Users/Joey/Documents/R/Project/NC_Project/") # Text Crawling from Investing.com News article setwd("d:/workspace/R_Crawling/") library(rvest) library(dplyr) library(stringr) library(wordcloud2) trim <- function(x) gsub("^\\s+|\\s+$", "", x) trim1 <- function(x) gsub("\r", "", x) trim2 <- function(x) gsub("\t", "", x) trim3 <- function(x) gsub("\n", "", x) base_url <- "https://hellodd.com/?md=news&mt=lists&list_type=plists&j_pid=&j_name=&ymd=&sdate=&edate=&cate_code=&find=all&search=대덕특구&page=" url_page1 <- paste0(base_url, 2) url_page1 html_test <- read_html(url_page1) html_nodes(html_test,".article") %>% html_text() %>% trim() %>% trim1() %>% trim2() article <- c() for (i in 1:347) { if(i %% 50 == 0) print(i) url <- paste0(base_url,i,encoding="UTF-8") html <- read_html(url) title <- html_nodes(html, ".article") %>% html_text() %>% trim() %>% trim1() %>% trim2() article <- c(article,title) } article_title <- data.frame(title = article) write.csv(article_title,"대덕.csv") View(article_title) #Wordcloud install.packages("KoNLP") library(KoNLP) useSejongDic() write(article, "daedeok_data.txt") data <- readLines('daedeok_data.txt', Encoding="UTF-8") data1 <- sapply(data, extractNoun, USE.NAMES = F) data3 <- unlist(data1) data3 <- gsub("\\d+","",data3) ## 숫자 없애기 data3 <- Filter(function(x) {nchar(x) >= 2}, data3) #2글자 이상 필터 data4 <- str_replace_all(data3, "[^[:alpha:]]","") #한글, 영어이외는 삭제 txt2 <- readLines("경제gsub.txt") for(i in 1:length(txt2)) { data3 <- gsub(txt2[i],"",data3) } write(data4,"대덕특구.txt") data5 <- read.table("대덕특구.txt") wordcount <- table(data5) wordcloud <-sort(wordcount,decreasing = T) head(wordcloud) wordcloud2(wordcloud) Sys.getlocale() Sys.getlocale("LC_ALL","ko_KR.UTF-8") Sys.setlocale("LC_ALL","ko_KR.UTF-8") Sys.setlocale("LC_ALL", "korean") Sys.setlocale("LC_ALL", "en_US.UTF-8")
425d148f212d1951888a5dd60790efbb55cafdb5
e69b1afa76dbf248acbcea98bc2660e49e8e6805
/R programming/Week 3/rankall.r
f8f703359ec4607d3f1456fca1c9c843aef5793e
[]
no_license
Aparna-Vijayakumar/Data-Science-Coursera-Projects
281c6d7548dc718857679f47e49b485ec4fdca97
bf531db45b35aa4d6b169aeae19acb533b0c4cc1
refs/heads/master
2020-04-12T10:21:48.898664
2018-12-20T13:30:57
2018-12-20T13:30:57
162,427,731
1
0
null
null
null
null
UTF-8
R
false
false
1,451
r
rankall.r
rankall <- function(outcome, num = "best") { ## Read the outcome data dat <- read.csv("outcome-of-care-measures.csv", colClasses = "character") ## Check that state and outcome are valid states = unique(dat[, 7]) switch(outcome, `heart attack` = { col = 11 }, `heart failure` = { col = 17 }, pneumonia = { col = 23 }, stop("invalid outcome")) ## Return hospital name in that state with the given rank 30-day death rate dat[, col] = as.numeric(dat[, col]) dat = dat[, c(2, 7, col)] # leave only name, state, and death rate dat = na.omit(dat) # head(dat) Hospital.Name State 1 SOUTHEAST ALABAMA MEDICAL CENTER AL 2 # MARSHALL MEDICAL CENTER SOUTH AL 3 ELIZA COFFEE MEMORIAL HOSPITAL AL 7 ST # VINCENT'S EAST AL 8 DEKALB REGIONAL MEDICAL CENTER AL 9 SHELBY BAPTIST # MEDICAL CENTER AL # Hospital.30.Day.Death..Mortality..Rates.from.Heart.Attack 1 14.3 2 18.5 3 # 18.1 7 17.7 8 18.0 9 15.9 rank_in_state <- function(state) { df = dat[dat[, 2] == state, ] nhospital = nrow(df) switch(num, best = { num = 1 }, worst = { num = nhospital }) if (num > nhospital) { result = NA } o = order(df[, 3], df[, 1]) result = df[o, ][num, 1] c(result, state) } output = do.call(rbind, lapply(states, rank_in_state)) output = output[order(output[, 2]), ] rownames(output) = output[, 2] colnames(output) = c("hospital", "state") data.frame(output) }
1d2edc9647b2c58c081479861ce5e7c428928ad6
119e0655c3a2e1418bb67e42083e492546998f2e
/scripts_queue/Reading_MODIS_LST_with_QC_09112013.R
263bdbd49982ae3cf6a7ded01ac9dd424d0e15ee
[]
no_license
dahcase/space_time_lucc
435041b61700d481c86d02704d2151c8376e4e82
67fe9dca7a496714478fa1ce860e0cfbfc9fe603
refs/heads/master
2021-05-07T17:55:50.016325
2017-11-01T05:26:11
2017-11-01T05:26:11
108,768,679
0
1
null
2017-10-29T20:28:16
2017-10-29T20:28:16
null
UTF-8
R
false
false
6,704
r
Reading_MODIS_LST_with_QC_09112013.R
######################################## MODIS QC FOR MOD12Q1 and MOD11A2 ####################################### ########################################### Read QC flags in R for MODIS ##################################### #This script provides an example of Quality Flag processing for twor MODIS product in R. #MODIS currently stores information in HDF4 format. Layers to be extracted must be listed first #using for example gdalinfo. Note that QC flags are store bitpacks of 8bits (byte) in big endian!!! #A data frame matching flag values is created to facilate the processing. #Much of the inspiration and code originates from Steve Mosher: #http://stevemosher.wordpress.com/2012/12/05/modis-qc-bits/ #AUTHOR: Benoit Parmentier #DATE: 09/11/2013 #PROJECT: Space Time project and NCEAS ################################################################################################### ###Loading R library and packages #library(gtools) # loading some useful tools library(sp) library(raster) library(rgdal) library(BMS) #contains hex2bin and bin2hex library(bitops) ### Parameters and arguments in_dir<- "/Users/benoitparmentier/Dropbox/Data/NCEAS/MODIS_processing" out_dir<- "/Users/benoitparmentier/Dropbox/Data/NCEAS/MODIS_processing" setwd(out_dir) infile_LC<-"MCD12Q1A2001001.h10v09.051.2012157220925.hdf" infile_LST <- list.files(path=in_dir,pattern=".*.hdf$") infile_IDRISI <- list.files(path=in_dir,pattern=".*.rst$") function_analyses_paper <-"MODIS_and_raster_processing_functions_09112013.R" script_path<-in_dir #path to script functions source(file.path(script_path,function_analyses_paper)) #source all functions used in this script. ### BEGIN ### rg <-GDAL.open(infile_LST[1]) getDriver(rg) getDriverLongName(rg) #this does not work #GDALinfo(rg) #test<-readGDAL(rg,band=1) GDALinfo_hdf<-GDALinfo(infile_LST[1]) str(GDALinfo_hdf) #modis_subdataset <-attr(GDALinfo_hdf,"subdsmdata") #get modis subdataset #GDALinfo_hdf["columns"] #GDALinfo_hdf["rows"] modis_subdataset <- attributes(GDALinfo_hdf)$subdsmdata print(modis_subdataset) ###### PART I: Reading LST and Land cover layers (subset) ###### #HDF4_EOS:EOS_GRID:"MOD11A1.A2001001.h09v04.005.2006343034412.hdf":MODIS_Grid_Daily_1km_LST:LST_Day_1km #HDF4_EOS:EOS_GRID:"MOD11A1.A2001001.h09v04.005.2006343034412.hdf":MODIS_Grid_Daily_1km_LST:QC_Day #modis_subset_layer <- paste("HDF4_EOS:EOS_GRID:",f20,":MODIS_Grid_Daily_1km_LST:LST_Day_1km",sep='') modis_subset_layer_LST_Day <- paste("HDF4_EOS:EOS_GRID:",infile_LST[1],":MODIS_Grid_Daily_1km_LST:LST_Day_1km",sep="") modis_subset_layer_LST_QC <- paste("HDF4_EOS:EOS_GRID:",infile_LST[1],":MODIS_Grid_Daily_1km_LST:QC_Day",sep="") #modis_subset_layer <- file.path(in_dir,modis_subset_layer) r <-readGDAL(modis_subset_layer_LST_Day) r <-raster(r) r_qc <-readGDAL(modis_subset_layer_LST_QC) r_qc <-raster(r_qc) #system("gdalinfo MOD11A1.A2001020.h09v04.005.2006347194212.hdf") #system(paste("gdalinfo"," MCD12Q1A2001001.h10v09.051.2012157220925.hdf",sep="")) quartz(13,28) plot(r) plot(r_qc) #note the storage in FLT4S, i.e. float but in effect empty for #for anything greater than 255!!! freq(r_qc) #0 is good quality #Here are the most frequent categories found in the QC lqyers... r_qc2 <- r_qc==2 # QC not produced clouds r_qc0 <- r_qc==0 # QC good quality r_qc3 <- r_qc==3 # QC not produced r_qc65 <- r_qc==65 # LST produced r_qcl1 <- stack(r_qc0,r_qc2,r_qc3,r_qc65) layerNames(r_qcl1) <- c("r_qc0 Good quality","r_qc2 Not produced-Cloud","r_qc3 not produced","r_qc65 LST produced") plot(r_qcl1) ###### PART II: Reading and Handling QC flags ###### ## CONVERSION TO RAW FORMAT: rawToBits,inToBits,packBits: this is in {base} package intToBits(65) #integer INT four bytes, not that the notation include 01 for 1 #rawToBits(65) for vector length(intToBits(65)) intToBits(65)[1:8] #integer INT four bytes as.integer(intToBits(65)[1:8]) #[1] 1 0 0 0 0 0 1 0 #this is little endian binary notation fg<-as.integer(intToBits(65)[1:8]) #flag reversed into big endian to match MODIS fg[8:1] #This is number 65 in big endian format!!! BITS 0-1 : LST produced check other QA #[1] 0 1 0 0 0 0 0 1 rev(as.integer(intToBits(65)[1:8])) ##### Quick test unique_val<-unique(r_qc) #unique values f_values <- as.data.frame(freq(r_qc)) # frequency values in the raster... head(f_values) f_values rev(as.integer(intToBits(65)[1:8])) val<-(as.integer(intToBits(65)[1:8])) val<-val[8:1] #sprintf("%x",65) #convert decimal to hexadecimal using C-style string formatting #sprintf("%x",123) #r_qc2 <- r_qc==2 # LST not produced due to clouds (1-0) #r_qc0 <- r_qc==0 # LST good quality (0-0) #r_qc3 <- r_qc==3 # LST not produced (1-1) (in hex decimal 0x03) #r_qc65 <- r_qc==65 # LST produced check QA (0-1) #[1] 0 1 0 0 0 0 0 1 : this is 65 val[1:2] # LST produced check QA (0-1) val[3:4] # good quality (0-0) #this is in the second level info, data quality flag val[5:6] # average emissivity error <= 0.01 , Emis Error Flag val[7:8] # average LST error <= 2K , LST Error Flag rev(as.integer(intToBits(65)[1:8])) rev(hex2bin("0x03")) #if 110000000000 then it is not produced and should be removed...? #if((qc_this_day & 0x03)==0, ${lst}, null())' # & is bitwise-and, #e.g qc_this day: 00000010 #e.g. 0x03 : 00000011 # result "AND" : 00000010 hence FALSE and value is set to null in GRASS... # Check in GRASS... # In R use bitAnd(a,b) for the bitwise operator & #there are 13 unique values, the most frequent one is value 2 with 3,0 and 65 following... ## REWRITE INTO A FUNCTION with options for LST,LC and NDVI/EVI ## Step 1: list values in raster f_values <- as.data.frame(freq(r_qc)) # frequency values in the raster... head(f_values) ## Step 2: convert integer values into relevant binary t44 <- (sapply(f_values$value,function(x){rev(as.integer(intToBits(x)[1:8]))})) t44 <- (lapply(f_values$value,function(x){rev(as.integer(intToBits(x)[1:8]))})) #f_values$bin_val <- unlist(lapply(f_values$value,function(x){rev(as.integer(intToBits(x)[1:8]))})) #This is currently created for LST (see S. Mosher blog) QC_obj <- create_MODIS_QC_table(LST=TRUE) names(QC_obj) QC_data_lst <- QC_obj$LST qc_lst_valid <- subset(x=QC_data_lst,Bit1 == 0 & Bit0 ==1 & Bit3 !=1) names(qc_lst_valid) qc_lst_valid$Integer_Value qc_valid<-qc_lst_valid$Integer_Value qc_valid_modis_fun(qc_valid,rast_qc,rast_var){ ## function to download modis product?? #add here...
003463745c27b6d4c1da201aee13eaa41f08eef9
96e54a2f183ac913cd533b22560dbb6f9de98e64
/man/assignMultiple.Rd
e8c2f447a07388e4a326e9290332611cc23a16cf
[]
no_license
cran/KarsTS
fe9e7cb51abd77edc1cf461b92fe86e9c760b9a8
a61bf7a479a7eeba1d2af68ff0fab8041b3d3fe2
refs/heads/master
2021-08-16T07:19:03.010559
2021-01-14T19:50:05
2021-01-14T19:50:05
92,603,787
0
0
null
null
null
null
UTF-8
R
false
false
592
rd
assignMultiple.Rd
\name{assignMultiple} \alias{assignMultiple} %- Also NEED an '\alias' for EACH other topic documented here. \title{ assignMultiple: assign multiple } \description{ This function applies the function assign multiple times } \usage{ assignMultiple(namesVector, valuesList, envir = KTSEnv) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{namesVector}{ A vector containing the names to be assigned } \item{valuesList}{ The values to which the names will be assigned } \item{envir}{ The environment } } \author{ Marina Saez Andreu }
d4c3f6c0367bd01463fdcc23ae17d56b86b05e0d
641f150bdb4dfd3cb5cd28af2c36dfeef24a6776
/plot3.R
9a762ff46fcf4526e5292473cebf86da48337834
[]
no_license
Louise222/ExData_Plotting1
824e5d902831148bf32fe8429979e5581365e2d5
85c602be91e7e9486549fea866fe5c23efb65840
refs/heads/master
2021-01-21T02:59:19.979829
2016-01-08T08:31:45
2016-01-08T08:31:45
49,254,300
0
0
null
2016-01-08T06:29:23
2016-01-08T06:29:23
null
UTF-8
R
false
false
446
r
plot3.R
source("load_data.R") png(filename = "plot3.png", width = 480, height = 480, units = "px") plot(newdata$DateTime,newdata$Sub_metering_1,type = "l", col="black",xlab="",ylab = "Energy sub metering") lines(newdata$DateTime,newdata$Sub_metering_2,col="red") lines(newdata$DateTime,newdata$Sub_metering_3,col="blue") legend("topright",c("Sub_metering_1","Sub_metering_2","Sub_metering_3"), col = c("black","red","blue"),lwd = 1) dev.off()
e5b304972be9a7b44a8ea8946ce17513a4c89ed1
1eee16736f5560821b78979095454dea33b40e98
/thirdParty/HiddenMarkov.mod/R/summary.mmglm1.R
d4381fb77ae1ea7aaaaa322be44e23390e164467
[]
no_license
karl616/gNOMePeaks
83b0801727522cbacefa70129c41f0b8be59b1ee
80f1f3107a0dbf95fa2e98bdd825ceabdaff3863
refs/heads/master
2021-01-21T13:52:44.797719
2019-03-08T14:27:36
2019-03-08T14:27:36
49,002,976
4
0
null
null
null
null
UTF-8
R
false
false
229
r
summary.mmglm1.R
"summary.mmglm1" <- function (object, ...) { list(delta=object$delta, Pi=object$Pi, nonstat=object$nonstat, beta=object$beta, sigma=object$sigma, glmfamily=object$glmfamily, n=length(object$y)) }
5919d6b4d61c2ab795d9e5b3a12f9f542372bad8
fdb874e3f89e28d8d5e2c9a499aa9bbe46349792
/fitGaussianGraph/R/fitGaussianGraph.R
260054dab4a119a873695d4529f8cad143ce6e9e
[]
no_license
bohaoyao/fitting-Gaussian-graphical-models
e3ae9f754c5902013ba9f89931ed6c696736c33d
9cff38b4989176dffa514af5333fe2ffb5612049
refs/heads/master
2022-08-07T06:38:30.051474
2022-07-20T16:35:44
2022-07-20T16:35:44
225,881,948
0
1
null
null
null
null
UTF-8
R
false
false
6,165
r
fitGaussianGraph.R
#outputs value of a_{i,j} f <- function(i, j, LambdaE, S){ ans <- S[i,j] if (i > 1) { for (k in 1:(i-1)) { ans <- ans - LambdaE[k,i]*S[k,j] } } return(ans) } #outputs parents of i parents <- function(i, LambdaA){ ans <- c() if (i > 1) { for (j in 1:(i-1)) { if (LambdaA[j,i] != 0) { ans <- c(ans, j) } } } return(ans) } #outputs the starting point \Tilde{\Lambda} SolveLambdaE <- function(LambdaA, S){ p <- dim(S)[1] # dimension LambdaE <- matrix(0, p, p) for (i in 2:p) { pa <- parents(i, LambdaA) p1 <- length(pa) if (p1 > 0) { A <- matrix(0, p1, p1) b <- matrix(0, p1, 1) count1 <- 1 for (j in pa) { count2 <- 1 for (k in pa) { A[count1, count2] <- f(j, k, LambdaE, S) count2 <- count2 + 1 } b[count1, 1] <- f(j, i, LambdaE, S) count1 <- count1 + 1 } B <- solve(A,b) LambdaE[pa,i] <- B } } return(LambdaE) } #outputs the value of \Tilde{\omega_{ij}} SolveOmega <- function(i, j, LambdaE, S){ ans <- f(i, j, LambdaE, S) if (j > 1) { for (k in 1:(j-1)) { ans <- ans - LambdaE[k,j]*f(i, k, LambdaE, S) } } return(ans) } #outputs the starting points \Tilde{\Omega} SolveOmegaE <- function(OmegaA, LambdaE, S){ p <- dim(S)[1] # dimension OmegaE <- matrix(0, p, p) for (i in 1:p) { for (j in i:p) { if (OmegaA[i,j] != 0) { OmegaE[i,j] <- SolveOmega(i, j, LambdaE, S) if (i != j) { OmegaE[j,i] <- OmegaE[i,j] } } } } return(OmegaE) } #outputs the derivative of the loglikelihood against Lambda dLambda <- function(L, O, LambdaA, S) { p <- dim(O)[1] # dimension A <- 2*S%*%(diag(p)-L)%*%solve(O) for (i in 1:p) { for (j in 1:p) { if (LambdaA[i,j] == 0){ A[i,j] <- 0 } } } return(A) } #outputs the derivative of the loglikelihood against Omega dOmega <- function(L, O, OmegaA, S) { p <- dim(O)[1] # dimension B <- solve(O)%*%t((diag(p)-L))%*%S%*%(diag(p)-L)%*%solve(O)-solve(O) for (i in 1:p) { for (j in i:p) { if (OmegaA[i,j] == 0){ B[i,j] <- 0 B[j,i] <- 0 } } } return(B) } #outputs the loglikelihood given Lambda and Omega (divided by n) loglikelihood <- function(L, O, S) { p <- dim(O)[1] # dimension return(log(det((diag(p)-L)%*%solve(O)%*%t(diag(p)-L)))-sum(diag(S%*%(diag(p)-L)%*%solve(O)%*%t(diag(p)-L)))) } #outputs the loglikelihood given Sigma loglikelihoodS <- function(Sigma, S, n) { return((-n*(log(det(Sigma)))-n*sum(diag(solve(Sigma)%*%S)))/2) } #ouputs the number of missing edges in the graph (used for finding the degree of freedom) count_missing_edges <- function(LambdaA, OmegaA) { p <- dim(LambdaA)[1] edges <- 0 for (i in 1:(p-1)) { for (j in (i+1):p) { if (LambdaA[i,j] != 0) { edges <- edges + 1 } else if (OmegaA[i,j] != 0) { edges <- edges + 1 } } } return(p*(p-1)/2 - edges) } #uses hill climbing algorithm to output the supremum of Lambda, Omega and Sigma #also computes the p-value HillClimb <- function(LambdaE, OmegaE, learning_rate, convergence, S, n) { diff <- 1 Lambda0 <- LambdaE Omega0 <- OmegaE p <- dim(S)[1] # dimension min_eig <- min(eigen(Omega0)$values) if (min_eig <= 0) { Omega0 <- Omega0 - (min_eig - 1)*diag(p) } # if (min(eigen(Omega0)$values) <= 0) { # SigmaE <- solve(t(diag(p)-LambdaE)) %*% OmegaE %*% solve(diag(p)-LambdaE) # message('Use a larger sample size to obtain p-value.') # return(list(Lambdahat = LambdaE, Omegahat = OmegaE, Sigmahat = SigmaE)) # } likelihoodvector <- c(loglikelihood(Lambda0, Omega0, S)) while (diff > convergence) { LambdaE <- Lambda0 OmegaE <- Omega0 A <- dLambda(LambdaE, OmegaE, LambdaE, S) B <- dOmega(LambdaE, OmegaE, OmegaE, S) Lambda0 <- LambdaE + learning_rate*A Omega0 <- OmegaE + learning_rate*B diff <- loglikelihood(Lambda0, Omega0, S) - loglikelihood(LambdaE, OmegaE, S) likelihoodvector <- c(likelihoodvector, loglikelihood(Lambda0, Omega0, S)) } SigmaE <- solve(t(diag(p)-LambdaE)) %*% OmegaE %*% solve(diag(p)-LambdaE) s <- 2 * (loglikelihoodS(S, S, n) - loglikelihoodS(SigmaE, S, n)) #likelihood ratio statistic e <- count_missing_edges(LambdaE, OmegaE) plot(likelihoodvector) return(list(Lambdahat = LambdaE, Omegahat = OmegaE, Sigmahat = SigmaE, chisq = s, pvalue = pchisq(s, df=e, lower.tail = FALSE))) } #' Fitting bridgeless Gaussian graphical model #' #' Fits a bridgeless Gaussian graphical model as well as outputting the p-value of whether the data set fits the model. #' #' The p-value should be used as a guide for rejecting models only as we might no longer be working in a concave space at low p-values. #' @param X centered data set (can provide both S and n instead). #' @param S covariance matrix of X (optional if X is provided). #' @param n sample size (optional if X is provided). #' @param LambdaA adjacency matrix for the directed edges in G. #' @param OmegaA adjacency matrix for the bidirected edges in G. #' @param learning_rate learning rate for the hill-climbing algorithm. #' @param convergence_rate the difference of the objective function between iterations whence we determine the hill-climbing algorithm has converged. #' #' @return A list with components #' \describe{ #' \item{Lambdahat}{a square matrix of the fitted regression coefficients.} #' \item{Omegahat}{the fitted covariance matrix of the error terms.} #' \item{Sigmahat}{the fitted covariance matrix of all observed variables.} #' \item{chisq}{the test statistic which converges to a chi-squared distribution.} #' \item{pvalue}{the p-value of whether the data set X fits the graphical model.} #' } #' #' @export fitGaussianGraph <- function(X, S, n, LambdaA, OmegaA, learning_rate, convergence_rate = 0) { if (missing(S)) { S <- cov(X) } if (missing(n)) { n <- length(X[,1]) } LambdaE <- SolveLambdaE(LambdaA, S) OmegaE <- SolveOmegaE(OmegaA, LambdaE, S) return(HillClimb(LambdaE, OmegaE, learning_rate, convergence_rate, S, n)) }
59e73cef20325621916023866c0d85b6f8dc721b
b4294e86bd4aa13da2da944c3499eff23ac9e0c6
/clustering.R
d1688c6c5cc4c662ca5a6b2ae5f77a1800d1a18a
[]
no_license
sylvansecrets/signal-coursework
62f0a5e7522eb478b6a6d6adc01609cebfeeeeca
caacf893d0e8c8fdff6c7fc0433422f54ea04309
refs/heads/master
2021-01-12T10:18:53.326551
2016-12-14T03:06:14
2016-12-14T03:06:14
76,419,676
0
0
null
null
null
null
UTF-8
R
false
false
3,474
r
clustering.R
library("readr") library("cluster") library("pvclust") library("fpc") library("ggplot2") options(digits=3) setwd("C:/Users/User/Documents/GitHub/Signal-Data-Science") protein_df = read.delim("~/GitHub/Signal-Data-Science/protein.txt") rownames(protein_df) = protein_df$Country protein_df$Country=NULL # Scale the data protein_matrix = scale(protein_df) protein_matrix # Generate distance matrix dist_matrix = dist(protein_matrix, method="euclidean") dist_matrix # Create a cluster clust = hclust(dist_matrix, method="ward.D2") plot(clust) # Convenience function print_clusters = function(labels, k) { for(i in 1:k) { print(paste("cluster", i)) print(protein_df[labels == i, c( "RedMeat", "Fish", "Fr.Veg")]) } } # Cut trees into 5 cut_clust = cutree(clust,k=5) print_clusters(cut_clust, k=5) # Convenience function hclust_plot = function(d, method,k){ scaled = scale(d) distance = dist(scaled) uncut = hclust(distance, method=method) cut = cutree(uncut, k=k) return( clusplot(scaled, cut, color=TRUE, shade=TRUE, labels=2, lines=0) ) } # Plot the first two principle components for (k in 2:5) { hclust_plot(dist_matrix, "ward.D2", k) } # bootstrap sampled clusters (new with P-values!) # transpose first, pvclust goes by columns instead of rows pval_clust = pvclust(t(protein_matrix), method.hclust="ward.D2", method.dist="euclidean") # K means clustering k_mean = kmeans(protein_matrix, 5) kmeans_plot = function(data,k){ k_mean = kmeans(data,k) return(clusplot(data, k_mean$cluster, color=TRUE, shade=TRUE, labels=2, lines=0)) } # fairly not stable with k=5 # extremely stable with k=2 artificial = rbind(China = rnorm(ncol(protein_matrix), sd=2), protein_matrix) # the Chinese ruin everything # Validating a choice of K # NEVER EVER put plot=TRUE k_meanrun = kmeansruns(protein_matrix, krange=1:10, criterion="ch") k_meanrun2 = kmeansruns(protein_matrix, krange=1:10, criterion="asw") k_mean_compare = data.frame(k=1:10, asw=scale(k_meanrun2$crit), ch=scale(k_meanrun$crit)) ggplot(k_mean_compare, aes(x=k)) + geom_point(aes(y=asw), color="darkgreen", size=5, alpha=0.5) + geom_point(aes(y=ch), color="purple", size=4, alpha=0.7) # The criteria disagree: aws supports 3 (slight), ch supports 2(lots) # run bootstrap k-means k_bootstrap = clusterboot(protein_matrix, clustermethod=kmeansCBI, runs=100, iter.max=100, krange=5) # get clusters on original data bootstrap_clust = k_bootstrap$result$partition bootstrap_clust[bootstrap_clust == 1] # Greece Italy Portugal Spain bootstrap_clust[bootstrap_clust == 2] # Albania Bulgaria Romania Yugoslavia bootstrap_clust[bootstrap_clust == 3] # Denmark Finland Norway Swede bootstrap_clust[bootstrap_clust == 4] # Austria Belgium France Ireland Netherlands Switzerland UK W Germany bootstrap_clust[bootstrap_clust == 5] # Czechoslovakia E Germany Hungary Poland USSR # of times each cluster has dissolved (more is bad) k_bootstrap$bootbrd # [1] 40 17 23 19 51 # stability of clusters (closer to 1 is good) k_bootstrap$bootmean # 0.703 0.835 0.842 0.758 0.606 # first and fifth aren't great. clusplot(protein_matrix, k_bootstrap$result$partition, color=TRUE, shade=TRUE, labels=2, lines=0) # incidentally, 1 and 5 are the most elongated on this graph
ec0608ab59d19691b56e1903d53737d440150c59
2b96dda01e284f5df6c5f749272249ff3b1c26cd
/ch07/ex7-2.r
61b94533d0d98da095f32e452f6eb2071258a11f
[]
no_license
freebz/The-Art-of-R-Programming
f9a82b42fedebc5ef0f10bfd132bdcad27600d83
6e51856512b945455810b1ad686bae58f0779ff7
refs/heads/master
2021-06-05T03:27:00.519420
2016-08-12T05:01:24
2016-08-12T05:01:24
65,524,551
1
1
null
null
null
null
UTF-8
R
false
false
268
r
ex7-2.r
## 7.2 산술 및 불리언 연산과 값 x <- c(TRUE, FALSE, TRUE) y <- c(TRUE, TRUE, FALSE) x y x & y x[1] && y[1] if (x[1] && y[1]) print("both TRUE") if (x & y) print("both TRUE") 1 < 2 (1 < 2) * (3 < 4) (1 < 2) * (3 < 4) * (5 < 1) (1 < 2) == TRUE (1 < 2) == 1
fea2c3f1672d2b7d211bb60f320b9d14322e7ea7
9b94004d73d16cb4ce13efb088f240302abf33b5
/classifier_EM_tskew.R
4ce410c91dd14de87be02b67bf6253e390f0f088
[]
no_license
Zeroh729/MS-Thesis
f94b89070255851a1c261bb8d8ef04c241dfdad7
c4058e9444883a768a4c35876b9cb4e645c0d2f0
refs/heads/master
2022-12-31T20:45:59.786850
2020-10-22T07:15:45
2020-10-22T07:15:45
267,747,109
0
0
null
null
null
null
UTF-8
R
false
false
6,277
r
classifier_EM_tskew.R
source("D:/~Masters/~ MS-STAT/~THESIS/Code/utils.R") source("D:/~Masters/~ MS-STAT/~THESIS/Code/common.R") library(EMCluster) library(EMMIXskew) library(dplyr) emclassifier_tskew <- function(vecFluo, volDrp, crit="BIC"){ res <- em_tskew(data.frame(Fluorescence=sort(vecFluo)), distr="mst",volDrp = volDrp, crit) res_info <- get_resInfo(res, "mst") return(res_info) } emclassifier_t <- function(vecFluo, volDrp, crit="BIC"){ res <- em_tskew(data.frame(Fluorescence=sort(vecFluo)), distr = "mvt", volDrp = volDrp, crit) res_info <- get_resInfo(res, "mvt") return(res_info) } get_resInfo <- function(res, distr){ res_info <- list() G <- res$G if(distr == "mst"){ estParam <- data.frame(Mu = c(res$em$modpts), Sigma = sqrt(c(res$em$sigma)), Df = res$em$dof, Skew = c(res$em$delta), MixProp = res$em$pro) %>% mutate(NegThres = rep(res$negThres, nrow(.))) %>% mutate(PosThres = rep(res$posThres, nrow(.))) %>% arrange(Mu) title <- bquote("Neg~"~t~"("~v==.(round(estParam[1,"Df"],2))~","~mu==.(round(estParam[1,"Mu"],2))~","~sigma==.(round(estParam[1,"Sigma"],2))~","~delta==.(round(estParam[1,"Skew"],2))~")") subtitle <- bquote("Pos~"~t~"("~v==.(round(estParam[G,"Df"],2))~","~mu==.(round(estParam[G,"Mu"],2))~","~sigma==.(round(estParam[G,"Sigma"],2))~","~delta==.(round(estParam[G,"Skew"],2))~")") if(G == 3){ res_info$desc <- bquote("Rain~"~t~"("~v==.(round(estParam[2,"Df"],2))~","~mu==.(round(estParam[2,"Mu"],2))~","~sigma==.(round(estParam[2,"Sigma"],2))~","~delta==.(round(estParam[2,"Skew"],2))~")") } }else if(distr == "mvt"){ estParam <- data.frame(Mu = c(res$em$modpts), Sigma = sqrt(c(res$em$sigma)), Df = res$em$dof, MixProp = res$em$pro) %>% mutate(NegThres = rep(res$negThres, nrow(.))) %>% mutate(PosThres = rep(res$posThres, nrow(.))) %>% arrange(Mu) title <- bquote("Neg~"~t~"("~v==.(round(estParam[1,"Df"],2))~","~mu==.(round(estParam[1,"Mu"],2))~","~sigma==.(round(estParam[1,"Sigma"],2))~")") subtitle <- bquote("Pos~"~t~"("~v==.(round(estParam[G,"Df"],2))~","~mu==.(round(estParam[G,"Mu"],2))~","~sigma==.(round(estParam[G,"Sigma"],2))~")") if(G == 3){ res_info$desc <- bquote("Rain~"~t~"("~v==.(round(estParam[2,"Df"],2))~","~mu==.(round(estParam[2,"Mu"],2))~","~sigma==.(round(estParam[2,"Sigma"],2))~")") } } res_info$est_parameter <- estParam res_info$classification <- res$classification res_info$G <- G res_info$emres <- res res_info$title <- title res_info$subtitle <- subtitle return(res_info) } em_tskew <- function(drp, volDrp, distr, crit="BIC"){ getClusMemberProb <- function(emres){ clusterMem <- emres$tau means <- emres$modpts posClust <- which.max(means) negClust <- which.min(means) rainClust <- if(length(means)==3) which(means == median(means)) else NA clusts <- c(posClust, negClust, rainClust) names(clusts) <- c("pos", "neg", "rain") clusts <- sort(clusts) classification <- factor(names(clusts[emres$clust]), levels = c("pos", "neg", "rain")) print(paste("Negative Mu:", means[negClust], "Positive Mu:", means[posClust])) if(!is.na(rainClust)) print(paste("Rain Mu:", means[rainClust])) posMemberProb <- clusterMem[,posClust] negMemberProb <- clusterMem[,negClust] rainMemberProb <- clusterMem[,rainClust] return(list(negMemberProb,posMemberProb, classification)) } getInitParams <- function(drp, G){ set.seed(1234) initEM <- init.EM(drp, nclass = G) initEMSkew <- list(mu = t(initEM$Mu), sigma = array(c(initEM$LTSigma), c(1,1,G)), pro = initEM$pi, dof = rep(30, G), delta = t(matrix(rep(0,G)))) writeLines(paste("Initial parameters for G=", G)) writeLines(paste("Mu = ", initEMSkew$mu)) writeLines(paste("Sigma = ", initEMSkew$sigma)) writeLines(paste("Pi = ", initEMSkew$pro)) return(initEMSkew) } set.seed(1234) # Manual - https://cran.r-project.org/web/packages/EMMIXskew/EMMIXskew.pdf; ncov = 3 means general variance (1 & 2 gives me equal variances) emres_G2 <- EmSkew(drp, init = getInitParams(drp, G = 2), g = 2, nkmeans = 2, nrandom = 2, distr = distr, ncov = 3, initloop = 20, debug = FALSE) # MAIN FUNCTION emres_G3 <- EmSkew(drp, init = getInitParams(drp, G = 3), g = 3, nkmeans = 3, nrandom = 3, distr = distr, ncov = 3, initloop = 20, debug = FALSE) # MAIN FUNCTION if(crit == "BIC"){ scoreG2 <- emres_G2$bic scoreG3 <- emres_G3$bic }else if(crit == "ICL"){ scoreG2 <- emres_G2$ICL scoreG3 <- emres_G3$ICL }else if(crit == "AIC"){ scoreG2 <- emres_G2$aic scoreG3 <- emres_G3$aic } if(scoreG3 < scoreG2){ emres <- emres_G3 emres_lower <- emres_G2 G <- 3 }else{ emres <- emres_G2 emres_lower <- emres_G3 G <- 2 } .g(negMemberProb, posMemberProb, classification) %=% getClusMemberProb(emres) nneg <- sum(classification == "neg") res <- list() res$est <- cal_concentration(nneg, nrow(drp),volDrp) res$member <- list(negProb = negMemberProb, posProb = posMemberProb) res$G <- G res$em <- emres res$em_lower <- emres_lower res$crit <- crit res$critScore <- min(scoreG2, scoreG3) res$bestmodel <- paste(paste(crit, "of G=2 is",scoreG2), paste(crit, "of G=3 is", scoreG3), sep = "\n") res$classification <- classification res$negThres <- drp[max(which(classification == "neg")),] res$posThres <- drp[min(which(classification == "pos")),] return(res) } # setwd("D:/~Masters/~ MS-STAT/~THESIS/Papers/(Supplementary Files) Lievens/ddPCR-master") # if(!exists("df_orig")) df_orig <- readRDS("Dataset_t_sampled.RDS") # flou <- df_orig %>% filter(react.ID==13) %>% select(-c(1:11)) # flou <- flou[!is.na(flou)] # flou <- sort(as.numeric(as.character((flou)))) # # emres <- emclassifier_tskew(flou, 0.85, crit="BIC") # emres$emres$bestmodel # emres$G # emres$emres$em$mu # # # emres$emres$em$aic # emres$emres$em_lower$aic # Comparison with 3 Targets in Umbrella tutorial data # Umbrella (by thres) | (by robust) | Mine # Target 1 : 6021 | 6008 | 6021 # Target 2 : 5893 | 5914 | 5111 # Target 3 : 5717 | 5697 | 4584
9e4de14989ef8c07b2a3f19a863510535090ac7c
43badf574c549135a0fc50b5054be28fdc7fb275
/experiment/MaFMethodology/R/hhcovshhcmoea/IGD/15/kruskalscript.R
7cef81c9e79f6e3f0248fddfecc00230c5bceadc
[]
no_license
fritsche/hhco-vs-hhcmoea
8343a589e8efd1b0c0ffc8b0d67347fa688eb5a0
8cb8e1ec2ebab879d74391013d868af24d769b79
refs/heads/main
2023-02-10T15:19:20.576194
2021-01-09T14:00:38
2021-01-09T14:00:38
326,830,556
0
0
null
null
null
null
UTF-8
R
false
false
1,062
r
kruskalscript.R
require(PMCMRplus) options("width"=10000) ARRAY <- c(0.02564970475535416,0.01621768667849493,0.016800804793346218,0.016280921910048676,0.0696660740186638,0.016177777896017948,0.058561150499856586,0.01669128097678837,0.0160956658042893,0.05241825970439316,0.045721932836257646,0.03284580700929481,0.09004995630520703,0.015348621785942448,0.015844836607363782,0.019709934727626093,0.016074199028840254,0.015616036277590674,0.016449652590480437,0.017913837304476394,0.08784820446844634,0.02066736273635942,0.020069257987767073,0.11730987199401094,0.02837753926502847,0.018606337844368052,0.02708142995815993,0.15555478815849594,0.11843003497558917,0.018753892831454795,0.09747591145088905,0.023611751550549957,0.0191628505003178,0.06671959328116094,0.026136708289983955,0.01928011323808046,0.04418713139265151,0.16959652122366278,0.017343335949022196,0.19735732180574594) categs<-as.factor(rep(c("HHcMOEA","HHCOR2LPNORM"),each=20)); result <- kruskal.test(ARRAY,categs) print(result);pos_teste<-kwAllPairsNemenyiTest(ARRAY, categs, method='Tukey');print(pos_teste);
993432cbad85930bdc2a9ceb36e820b4985caae5
648ebf72f913f90fe9575a8325ce1d8633ac449e
/R/svd.triplet.R
c19cd38d5b246a562baa079f678cfd695ef1c62a
[]
no_license
husson/FactoMineR
1b2068dc925647603899607bf2a90e926ef002d5
1f7d04dcf7f24798ce6b322a4dd3ab2bd8ddd238
refs/heads/master
2023-04-28T09:19:02.186828
2023-04-23T11:32:21
2023-04-23T11:32:21
32,511,270
26
9
null
2023-04-21T13:34:38
2015-03-19T09:08:51
HTML
UTF-8
R
false
false
2,931
r
svd.triplet.R
svd.triplet <- function (X, row.w = NULL, col.w = NULL,ncp=Inf) { tryCatch.W.E <- function(expr){ ## function proposed by Maechler W <- NULL w.handler <- function(w){ # warning handler W <<- w invokeRestart("muffleWarning") } list(value = withCallingHandlers(tryCatch(expr, error = function(e) e), warning = w.handler), warning = W) } if (is.null(row.w)) row.w <- rep(1/nrow(X), nrow(X)) if (is.null(col.w)) col.w <- rep(1, ncol(X)) ncp <- min(ncp,nrow(X)-1,ncol(X)) row.w <- row.w / sum(row.w) X <- t(t(X)*sqrt(col.w))*sqrt(row.w) if (ncol(X)<nrow(X)){ ## svd.usuelle <- svd(X,nu=ncp,nv=ncp) ## lignes suivantes pour eviter qq pb de convergence de l'algo LINPACK de svd svd.usuelle <- tryCatch.W.E(svd(X,nu=ncp,nv=ncp))$val if (names(svd.usuelle)[[1]]=="message"){ svd.usuelle <- tryCatch.W.E(svd(t(X),nu=ncp,nv=ncp))$val if (names(svd.usuelle)[[1]]=="d"){ aux <- svd.usuelle$u svd.usuelle$u <- svd.usuelle$v svd.usuelle$v <- aux } else{ bb <- eigen(crossprod(X,X),symmetric=TRUE) svd.usuelle <- vector(mode = "list", length = 3) svd.usuelle$d[svd.usuelle$d<0]<-0 svd.usuelle$d <- sqrt(svd.usuelle$d) svd.usuelle$v <- bb$vec[,1:ncp] # svd.usuelle$u <- sweep(X%*%svd.usuelle$v,2,svd.usuelle$d[1:ncp],FUN="/") svd.usuelle$u <- t(t(crossprod(t(X),svd.usuelle$v))/svd.usuelle$d[1:ncp]) } } U <- svd.usuelle$u V <- svd.usuelle$v if (ncp >1){ mult <- sign(as.vector(crossprod(rep(1,nrow(V)),as.matrix(V)))) mult[mult==0] <- 1 U <- t(t(U)*mult) V <- t(t(V)*mult) } U <- U/sqrt(row.w) V <- V/sqrt(col.w) } else{ svd.usuelle <- tryCatch.W.E(svd(t(X),nu=ncp,nv=ncp))$val if (names(svd.usuelle)[[1]]=="message"){ svd.usuelle <- tryCatch.W.E(svd(X,nu=ncp,nv=ncp))$val if (names(svd.usuelle)[[1]]=="d"){ aux <- svd.usuelle$u svd.usuelle$u <- svd.usuelle$v svd.usuelle$v <- aux } else{ bb <- eigen(crossprod(t(X),t(X)),symmetric=TRUE) svd.usuelle <- vector(mode = "list", length = 3) svd.usuelle$d[svd.usuelle$d<0]<-0 svd.usuelle$d <- sqrt(svd.usuelle$d) svd.usuelle$v <- bb$vec[,1:ncp] svd.usuelle$u <- t(t(crossprod(X,svd.usuelle$v))/svd.usuelle$d[1:ncp]) } } U <- svd.usuelle$v V <- svd.usuelle$u mult <- sign(as.vector(crossprod(rep(1,nrow(V)),as.matrix(V)))) mult[mult==0] <- 1 V <- t(t(V)*mult)/sqrt(col.w) U <- t(t(U)*mult)/sqrt(row.w) } vs <- svd.usuelle$d[1:min(ncol(X),nrow(X)-1)] num <- which(vs[1:ncp]<1e-15) if (length(num)==1){ U[,num] <- U[,num,drop=FALSE]*vs[num] V[,num] <- V[,num,drop=FALSE]*vs[num] } if (length(num)>1){ U[,num] <- t(t(U[,num])*vs[num]) V[,num] <- t(t(V[,num])*vs[num]) } res <- list(vs = vs, U = U, V = V) return(res) }
6ac0235a84f9edc0855e66f9aaee6c24e63bfe47
a677b41109337cfc41479ee14e73884f2d75e898
/dsp/dwt.R
056296a8a374b0c874342a90c59967f8c62c76e7
[ "CC0-1.0" ]
permissive
af12066/example-r
b1d0eca8a1dee37203c398631900a2a2383c881b
4cdd170407fcbc90b49dcd2a5e85a13a067836a4
refs/heads/master
2016-08-12T07:28:52.798354
2015-12-13T03:11:41
2015-12-13T03:11:41
47,903,987
0
0
null
null
null
null
UTF-8
R
false
false
634
r
dwt.R
library(wavelets) Fs <- 100 # サンプリング周波数 sampling <- 1024 # Waveletサンプルポイント数 samplingPoint <- 0:(sampling-1) # サンプルポイント数のベクトル t <- samplingPoint / Fs # 時間軸 wave1 <- sin(2 * pi * 1 * t) # 波形(1Hz) wave2 <- rnorm(t) / 10 # 波形2(わずかにランダムノイズ) wave <- wave1 + wave2 wdec <- dwt(wave, filter = "d4", n.levels = 4) # ウェーブレットの種類... # d : Daubechies (2,4,6,8,10,12,14,16,18,20) # la : Least Asymetric (8,10,12,14,16,18,20) # bl : Best Localized (14,18,20) # c : Coiflet (6,12,18,24,30) plot(wdec)
98e72b1a602ddfb70846814074ef2e2fee03ec74
02fe930e2f9c76fea9643d013e98ab937724579f
/R/fastqTools.R
ceaf1fc92cecf2bc68de87314f5a319157d1c9a2
[]
no_license
sturkarslan/DuffyTools
ec751c1b58db5bef30ccc76f6e2afbc26c317d7d
10c540eaabdda27c14ddc9e27096e52444a2a67c
refs/heads/master
2016-08-04T23:58:02.110791
2014-11-26T18:09:35
2014-11-26T18:09:35
27,187,826
1
0
null
null
null
null
UTF-8
R
false
false
25,677
r
fastqTools.R
# fastqTools.R `readFastqFile` <- function( filein, maxReads=NULL, verbose=TRUE) { fileToUse <- allowCompressedFileName( filein) if ( ! file.readable( fileToUse)) { warning( paste( "readFastqFile: unable to read FASTQ file", fileToUse)) return( data.frame()) } # catch compressed files conIn <- openCompressedFile( fileToUse, open="r") if (verbose) cat( "\nReading file: ", fileToUse) # read in the raw text chunkSize <- 1000000 if ( ! is.null(maxReads) && (maxReads*4) < chunkSize) chunkSize <- maxReads * 4 readIDs <- readSeqs <- scores <- vector() repeat { fastqText <- readLines( con=conIn, n=chunkSize, warn=FALSE) if ( length( fastqText) < 1) break # get the delimited lines idLines <- grep( "^@", fastqText) scoreMarks <- grep( "^\\+", fastqText) if ( length( idLines) < 1 || length(scoreMarks) < 1 ) { warning( paste( "readFastqFile: not a FASTQ format file: ", fileToUse)) return( data.frame()) } idLines <- base::sort( intersect( idLines, seq( 1, length(fastqText), by=4))) scoreMarks <- base::sort( intersect( scoreMarks, seq( 3, length(fastqText), by=4))) if ( (length( idLines) != length(scoreMarks)) || any( idLines >= scoreMarks)) { warning( paste( "readFastqFile: bad FASTQ file: ", fileToUse, "\tMismatched readIDs and/or quality scores...")) return( data.frame()) } # now get the parts readIDs <- base::append( readIDs, sub( "^@", "", fastqText[ idLines])) readSeqs <- base::append( readSeqs, fastqText[ (idLines+1)]) scores <- base::append( scores, fastqText[ (scoreMarks+1)]) if (verbose) cat(".") if ( ! is.null( maxReads)) { if ( length(readIDs) >= maxReads) break } } # end of 'repeat' loop... close( conIn) if ( any( base::nchar( readSeqs) != base::nchar( scores))) warning( "readFastqFile: some Read & Score lengths disagree") out <- data.frame( readIDs, readSeqs, scores, stringsAsFactors=FALSE) colnames( out) <- FASTQ_COLUMNS rownames( out) <- 1:nrow(out) if ( ! is.null( maxReads)) { if ( nrow(out) >= maxReads) out <- out[ 1:maxReads, ] } if (verbose) cat( "\nN_Reads: ", prettyNum( nrow(out), big.mark=","), "\n") return( out) } `test.readFastqFile` <- function() { tmpFile <- build.testFastqFile() zz <- readFastqFile( tmpFile, verbose=FALSE) checkEquals( dim(zz), c(1000,3)) checkEquals( colnames(zz), FASTQ_COLUMNS) remove.testFile( tmpFile) } # efficient writing of .fastq to a file `writeFastqFile` <- function( x, fileout, compress=FALSE, verbose=TRUE) { if ( ! all( colnames( x) == FASTQ_COLUMNS)) { warning( paste( "writeFastqFile: unexpected column names: ", colnames(x))) warning( "No file written...") return( NULL) } fileToUse <- fileout # catch compressed file hasGZ <- (regexpr( "\\.gz$", fileout) > 0) if ( compress || hasGZ) { if ( ! hasGZ) fileToUse <- paste( fileout, "gz", sep=".") conOut <- gzfile( fileToUse, open="w") } else { conOut <- file( fileToUse, open="w") } # prepend the .fastq markers to the needed spots idText <- base::paste( "@", x$READ_ID, sep="") out <- base::paste( idText, x$READ_SEQ, "+", x$SCORE, sep="\n") # write it out writeLines( out, con=conOut, sep="\n") if( verbose) cat( "\nWrote file: \t", fileToUse, "\nN_Reads: \t", nrow( x),"\n") close( conOut) return( fileToUse) } `test.writeFastqFile` <- function() { tmpFile <- build.testFastqFile() zz <- readFastqFile( tmpFile, verbose=FALSE) tmpFile2 <- writeFastqFile( zz, fileout="DuffyTools.test2.fastq", verbose=FALSE) zz2 <- readFastqFile( tmpFile2, verbose=FALSE) checkEquals( zz, zz2) remove.testFile( tmpFile) remove.testFile( tmpFile2) } # make shorter reads from the ends for splice discovery `fastqToOverlapReadlets` <- function( filein, fileout, segmentLength=12, verbose=TRUE) { fileToUse <- allowCompressedFileName( filein) if ( ! file.exists( fileToUse)) stop( paste("Can't find input file: ", fileToUse)) conIn <- openCompressedFile( fileToUse, open="r") if ( regexpr( ".gz$", fileout) > 0) { conOut <- gzfile( fileout, open="w") } else { conOut <- file( fileout, open="w") } chunkSize <- 400000 nread <- 0 if (verbose) cat( "\nReading file: ", fileToUse) repeat { chunk <- readLines( conIn, n=chunkSize) if ( length( chunk) < 1) break # get the lines we want ids <- chunk[ seq( 1, length(chunk), by=4)] seqs <- chunk[ seq( 2, length(chunk), by=4)] scores <- chunk[ seq( 4, length(chunk), by=4)] N <- length( ids) # get the actual read lengths if ( nread == 0) { alllens <- base::nchar( seqs) maxlen <- max( alllens) segmentLength <- ceiling(segmentLength/2) * 2 overlap <- segmentLength / 2 nOverlaps <- ceiling( (maxlen - segmentLength) / overlap) + 1 if (verbose) cat( "\n readLen, segLength, overlap, nSegs: ", maxlen, segmentLength, overlap, nOverlaps) } myStarts <- seq( 1, (maxlen-overlap), by=overlap) myStops <- seq( segmentLength, (maxlen+overlap-1), by=overlap) if ( length( myStarts) != nOverlaps || length( myStarts) != nOverlaps) { cat( "bad overlap sizes...?") stop("") } myStarts[nOverlaps] <- maxlen - segmentLength + 1 myStops[nOverlaps] <- maxlen # get the substring chunks allSeqs <- allScores <- allIDs <- matrix( nrow=N, ncol=nOverlaps) for ( k in 1:nOverlaps) { allSeqs[ ,k] <- base::substr( seqs, myStarts[k], myStops[k]) allScores[ ,k] <- base::substr( scores, myStarts[k], myStops[k]) allIDs[ ,k] <- base::paste( ids, "/seg", k, sep="") } # interleave the output to keep the pairs together outIDs <- as.vector( t( allIDs)) outSeqs <- as.vector( t( allSeqs)) outScores <- as.vector( t( allScores)) # format as Fastq (the ID still has the '@'...) outTxt <- base::paste( outIDs, "\n", outSeqs, "\n+\n", outScores, sep="") writeLines( outTxt, con=conOut) nread <- nread + length( chunk) if (verbose) cat( ".") } close( conIn) close( conOut) if (verbose) cat( "\nN_reads: ", round( as.integer(nread)/4)) if (verbose) cat( "\nWrote file: ", fileout, "\n") return( list( "Segments"=nOverlaps, "Overlap"=overlap)) } `fastqToChunks` <- function( filein, fileroot=sub( "(fq|fastq)(.gz)?$","",filein), filetail=sub( fileroot, "", filein, fixed=T), chunk.size=1000000) { filein <- allowCompressedFileName( filein) if ( ! file.exists( filein)) stop( paste("Can't find input file: ", filein)) conIn <- openCompressedFile( filein, open="r") blockSize <- min( chunk.size, 100000) * 4 nread <- 0 nchunk <- 0 cat( "\nBreaking: ", basename(filein), " into chunks of ", chunk.size, "reads.\n") nThisChunk <- 0 makeNewFile <- TRUE repeat { if ( makeNewFile) { nchunk <- nchunk + 1 fileout <- paste( fileroot, "chunk", nchunk, ".", filetail, sep="") if ( regexpr( ".gz$", fileout) > 0) { conOut <- gzfile( fileout, open="w") } else { conOut <- file( fileout, open="w") } makeNewFile <- FALSE } thisBlockSize <- min( blockSize, (chunk.size-nThisChunk)*4) chunk <- readLines( conIn, n=thisBlockSize) if ( length( chunk) < 1) break nread <- nread + length(chunk)/4 nThisChunk <- nThisChunk + length(chunk)/4 # get the lines we want who <- seq( 1, length(chunk), by=4) ids <- chunk[ who] seqs <- chunk[ who + 1] scores <- chunk[ who + 3] writeLines( base::paste( ids, seqs, "+", scores, sep="\n"), con=conOut) cat( ".") if ( nThisChunk >= chunk.size) { close( conOut) cat( " ", nread, basename(fileout), "\n") makeNewFile <- TRUE nThisChunk <- 0 } } # close the last one... close( conOut) cat( "\n", nread, basename(fileout)) close( conIn) cat( "\nN_reads: ", round( as.integer(nread)/4)) return() } `fastqToFasta` <- function( filein, fileout, Qscores=TRUE) { filein <- allowCompressedFileName( filein) if ( ! file.exists( filein)) stop( paste("Can't find input file: ", filein)) conIn <- openCompressedFile( filein, open="r") if ( regexpr( ".gz$", fileout) > 0) { conOut <- gzfile( fileout, open="w") } else { conOut <- file( fileout, open="w") } chunkSize <- 800000 nread <- 0 repeat { chunk <- readLines( conIn, n=chunkSize) if ( length( chunk) < 1) break nread <- nread + length( chunk) # get the lines we want ids <- chunk[ seq( 1, length(chunk), by=4)] seqs <- chunk[ seq( 2, length(chunk), by=4)] if ( Qscores) { scores <- chunk[ seq( 4, length(chunk), by=4)] avgScores <- apply( phredScoreStringToInt( scores), MARGIN=1, FUN=mean) newIds <- base::paste( sub( "@", ">", ids, fixed=TRUE), ":Q=", formatC( avgScores, digits=2, format="f"), sep="") } else { newIds <- sub( "@", ">", ids, fixed=TRUE) } writeLines( base::paste( newIds, seqs, sep="\n"), con=conOut) cat( ".") } close( conIn) close( conOut) cat( "\nN_reads: ", round( as.integer(nread)/4)) return() } `clipBases` <- function( mySEQ, myScores, laneID, clip5prime, clip3prime, scoresAsIntegers=TRUE) { # parse the clip instructions... if ( is.null( clip5prime)) clip5prime <- 0 if ( is.null( clip3prime)) clip3prime <- 0 clipLanes <- vector() if ( ! is.null( names(clip5prime))) clipLanes <- names( clip5prime) if ( ! is.null( names(clip3prime))) clipLanes <- unique.default( base::append( clipLanes, names( clip3prime))) nClipLanes <- length( clipLanes) doByLane <- (nClipLanes > 0) if ( doByLane) { # there were some named lanes, so expand to a complete set trims <- matrix( 0, nrow=max(as.numeric(clipLanes)), ncol=2) trims[ as.numeric( names( clip5prime)), 1] <- base::unlist( clip5prime) trims[ as.numeric( names( clip3prime)), 2] <- base::unlist( clip3prime) } # get the lengths nlines <- length( mySEQ) nbases <- base::nchar( mySEQ) nscoreCh <- base::nchar( myScores) # and remove the leading spaces before the first base score if ( scoresAsIntegers) { repeat { hasBlank <- which( base::substr( myScores,1,1) == " ") if ( length( hasBlank) < 1) break myScores[ hasBlank] <- sub( " ", "", myScores[ hasBlank], fixed=TRUE) nscoreCh[ hasBlank] <- nscoreCh[ hasBlank] - 1 } scoreList <- strsplit( myScores, split=" ", fixed=TRUE) lens <- sapply( scoreList, length) if ( any( lens != nbases)) warning("clipBases: Read -- Quality score length mis-match") } # ready to do the clipping... if ( ! doByLane) { cat( " clipping all lanes(5',3')=", clip5prime, clip3prime) new5 <- 1 + clip5prime for ( i in 1:nlines) { new3 <- nbases[i] - clip3prime mySEQ[i] <- base::substr( mySEQ[i], new5, new3) if ( scoresAsIntegers) { scoretmp <- scoreList[[i]][ new5:new3] myScores[i] <- base::paste( scoretmp, collapse=" ") } else { myScores[i] <- base::substr( myScores[i], new5, new3) } } } else { for ( ilane in 1:nClipLanes) { lane <- clipLanes[ ilane] this5 <- trims[ as.integer( lane),1] this3 <- trims[ as.integer( lane),2] if ( all( c( this5, this3) == 0)) next who <- which( laneID == lane) if ( length( who) < 1) next new5 <- 1 + this5 cat( " clipping lane",lane,"(5',3')=", this5, this3) for ( i in who) { new3 <- nbases[i] - this3 mySEQ[i] <- base::substr( mySEQ[i], new5, new3) if ( scoresAsIntegers) { scoretmp <- scoreList[[i]][ new5:new3] myScores[i] <- base::paste( scoretmp, collapse=" ") } else { myScores[i] <- base::substr( myScores[i], new5, new3) } } } } # ready. out <- list( "seqs"=mySEQ, "scores"=myScores) return( out) } clipFastqFile <- function( filein, fileout, clip5prime=0, clip3prime=0) { # clip bases off an existing fastq file filein <- allowCompressedFileName( filein) if ( ! file.exists( filein)) stop( paste("Can't find input file: ", filein)) conIn <- openCompressedFile( filein, open="r") if ( regexpr( ".gz$", fileout) > 0) { conOut <- gzfile( fileout, open="w") } else { conOut <- file( fileout, open="w") } chunkSize <- 800000 nread <- 0 cat( "\nClipping ( 5', 3') = ", clip5prime, clip3prime, "\n") repeat { chunk <- readLines( conIn, n=chunkSize) if ( length( chunk) < 1) break nread <- nread + length( chunk) # get the lines we want ids <- chunk[ seq( 1, length(chunk), by=4)] seqs <- chunk[ seq( 2, length(chunk), by=4)] scores <- chunk[ seq( 4, length(chunk), by=4)] ans <- clipBases( seqs, scores, ids, clip5=clip5prime, clip3=clip3prime, scoresAsIntegers=FALSE) newSeqs <- ans$seq newScores <- ans$scores newLen <- base::nchar( newSeqs[1]) newIds <- sub( "=[0-9]+$", base::paste( "=",newLen, sep=""), ids) newId2 <- sub( "@","+", newIds, fixed=TRUE) writeLines( base::paste( newIds, newSeqs, newId2, newScores, sep="\n"), con=conOut) cat( ".") } close( conIn) close( conOut) cat( "\nN_reads trimmed: ", round( as.integer(nread)/4)) cat( "\nNew Read Length: ", base::nchar( newSeqs[1]), "\n") return() } `fastqPatternSearch` <- function( filein, patterns, max.mismatch=0, chunkSize=400000) { require( Biostrings) fileToUse <- allowCompressedFileName( filein) if ( ! file.exists( fileToUse)) stop( paste("Can't find input file: ", fileToUse)) conIn <- openCompressedFile( fileToUse, open="r") nread <- 0 cat( "\nReading file: ", fileToUse, "\n") nPatt <- length( patterns) findCounts <- rep( 0, times=nPatt) repeat { chunk <- readLines( conIn, n=chunkSize) if ( length( chunk) < 1) break # get the lines we want ids <- chunk[ seq( 1, length(chunk), by=4)] seqs <- chunk[ seq( 2, length(chunk), by=4)] N <- length( ids) # turn these into a serchable string subject <- DNAString( paste( seqs, collapse="N")) for ( k in 1:nPatt) { v <- countPattern( patterns[k], subject, max.mismatch=max.mismatch) findCounts[k] <- findCounts[k] + v if ( k %% 20 == 0) cat( "\r", k, v, sum( findCounts[1:k])) } nread <- nread + N cat( "\nReads: ", formatC( as.integer(nread), big.mark=","), "\tHits: ", sum( findCounts)) } cat( "\n") close( conIn) out <- findCounts names(out) <- patterns return( out) } `bam2fastq` <- function( bamfile, outfile=sub( ".bam$", "", bamfile), paired.end=TRUE) { cat( "\nConverting BAM file: ", bamfile) cat( "\nCreating FASTQ(s): ", outfile, "\n") cmdline <- paste( "bam2fastq.pl ", " --filter '-F 0x000' --prefix ", outfile, " ", bamfile) if ( paired.end) { cmdline <- paste( "bam2fastq.pl ", " --filter '-F 0x000' --yes --prefix ", outfile, " ", bamfile) } system( cmdline) cat( " Done.\n") return( ) } `fastqToPeptides` <- function( filein, fileout, chunkSize=100000) { filein <- allowCompressedFileName( filein) if ( ! file.exists( filein)) stop( paste("Can't find input file: ", filein)) conIn <- openCompressedFile( filein, open="r") #conOut <- file( fileout, open="wt") chunkLines <- chunkSize * 4 # local function to parallelize myDNAtoAAfunc <- function( x, peps, cnts) { peptides <- counts <- vector() nout <- 0 lapply( x, function(i) { dna <- peps[ i] lenFullAA <- floor( nchar(dna)/3) AAs <- DNAtoAA.fast( dna) # they have to be full length with no N's or non-AA calls good <- setdiff( which( nchar(AAs) == lenFullAA), grep( "?", AAs, fixed=T)) if ( (ngood <- length(good)) > 0) { nnow <- (nout+1) : (nout+ngood) peptides[ nnow] <<- AAs[ good] counts[ nnow] <<- cnts[i] nout <<- nout + ngood } return(NULL) }) # the mapping from DNA to AA may have generated duplicates if ( length( peptides) < 1) return( data.frame()) tapply( 1:length(peptides), factor( peptides), FUN=function(x) { if ( length(x) < 2) return() totalCnt <- sum( counts[x]) counts[ x[1]] <<- totalCnt counts[ x[2:length(x)]] <<- 0 return() }, simplify=FALSE) keep <- which( counts > 0) # final ans is a table of peptides with counts ans <- list( "Peptide"=peptides[keep], "Count"=counts[keep]) return(ans) } # end of local function nread <- ntotal <- nUtotal <- 0 repeat { chunk <- readLines( conIn, n=chunkLines) if ( length( chunk) < 1) break nReadsNow <- length(chunk)/4 nread <- nread + nReadsNow cat( "\nReads: ", prettyNum( as.integer( nread), big.mark=",")) # get the raw read lines we want, but only do one of each duplicate seqs <- chunk[ seq.int( 2, length(chunk), 4)] seqCntsTbl <- table( seqs) uniqSeqs <- names( seqCntsTbl) uniqCnts <- as.vector( seqCntsTbl) N <- length(uniqCnts) rm( seqCntsTbl) nUtotal <- nUtotal + N cat( " Unique: ", prettyNum( as.integer( nUtotal))) coreOpt <- getOption("cores") nCores <- if ( is.null(coreOpt)) 1 else as.integer( coreOpt) if ( nCores < 2) { ans <- myDNAtoAAfunc( 1:N, uniqSeqs, uniqCnts) } else { starts <- seq.int( 1, nReadsNow, (nReadsNow/nCores)) stops <- c( starts[2:length(starts)] - 1, nReadsNow) cat( " use", nCores, "cores..") locs <- vector( mode="list") for ( i in 1:length(starts)) locs[[i]] <- starts[i] : stops[i] ans <- multicore.lapply( locs, FUN=myDNAtoAAfunc, peps=uniqSeqs, cnts=uniqCnts, preschedule=TRUE) } # extract all the little data frame answers bigp <- bigc <- vector() if ( length( ans) == 2 && names(ans)[1] == "Peptide") { bigp <- ans$Peptide bigc <- ans$Count } else { cat( " merge..") for ( k in 1:length(ans)) { obj <- ans[[k]] newlocs <- (length(bigp) + 1) : (length(bigp) + length(obj$Peptide)) bigp[ newlocs] <- obj$Peptide bigc[ newlocs] <- obj$Count } } N <- length(bigp) # the mapping from DNA to AA may have generated duplicates cat( " dups..") tapply( 1:N, factor( bigp), FUN=function(x) { if ( length(x) < 2) return() totalCnt <- sum( bigc[x]) bigc[ x[1]] <<- totalCnt bigc[ x[2:length(x)]] <<- 0 return() }, simplify=FALSE) keep <- which( bigc > 0) ansDF <- data.frame( "Peptide"=bigp[keep], "Count"=bigc[keep], stringsAsFactors=F) nout <- nrow(ansDF) ntotal <- ntotal + nout cat( " Peptides: ", prettyNum( as.integer( ntotal)), " ", as.percent( ntotal, big.value=nUtotal*100, percentSign=FALSE), "per Read") #write.table( ansDF, file=conOut, col.names=(ntotal == nout), sep="\t", quote=F, row.names=F) if ( ntotal == nout) { write.table( ansDF, file=fileout, append=FALSE, col.names=TRUE, sep="\t", quote=F, row.names=F) } else { write.table( ansDF, file=fileout, append=TRUE, col.names=FALSE, sep="\t", quote=F, row.names=F) } } close( conIn) #close( conOut) cat( "\nTotal_Reads: ", prettyNum( as.integer(nread), big.mark=",")) cat( "\nTotal_Peptides: ", prettyNum( as.integer(ntotal), big.mark=",")) return( ntotal) } `fastqReader` <- function() { filename <- "" con <- NULL N <- 0 initialize <- function( file) { cat( "\nInitializing FASTQ reader for: ", file) if ( ! file.exists( file)) { cat( "\nFile not found: ", file) return( "Error") } con <<- gzfile( file, open="rt") filename <<- file return( file) } read <- function( n=1) { nlines <- n * 4 txt <- readLines( con, n=nlines) nread <- length( txt) if ( nread < 4) return(NULL) isRID <- seq( 1, nread, by=4) N <<- N + length(isRID) return( list( "rid"=base::sub( "^@","",txt[isRID]), "seq"=txt[isRID+1], "score"=txt[isRID+3])) } finalize <- function() { if ( !is.null(con)) base::close(con) cat( "\nRead", N, "records from: ", filename, "\n") return() } return( environment()) } `fastqWriter` <- function() { filename <- "" con <- NULL N <- 0 initialize <- function( file) { cat( "\nInitializing FASTQ writer for: ", file) con <<- gzfile( file, open="wt") filename <<- file return( file) } write <- function( rid, seq, score) { txt <- paste( "@", rid, "\n", seq, "\n+\n", score, sep="") writeLines( txt, con=con) N <<- N + 1 return() } finalize <- function() { if ( !is.null(con)) base::close(con) cat( "\nWrote", N, "records to: ", filename, "\n") return() } return( environment()) } `fastqToPairedFiles` <- function( file, secondFile=NULL, max.buf=20000) { options( warn=-1) on.exit( options( warn=0)) fin <- fastqReader() if ( fin$initialize(file) != file) return() f1name <- sub( "fastq.gz", "1.fastq.gz", file) fout1 <- fastqWriter() fout1$initialize(f1name) on.exit( fout1$finalize(), add=TRUE) f2name <- sub( "fastq.gz", "2.fastq.gz", file) fout2 <- fastqWriter() fout2$initialize(f2name) on.exit( fout2$finalize(), add=TRUE) rids1 <- rids2 <- seqs1 <- seqs2 <- scores1 <- scores2 <- rep.int("", 100) n1 <- n2 <- nout <- 0 find1 <- function( rid) { if ( n1 < 1) return(0) who <- (1:n1)[ rid == rids1[1:n1]][1] return( if (is.na(who)) 0 else who) } find2 <- function( rid) { if ( n2 < 1) return(0) who <- (1:n2)[ rid == rids2[1:n2]][1] return( if (is.na(who)) 0 else who) } store1 <- function( rid, seq, score) { where <- if ( n1 > 0) (1:n1)[ rids1[1:n1] == ""][1] else NA #where <- if ( n1 > 0) which( rids1[1:n1] == "")[1] else NA if ( is.na( where)) { n1 <<- n1 + 1 where <- n1 } rids1[where] <<- rid seqs1[where] <<- seq scores1[where] <<- score return() } store2 <- function( rid, seq, score) { where <- if ( n2 > 0) (1:n2)[ rids2[1:n2] == ""][1] else NA #where <- if ( n2 > 0) which( rids2[1:n2] == "")[1] else NA if ( is.na( where)) { n2 <<- n2 + 1 where <- n2 } rids2[where] <<- rid seqs2[where] <<- seq scores2[where] <<- score return() } squeeze1 <- function() { isBlank <- which( rids1 == "") if ( length( isBlank) > 0) { rids1 <<- rids1[ -isBlank] seqs1 <<- seqs1[ -isBlank] scores1 <<- scores1[ -isBlank] n1 <<- length(rids1) if ( n1 > max.buf) { drops <- 1 : (n1-max.buf) rids1 <<- rids1[ -drops] seqs1 <<- seqs1[ -drops] scores1 <<- scores1[ -drops] n1 <<- length(rids1) } } } squeeze2 <- function() { isBlank <- which( rids2 == "") if ( length( isBlank) > 0) { rids2 <<- rids2[ -isBlank] seqs2 <<- seqs2[ -isBlank] scores2 <<- scores2[ -isBlank] n2 <<- length(rids2) if ( n2 > max.buf) { drops <- 1 : (n2-max.buf) rids2 <<- rids2[ -drops] seqs2 <<- seqs2[ -drops] scores2 <<- scores2[ -drops] n2 <<- length(rids2) } } } # the main loop is to look for mate pairs within the file, buffering up as we go # so read one at a time cat("\n") repeat { item <- fin$read(1) if (is.null(item)) break rid1 <- rid2 <- item[[1]] nc <- nchar( rid1) mate <- substr( rid1, nc, nc) rid <- substr( rid1, 1, nc-1) seq <- item[[2]] score <- item[[3]] is1 <- (mate == '1') hit <- FALSE if (is1) { where2 <- find2( rid) if ( where2 == 0) { store1( rid, seq, score) } else { fout1$write( rid1, seq, score) rid2 <- paste( rid, "2", sep="") fout2$write( rid2, seqs2[where2], scores2[where2]) rids2[where2] <- "" nout <- nout + 1 hit <- TRUE } } else { where1 <- find1( rid) if ( where1 == 0) { store2( rid, seq, score) } else { fout2$write( rid2, seq, score) rid1 <- paste( rid, "1", sep="") fout1$write( rid1, seqs1[where1], scores1[where1]) rids1[where1] <- "" nout <- nout + 1 hit <- TRUE } } if ( hit && nout %% 100 == 0) { squeeze1() squeeze2() cat( "\rPairs:", nout, " Buf1:", n1, " Buf2:", n2) } } # done reading the file... fin$finalize() cat( "\rPairs:", nout, " Buf1:", n1, " Buf2:", n2) # if a second file was given, (the 'No Hits'), use it as a read only source of possible second mates if ( ! is.null( secondFile)) { if ( fin$initialize(secondFile) != secondFile) break cat("\n") repeat { item <- fin$read( n=10000) if (is.null(item)) break ridset <- item[[1]] seqset <- item[[2]] scoreset <- item[[3]] hit <- FALSE # see if any of whats in our buffers match these try1 <- paste( rids1, "2", sep="") where <- match( ridset, try1, nomatch=0) if ( any( where > 0)) { set2 <- which( where > 0) set1 <- where[ set2] for (j in 1:length(set2)) { j1 <- set1[j] j2 <- set2[j] fout1$write( rids1[j1], seqs1[j1], scores1[j1]) fout2$write( ridset[j2], seqset[j2], scoreset[j2]) rids1[j1] <- "" nout <- nout + 1 } hit <- TRUE } try2 <- paste( rids2, "1", sep="") where <- match( ridset, try2, nomatch=0) if ( any( where > 0)) { set1 <- which( where > 0) set2 <- where[ set1] for (j in 1:length(set1)) { j1 <- set1[j] j2 <- set2[j] fout1$write( ridset[j1], seqset[j1], scoreset[j1]) fout2$write( rids2[j2], seqs2[j2], scores2[j2]) rids2[j2] <- "" nout <- nout + 1 } hit <- TRUE } if (hit) { squeeze1() squeeze2() cat( "\rPairs:", nout, " Buf1:", n1, " Buf2:", n2, " ") if ( n1 == 0 && n2 == 0) break } } fin$finalize() } # all done now }
36ee8dcb5ec75e7c59693a236da8b4d4634cd53c
c06f1619dbd2007837f73cc184fdef6d821ad981
/man/same.Rd
37a2f7b229d4295cd2e8137000cc146c8f3976a4
[]
no_license
BenGriff42/useless
34cba60dada4e01324cd418e38e5c8fa0cad8f2d
ef3686ae6cbe4095ad0bdd3ac7ed97f4785c2a35
refs/heads/main
2023-08-14T11:45:09.814151
2021-10-07T12:28:32
2021-10-07T12:28:32
414,521,717
0
0
null
null
null
null
UTF-8
R
false
true
309
rd
same.Rd
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/useless_functions.R \name{same} \alias{same} \title{Return input} \usage{ same(x) } \arguments{ \item{x}{Anything} } \value{ What you input } \description{ Function to return whatever you put in } \examples{ same(1) same("same") }
159a89899233f9bcdcc4d1f30ca667cbcc1ca2c7
4201e9b754760dc35fc0aeef9df5a8b9d801c47f
/bin/R-3.5.1/src/library/stats/man/pairwise.wilcox.test.Rd
55d858490249dedc04617eb60f834e0cdc3beec8
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "GPL-2.0-only" ]
permissive
lifebit-ai/exomedepth
cbe59cb7fcf2f9183d187f8d466c6620fb1a0c2e
5a775ae5e2a247aeadc5208a34e8717c7855d080
refs/heads/master
2020-03-27T12:55:56.400581
2018-10-11T10:00:07
2018-10-11T10:00:07
146,578,924
0
0
MIT
2018-08-29T09:43:52
2018-08-29T09:43:51
null
UTF-8
R
false
false
1,543
rd
pairwise.wilcox.test.Rd
% File src/library/stats/man/pairwise.wilcox.test.Rd % Part of the R package, https://www.R-project.org % Copyright 1995-2007 R Core Team % Distributed under GPL 2 or later \name{pairwise.wilcox.test} \alias{pairwise.wilcox.test} \title{Pairwise Wilcoxon Rank Sum Tests} \description{ Calculate pairwise comparisons between group levels with corrections for multiple testing. } \usage{ pairwise.wilcox.test(x, g, p.adjust.method = p.adjust.methods, paired = FALSE, \dots) } \arguments{ \item{x}{ response vector. } \item{g}{ grouping vector or factor. } \item{p.adjust.method}{ method for adjusting p values (see \code{\link{p.adjust}}). Can be abbreviated.} \item{paired}{a logical indicating whether you want a paired test.} \item{\dots}{additional arguments to pass to \code{\link{wilcox.test}}.} } \details{ Extra arguments that are passed on to \code{wilcox.test} may or may not be sensible in this context. In particular, only the lower triangle of the matrix of possible comparisons is being calculated, so setting \code{alternative} to anything other than \code{"two.sided"} requires that the levels of \code{g} are ordered sensibly. } \value{ Object of class \code{"pairwise.htest"} } \seealso{ \code{\link{wilcox.test}}, \code{\link{p.adjust}}} \examples{ attach(airquality) Month <- factor(Month, labels = month.abb[5:9]) ## These give warnings because of ties : pairwise.wilcox.test(Ozone, Month) pairwise.wilcox.test(Ozone, Month, p.adj = "bonf") detach() } \keyword{htest}
977cd77d4cc90f7d8b437cc8291f9bf6eca6a800
ecb246919cb876cf82dc3375b9105189b254b96e
/tests/testthat/test_period_dates.R
3492827f0ab8e4bfc65e846c3820f19ad738e99c
[]
no_license
mickmioduszewski/dqr
4060cdc230c0f0a5756e93c7499b8b50e4635b56
9b5fd4ca824a6aade7ad5db600305360b93f124a
refs/heads/master
2020-04-16T08:48:48.559005
2019-01-13T02:47:14
2019-01-13T02:47:14
165,439,005
1
0
null
null
null
null
UTF-8
R
false
false
106
r
test_period_dates.R
context("Data quality for R stub") library(lubridate) test_that("stub", { expect_equal(TRUE, TRUE) })
8bba6b6da9e2d4018da75489ac71205f5eba71c8
0dac3070dd10c9329f52562cb119c5090c039fb5
/Worksheet_5/Worksheet_5.R
eee5b2320b4368cffd2157738eb68f8bcd00d83c
[]
no_license
retodomax/CompSkills
9af99150e6a50296f72a69f9c70cbdbd7ca2fbfe
1d7d1409e5240abee4269aed1864028fbd87494d
refs/heads/master
2020-09-24T05:59:19.469927
2019-12-03T23:10:44
2019-12-03T23:10:44
225,681,922
0
0
null
null
null
null
UTF-8
R
false
false
3,771
r
Worksheet_5.R
#' --- #' project: CompSkills ################################################# #' title: Homework 5 #' author: "[Reto Zihlmann](https://retodomax.github.io/)" #' date: 2019-11-19 18:40:38 #' output: github_document ############################################# #' --- # packages ---------------------------------------------------------------- library(mgcv) # Single example ---------------------------------------------------------- data <- read.table("frequency.dat") names(data) <- c("year", "freq") plot(freq ~ year, data = data, ylab = "Freqency [MHz]", ylim = c(-1000, 6000)) # Assume a true function fpl <- function(x, A = 0, B = 3000, xmid = 2003, scal = 3){ A+(B-A)/(1+exp((xmid-x)/scal)) } curve(fpl, from = 1970, to = 2020, add = T) # sample new points set.seed(1) true_value <- fpl(data$year) value <- abs(true_value + rnorm(length(true_value), mean = 0, sd = true_value/3)) points(data$year, value, col = 'green') sim_data <- data.frame(year = data$year, freq = value) # fit with GAM fit <- gam(log(freq) ~ s(year), data = sim_data) # fit with SSfpl() fit_ssfpl <- nls(freq ~ SSfpl(year, A, B, xmid, scal), data = sim_data) # plot all plot(freq ~ year, data = sim_data, ylab = "Freqency [MHz]", ylim = c(-1000, 6000)) lines(sim_data$year,exp(predict(fit)), col = "red", lwd = 2) lines(sim_data$year, predict(fit_ssfpl), col = 'green', lwd = 2) curve(fpl, lwd = 2, add = T) legend('topleft', legend = c('True model', 'GAM fit', 'FPL fit'), lwd = 2, col = c('black', 'red', 'green')) abline(v = 2008, lty = 2) abline(v = 2017, lty = 2) # question: which model is closer to true function at year = 2008 # and year = 2017 # simulation -------------------------------------------------------------- sim_diff <- function() { true_value <- fpl(data$year) value <- abs(true_value + rnorm(length(true_value), mean = 0, sd = true_value/3)) sim_data <- data.frame(year = data$year, freq = value) fit <- gam(log(freq) ~ s(year), data = sim_data) fit_ssfpl <- nls(freq ~ SSfpl(year, A, B, xmid, scal), data = sim_data) gam_pred <- unname(exp(predict(fit, newdata = list(year = c(2008, 2017))))) ssfpl_pred <- predict(fit_ssfpl, newdata = list(year = c(2008, 2017))) true_values <- fpl(c(2008, 2017)) c(gam_pred-true_values, ssfpl_pred-true_values) } ## maybe include: # - variate the number of data points (n) # (at the moment n always the number of observations in real data) # - variate the distribution of the errors # (symmetirc(normal)/nonsymetric(chisquare, lognormal), heavy tailed, # different support (only positive numbers), # discrete/count, ...) sim_diff() out <- replicate(1000, sim_diff()) out <- t(out) # plot simulation results ------------------------------------------------- plot(density(out[,1]), main = 'Difference to true function at 2008', xlim = c(-1000, 1000), ylim = c(0, 0.005), col = 'red', lwd = 2) lines(density(out[,3]), col = 'green', lwd = 2) abline(v = 0, lty = 2) legend('topleft', legend = c('True model', 'GAM fit', 'FPL fit'), lwd = 2, col = c('black', 'red', 'green')) plot(density(out[,2]), main = 'Difference to true function at 2008', xlim = c(-1000, 1000), ylim = c(0, 0.005), col = 'red', lwd = 2) lines(density(out[,4]), col = 'green', lwd = 2) abline(v = 0, lty = 2) legend('topleft', legend = c('True model', 'GAM fit', 'FPL fit'), lwd = 2, col = c('black', 'red', 'green')) ## finally evaluate # for estimator # -bias # -MSE (variance) # -distribution # for CI # -width (how wide are the CI) # -coverage (do they include the true parameter) # for curve # -point-wise (only compare at specific locations) # -integrate (AMSE: average MSE, # IMSE: integrated MSE)