content
large_stringlengths 0
6.46M
| path
large_stringlengths 3
331
| license_type
large_stringclasses 2
values | repo_name
large_stringlengths 5
125
| language
large_stringclasses 1
value | is_vendor
bool 2
classes | is_generated
bool 2
classes | length_bytes
int64 4
6.46M
| extension
large_stringclasses 75
values | text
stringlengths 0
6.46M
|
---|---|---|---|---|---|---|---|---|---|
context("test-shapley.R")
RNGversion(vstr = "3.5.0")
test_that("Basic test functions in shapley.R", {
# Load data -----------
if (requireNamespace("MASS", quietly = TRUE)) {
data("Boston", package = "MASS")
x_var <- c("lstat", "rm", "dis", "indus")
x_train <- tail(Boston[, x_var], 50)
# Load premade lm model. Path needs to be relative to testthat directory in the package
model <- readRDS("model_objects/lm_model_object.rds")
# Prepare the data for explanation
explainer <- shapr(x_train, model)
expect_known_value(explainer,
file = "test_objects/shapley_explainer_obj.rds",
update = F
)
}
})
test_that("Testing data input to shapr in shapley.R", {
if (requireNamespace("MASS", quietly = TRUE)) {
data("Boston", package = "MASS")
y_var <- "medv"
x_train <- tail(Boston, -6)
y_train <- tail(Boston[, y_var], -6)
y_train_binary <- as.factor(tail((Boston[, y_var] > 20) * 1, -6))
# convert to factors for testing purposes
x_train$rad <- factor(round(x_train$rad))
x_train$chas <- factor(round(x_train$chas))
train_df <- cbind(x_train, y_train, y_train_binary)
x_var_numeric <- c("lstat", "rm", "dis", "indus")
x_var_factor <- c("lstat", "rm", "dis", "indus", "rad", "chas")
train_df_used_numeric <- x_train[, x_var_numeric]
train_df_used_factor <- x_train[, x_var_factor]
formula_numeric <- as.formula(paste0("y_train ~ ", paste0(x_var_numeric, collapse = "+")))
formula_factor <- as.formula(paste0("y_train ~ ", paste0(x_var_factor, collapse = "+")))
formula_binary_numeric <- as.formula(paste0("y_train_binary ~ ", paste0(x_var_numeric, collapse = "+")))
formula_binary_factor <- as.formula(paste0("y_train_binary ~ ", paste0(x_var_factor, collapse = "+")))
dummylist <- make_dummies(traindata = x_train[, x_var_factor], testdata = x_train[, x_var_factor])
# List of models to run silently
l_numeric <- list(
stats::lm(formula_numeric, data = train_df),
stats::glm(formula_numeric, data = train_df)
)
if (requireNamespace("mgcv", quietly = TRUE)) {
l_numeric[[length(l_numeric) + 1]] <- mgcv::gam(formula_numeric, data = train_df)
}
l_factor <- list(
stats::lm(formula_factor, data = train_df),
stats::glm(formula_factor, data = train_df)
)
if (requireNamespace("mgcv", quietly = TRUE)) {
l_factor[[length(l_factor) + 1]] <- mgcv::gam(formula_factor, data = train_df)
}
if (requireNamespace("xgboost", quietly = TRUE)) {
l_factor[[length(l_factor) + 1]] <- xgboost::xgboost(
data = dummylist$train_dummies,
label = y_train,
nrounds = 3, verbose = FALSE
)
l_factor[[length(l_factor)]]$feature_list <- dummylist$feature_list
}
for (i in seq_along(l_numeric)) {
expect_silent(shapr(train_df_used_numeric, l_numeric[[i]])) # No modification
expect_message(shapr(train_df, l_numeric[[i]])) # Features dropped
}
for (i in seq_along(l_factor)) {
expect_silent(shapr(train_df_used_factor, l_factor[[i]])) # No modification
expect_message(shapr(train_df, l_factor[[i]])) # Features dropped
}
# Testing errors on incompatible model and data
# Missing features
model <- stats::lm(formula_factor, data = train_df)
data_error <- train_df[, -3]
expect_error(shapr(data_error, model))
# Duplicated column names
data_error <- train_df_used_factor
data_error <- cbind(data_error, lstat = 1)
expect_error(shapr(data_error, model))
# Empty column names in data
data_error <- train_df
colnames(data_error) <- NULL
expect_error(shapr(data_error, model))
# Empty column names in model (ok if found in data -- and we trust it)
if (requireNamespace("xgboost", quietly = TRUE)) {
data_with_colnames <- data_without_colnames <- as.matrix(train_df_used_numeric)
colnames(data_without_colnames) <- NULL
model_xgb <- xgboost::xgboost(
data = data_without_colnames, label = y_train,
nrounds = 3, verbose = FALSE
)
expect_message(shapr(data_with_colnames, model_xgb))
}
# Data feature with incorrect class
data_error <- train_df_used_factor
data_error$lstat <- as.logical(data_error$lstat > 15)
expect_error(shapr(data_error, model))
# non-matching factor levels
data_error <- head(train_df_used_factor)
data_error$rad <- droplevels(data_error$rad)
expect_error(shapr(data_error, model))
}
})
test_that("Basic test functions for grouping in shapley.R", {
# Load data -----------
if (requireNamespace("MASS", quietly = TRUE)) {
data("Boston", package = "MASS")
x_var <- c("lstat", "rm", "dis", "indus")
x_train <- tail(Boston[, x_var], 50)
# Load premade lm model. Path needs to be relative to testthat directory in the package
model <- readRDS("model_objects/lm_model_object.rds")
group1_num <- list(
c(1, 3),
c(2, 4)
)
group1 <- lapply(group1_num, function(x) {
x_var[x]
})
group2_num <- list(
c(1),
c(2),
c(3),
c(4)
)
group2 <- lapply(group2_num, function(x) {
x_var[x]
})
# Prepare the data for explanation
explainer1 <- shapr(x_train, model, group = group1)
explainer2 <- shapr(x_train, model, group = group2)
set.seed(123)
explainer1_2 <- shapr(x_train, model, group = group1, n_combinations = 5)
set.seed(1234)
explainer2_2 <- shapr(x_train, model, group = group2, n_combinations = 5)
expect_known_value(explainer1,
file = "test_objects/shapley_explainer_group1_obj.rds",
update = F
)
expect_known_value(explainer2,
file = "test_objects/shapley_explainer_group2_obj.rds",
update = F
)
expect_known_value(explainer1_2,
file = "test_objects/shapley_explainer_group1_2_obj.rds",
update = F
)
expect_known_value(explainer2_2,
file = "test_objects/shapley_explainer_group2_2_obj.rds",
update = F
)
}
})
test_that("Testing data input to shapr for grouping in shapley.R", {
if (requireNamespace("MASS", quietly = TRUE)) {
data("Boston", package = "MASS")
x_var <- c("lstat", "rm", "dis", "indus")
not_x_var <- "crim"
x_train <- as.matrix(tail(Boston[, x_var], -6))
xy_train <- tail(Boston, -6)
group_num <- list(
c(1, 3),
c(2, 4)
)
group <- lapply(group_num, function(x) {
x_var[x]
})
names(group) <- c("A", "B")
group_no_names <- lapply(group_num, function(x) {
x_var[x]
})
group_error_1 <- list(
c(x_var[1:2], not_x_var),
x_var[3:4]
)
group_error_2 <- list(
x_var[1],
x_var[3:4]
)
group_error_3 <- list(
x_var[c(1, 2)],
x_var[c(1, 3, 4)]
)
group_error_4 <- list(
x_var[c(1, 2)],
x_var[c(1, 3, 4)]
)
# Fitting models
formula <- as.formula(paste0("medv ~ ", paste0(x_var, collapse = "+")))
model <- stats::lm(formula = formula, data = xy_train)
# Expect silent
expect_silent(shapr(x = x_train, model = model, group = group))
# Expect message for missing names
expect_message(shapr(x = x_train, model = model, group = group_no_names))
# Expect error when group is not a list
expect_error(shapr(x_train, model, group = x_var))
# Expect error that group does not include names of features
expect_error(shapr(x = x_train, model = model, group = group_num))
# Expect error when x_train/model does not use a feature mentioned in the group
expect_error(shapr(x_train, model, group = group_error_1))
# Expect error when group does not contain a feature used by the model
expect_error(shapr(x_train, model, group = group_error_2))
# Expect error when group does duplicated features
expect_error(shapr(x_train, model, group = group_error_3))
}
})
|
/tests/testthat/test-a-shapley.R
|
permissive
|
stjordanis/shapr
|
R
| false | false | 8,013 |
r
|
context("test-shapley.R")
RNGversion(vstr = "3.5.0")
test_that("Basic test functions in shapley.R", {
# Load data -----------
if (requireNamespace("MASS", quietly = TRUE)) {
data("Boston", package = "MASS")
x_var <- c("lstat", "rm", "dis", "indus")
x_train <- tail(Boston[, x_var], 50)
# Load premade lm model. Path needs to be relative to testthat directory in the package
model <- readRDS("model_objects/lm_model_object.rds")
# Prepare the data for explanation
explainer <- shapr(x_train, model)
expect_known_value(explainer,
file = "test_objects/shapley_explainer_obj.rds",
update = F
)
}
})
test_that("Testing data input to shapr in shapley.R", {
if (requireNamespace("MASS", quietly = TRUE)) {
data("Boston", package = "MASS")
y_var <- "medv"
x_train <- tail(Boston, -6)
y_train <- tail(Boston[, y_var], -6)
y_train_binary <- as.factor(tail((Boston[, y_var] > 20) * 1, -6))
# convert to factors for testing purposes
x_train$rad <- factor(round(x_train$rad))
x_train$chas <- factor(round(x_train$chas))
train_df <- cbind(x_train, y_train, y_train_binary)
x_var_numeric <- c("lstat", "rm", "dis", "indus")
x_var_factor <- c("lstat", "rm", "dis", "indus", "rad", "chas")
train_df_used_numeric <- x_train[, x_var_numeric]
train_df_used_factor <- x_train[, x_var_factor]
formula_numeric <- as.formula(paste0("y_train ~ ", paste0(x_var_numeric, collapse = "+")))
formula_factor <- as.formula(paste0("y_train ~ ", paste0(x_var_factor, collapse = "+")))
formula_binary_numeric <- as.formula(paste0("y_train_binary ~ ", paste0(x_var_numeric, collapse = "+")))
formula_binary_factor <- as.formula(paste0("y_train_binary ~ ", paste0(x_var_factor, collapse = "+")))
dummylist <- make_dummies(traindata = x_train[, x_var_factor], testdata = x_train[, x_var_factor])
# List of models to run silently
l_numeric <- list(
stats::lm(formula_numeric, data = train_df),
stats::glm(formula_numeric, data = train_df)
)
if (requireNamespace("mgcv", quietly = TRUE)) {
l_numeric[[length(l_numeric) + 1]] <- mgcv::gam(formula_numeric, data = train_df)
}
l_factor <- list(
stats::lm(formula_factor, data = train_df),
stats::glm(formula_factor, data = train_df)
)
if (requireNamespace("mgcv", quietly = TRUE)) {
l_factor[[length(l_factor) + 1]] <- mgcv::gam(formula_factor, data = train_df)
}
if (requireNamespace("xgboost", quietly = TRUE)) {
l_factor[[length(l_factor) + 1]] <- xgboost::xgboost(
data = dummylist$train_dummies,
label = y_train,
nrounds = 3, verbose = FALSE
)
l_factor[[length(l_factor)]]$feature_list <- dummylist$feature_list
}
for (i in seq_along(l_numeric)) {
expect_silent(shapr(train_df_used_numeric, l_numeric[[i]])) # No modification
expect_message(shapr(train_df, l_numeric[[i]])) # Features dropped
}
for (i in seq_along(l_factor)) {
expect_silent(shapr(train_df_used_factor, l_factor[[i]])) # No modification
expect_message(shapr(train_df, l_factor[[i]])) # Features dropped
}
# Testing errors on incompatible model and data
# Missing features
model <- stats::lm(formula_factor, data = train_df)
data_error <- train_df[, -3]
expect_error(shapr(data_error, model))
# Duplicated column names
data_error <- train_df_used_factor
data_error <- cbind(data_error, lstat = 1)
expect_error(shapr(data_error, model))
# Empty column names in data
data_error <- train_df
colnames(data_error) <- NULL
expect_error(shapr(data_error, model))
# Empty column names in model (ok if found in data -- and we trust it)
if (requireNamespace("xgboost", quietly = TRUE)) {
data_with_colnames <- data_without_colnames <- as.matrix(train_df_used_numeric)
colnames(data_without_colnames) <- NULL
model_xgb <- xgboost::xgboost(
data = data_without_colnames, label = y_train,
nrounds = 3, verbose = FALSE
)
expect_message(shapr(data_with_colnames, model_xgb))
}
# Data feature with incorrect class
data_error <- train_df_used_factor
data_error$lstat <- as.logical(data_error$lstat > 15)
expect_error(shapr(data_error, model))
# non-matching factor levels
data_error <- head(train_df_used_factor)
data_error$rad <- droplevels(data_error$rad)
expect_error(shapr(data_error, model))
}
})
test_that("Basic test functions for grouping in shapley.R", {
# Load data -----------
if (requireNamespace("MASS", quietly = TRUE)) {
data("Boston", package = "MASS")
x_var <- c("lstat", "rm", "dis", "indus")
x_train <- tail(Boston[, x_var], 50)
# Load premade lm model. Path needs to be relative to testthat directory in the package
model <- readRDS("model_objects/lm_model_object.rds")
group1_num <- list(
c(1, 3),
c(2, 4)
)
group1 <- lapply(group1_num, function(x) {
x_var[x]
})
group2_num <- list(
c(1),
c(2),
c(3),
c(4)
)
group2 <- lapply(group2_num, function(x) {
x_var[x]
})
# Prepare the data for explanation
explainer1 <- shapr(x_train, model, group = group1)
explainer2 <- shapr(x_train, model, group = group2)
set.seed(123)
explainer1_2 <- shapr(x_train, model, group = group1, n_combinations = 5)
set.seed(1234)
explainer2_2 <- shapr(x_train, model, group = group2, n_combinations = 5)
expect_known_value(explainer1,
file = "test_objects/shapley_explainer_group1_obj.rds",
update = F
)
expect_known_value(explainer2,
file = "test_objects/shapley_explainer_group2_obj.rds",
update = F
)
expect_known_value(explainer1_2,
file = "test_objects/shapley_explainer_group1_2_obj.rds",
update = F
)
expect_known_value(explainer2_2,
file = "test_objects/shapley_explainer_group2_2_obj.rds",
update = F
)
}
})
test_that("Testing data input to shapr for grouping in shapley.R", {
if (requireNamespace("MASS", quietly = TRUE)) {
data("Boston", package = "MASS")
x_var <- c("lstat", "rm", "dis", "indus")
not_x_var <- "crim"
x_train <- as.matrix(tail(Boston[, x_var], -6))
xy_train <- tail(Boston, -6)
group_num <- list(
c(1, 3),
c(2, 4)
)
group <- lapply(group_num, function(x) {
x_var[x]
})
names(group) <- c("A", "B")
group_no_names <- lapply(group_num, function(x) {
x_var[x]
})
group_error_1 <- list(
c(x_var[1:2], not_x_var),
x_var[3:4]
)
group_error_2 <- list(
x_var[1],
x_var[3:4]
)
group_error_3 <- list(
x_var[c(1, 2)],
x_var[c(1, 3, 4)]
)
group_error_4 <- list(
x_var[c(1, 2)],
x_var[c(1, 3, 4)]
)
# Fitting models
formula <- as.formula(paste0("medv ~ ", paste0(x_var, collapse = "+")))
model <- stats::lm(formula = formula, data = xy_train)
# Expect silent
expect_silent(shapr(x = x_train, model = model, group = group))
# Expect message for missing names
expect_message(shapr(x = x_train, model = model, group = group_no_names))
# Expect error when group is not a list
expect_error(shapr(x_train, model, group = x_var))
# Expect error that group does not include names of features
expect_error(shapr(x = x_train, model = model, group = group_num))
# Expect error when x_train/model does not use a feature mentioned in the group
expect_error(shapr(x_train, model, group = group_error_1))
# Expect error when group does not contain a feature used by the model
expect_error(shapr(x_train, model, group = group_error_2))
# Expect error when group does duplicated features
expect_error(shapr(x_train, model, group = group_error_3))
}
})
|
#### Получение информации о пользователе сети ВКонтакте.
library(RCurl)
library(rjson)
# Параметры доступа
access_token <- "ключ_доступа_вашего_приложения"
ver <- "5.53"
# Идентификатор пользователя
uid <- "идентификатор_пользователя"
# Функция запроса к API
vk <- function( method, params ) {
if( !missing(params) ){
params <- sprintf( "?%s", paste( names(params), "=",
unlist(params), collapse = "&", sep = "" ) )
} else {
params <- ""
}
url <- sprintf( "https://api.vk.com/method/%s%s&access_token=%s&v=%s",
method, params, access_token, ver )
data <- getURL(url)
tryCatch({
list <- fromJSON( data )
}, error = function (e) {
print(data)
stop(e)
})
list$response
}
# Список сообществ (групп и пабликов) с описанием.
params <- list(user_id = uid, extended = 1, fields = "description")
groups <- vk( "groups.get", params )
# Список подписок (пабликов и пользователей) с описанием.
params <- list(user_id = uid, extended = 1, fields = "description")
subscriptions <- vk( "users.getSubscriptions", params )
# Список подписчиков
# (часть из них может быть забанена или деактивирована)
params <- list(user_id = uid, fields = "last_name")
followers <- vk( "users.getFollowers", params )
|
/Сбор данных в интернете/18/02-user_info.R
|
no_license
|
kn7072/R
|
R
| false | false | 1,599 |
r
|
#### Получение информации о пользователе сети ВКонтакте.
library(RCurl)
library(rjson)
# Параметры доступа
access_token <- "ключ_доступа_вашего_приложения"
ver <- "5.53"
# Идентификатор пользователя
uid <- "идентификатор_пользователя"
# Функция запроса к API
vk <- function( method, params ) {
if( !missing(params) ){
params <- sprintf( "?%s", paste( names(params), "=",
unlist(params), collapse = "&", sep = "" ) )
} else {
params <- ""
}
url <- sprintf( "https://api.vk.com/method/%s%s&access_token=%s&v=%s",
method, params, access_token, ver )
data <- getURL(url)
tryCatch({
list <- fromJSON( data )
}, error = function (e) {
print(data)
stop(e)
})
list$response
}
# Список сообществ (групп и пабликов) с описанием.
params <- list(user_id = uid, extended = 1, fields = "description")
groups <- vk( "groups.get", params )
# Список подписок (пабликов и пользователей) с описанием.
params <- list(user_id = uid, extended = 1, fields = "description")
subscriptions <- vk( "users.getSubscriptions", params )
# Список подписчиков
# (часть из них может быть забанена или деактивирована)
params <- list(user_id = uid, fields = "last_name")
followers <- vk( "users.getFollowers", params )
|
############## data preparing for Brandon
install.packages("sqldf")
library(sqldf)
s01 <- sqldf("select pdbid, chainid from protein_annotate_onlysnp group by UniProtID")
write.table(s01, file = "unique_pdb.txt", quote = F, row.names = F)
# get uniprot with disease snp in binding site
uniprot_bs_ds <- sqldf('select UniProtID from protein_annotate_onlysnp where VarType = "Disease" and location = "Binding Site" group by UniProtID')
with(subset(protein_annotate_onlysnp, VarType == "Disease"), table(factor(UniProtID), location))
# odds ratio for each uniprot
odds_ratio_stat <- function(p_annotate, vartype){
table_res <- table(data.frame(location = deal_with_na(subset(p_annotate, location %in% c("Surface", "Binding Site"))$VarType == vartype),
Disease = deal_with_na(subset(p_annotate, location %in% c("Surface", "Binding Site"))$location == "Surface")))
#table_res <- apply(table_res, 1:2, as.numeric)
# rownames(table_res) <- c(paste("Not", vartype), vartype)
#colnames(table_res) <- c("Binding Site", "Surface")
#print(table_res)
fisher.test(table_res)
}
snp_uniprot = ddply(subset(protein_annotate_withsnp, UniProtID %in% uniprot_bs_ds[,1]), .(UniProtID), summarise, pvalue = odds_ratio_stat(data.frame(location = location, VarType = VarType), "Disease")$p.value, oddsratio = 1/ odds_ratio_stat(data.frame(location = location, VarType = VarType), "Disease")$estimate)
snp_uniprot[order(snp_uniprot$pvalue),]
# test whether this is right
with(subset(protein_annotate_withsnp, UniProtID == "P01112"), table(location, VarType))
VarType
location Disease Polymorphism Unclassified
Binding Site 16 0 2
Core 0 0 0
Surface 1 0 0
with(subset(protein_annotate_withsnp, UniProtID == "P38398"), table(location, VarType))
VarType
location Disease Polymorphism Unclassified
Binding Site 4 0 2
Core 2 3 15
Surface 0 1 22
# top 40
snp_uniprot_t40 <- snp_uniprot[order(snp_uniprot$pvalue),][1:40,]
#
s01 <- sqldf("select pdbid, chainid, snp_uniprot_t40.UniProtID, snp_uniprot_t40.pvalue from protein_annotate_withsnp inner join snp_uniprot_t40 on protein_annotate_withsnp.UniProtID = snp_uniprot_t40.UniProtID group by protein_annotate_withsnp.UniProtID")
write.table(s01, file = "top_40_pdb.txt", quote = F, row.names = F)
|
/Analysis/brandon.R
|
permissive
|
ajing/SIFTS.py
|
R
| false | false | 2,464 |
r
|
############## data preparing for Brandon
install.packages("sqldf")
library(sqldf)
s01 <- sqldf("select pdbid, chainid from protein_annotate_onlysnp group by UniProtID")
write.table(s01, file = "unique_pdb.txt", quote = F, row.names = F)
# get uniprot with disease snp in binding site
uniprot_bs_ds <- sqldf('select UniProtID from protein_annotate_onlysnp where VarType = "Disease" and location = "Binding Site" group by UniProtID')
with(subset(protein_annotate_onlysnp, VarType == "Disease"), table(factor(UniProtID), location))
# odds ratio for each uniprot
odds_ratio_stat <- function(p_annotate, vartype){
table_res <- table(data.frame(location = deal_with_na(subset(p_annotate, location %in% c("Surface", "Binding Site"))$VarType == vartype),
Disease = deal_with_na(subset(p_annotate, location %in% c("Surface", "Binding Site"))$location == "Surface")))
#table_res <- apply(table_res, 1:2, as.numeric)
# rownames(table_res) <- c(paste("Not", vartype), vartype)
#colnames(table_res) <- c("Binding Site", "Surface")
#print(table_res)
fisher.test(table_res)
}
snp_uniprot = ddply(subset(protein_annotate_withsnp, UniProtID %in% uniprot_bs_ds[,1]), .(UniProtID), summarise, pvalue = odds_ratio_stat(data.frame(location = location, VarType = VarType), "Disease")$p.value, oddsratio = 1/ odds_ratio_stat(data.frame(location = location, VarType = VarType), "Disease")$estimate)
snp_uniprot[order(snp_uniprot$pvalue),]
# test whether this is right
with(subset(protein_annotate_withsnp, UniProtID == "P01112"), table(location, VarType))
VarType
location Disease Polymorphism Unclassified
Binding Site 16 0 2
Core 0 0 0
Surface 1 0 0
with(subset(protein_annotate_withsnp, UniProtID == "P38398"), table(location, VarType))
VarType
location Disease Polymorphism Unclassified
Binding Site 4 0 2
Core 2 3 15
Surface 0 1 22
# top 40
snp_uniprot_t40 <- snp_uniprot[order(snp_uniprot$pvalue),][1:40,]
#
s01 <- sqldf("select pdbid, chainid, snp_uniprot_t40.UniProtID, snp_uniprot_t40.pvalue from protein_annotate_withsnp inner join snp_uniprot_t40 on protein_annotate_withsnp.UniProtID = snp_uniprot_t40.UniProtID group by protein_annotate_withsnp.UniProtID")
write.table(s01, file = "top_40_pdb.txt", quote = F, row.names = F)
|
library(ape)
testtree <- read.tree("1177_2.txt")
unrooted_tr <- unroot(testtree)
write.tree(unrooted_tr, file="1177_2_unrooted.txt")
|
/codeml_files/newick_trees_processed/1177_2/rinput.R
|
no_license
|
DaniBoo/cyanobacteria_project
|
R
| false | false | 135 |
r
|
library(ape)
testtree <- read.tree("1177_2.txt")
unrooted_tr <- unroot(testtree)
write.tree(unrooted_tr, file="1177_2_unrooted.txt")
|
library(ape)
testtree <- read.tree("7705_0.txt")
unrooted_tr <- unroot(testtree)
write.tree(unrooted_tr, file="7705_0_unrooted.txt")
|
/codeml_files/newick_trees_processed/7705_0/rinput.R
|
no_license
|
DaniBoo/cyanobacteria_project
|
R
| false | false | 135 |
r
|
library(ape)
testtree <- read.tree("7705_0.txt")
unrooted_tr <- unroot(testtree)
write.tree(unrooted_tr, file="7705_0_unrooted.txt")
|
rm(list=ls())
library(dplyr)
library(tidyr)
library(ggplot2)
library(testthat)
library(bbmle)
library(lme4)
library(readxl)
options(stringsAsFactors = F)
source("analysis/format_data/format_scripts.R")
source("analysis/format_data/format_functions.R")
# data
lupine_df <- read.csv( "data/lupine_all.csv")
enso <- read.csv( "data/enso_data.csv")
clim <- read.csv( "data/prism_point_reyes_87_18.csv")
fruit_rac <- read_xlsx('data/fruits_per_raceme.xlsx')
seed_x_fr <- read_xlsx('data/seedsperfruit.xlsx')
germ <- read_xlsx('data/seedbaskets.xlsx')
# data format --------------------------------------------------------------
fert <- subset(lupine_df, flow_t0 == 1 ) %>%
subset( area_t0 != 0) %>%
subset( !is.na(numrac_t0) ) %>%
# remove non-flowering individuals
subset( !(flow_t0 %in% 0) ) %>%
mutate( log_area_t0 = log_area_t0_z,
log_area_t02 = log_area_t0_z^2 ) %>%
# remove zero fertility (becase fertility should not be 0)
# NOTE: in many cases, notab_t1 == 0, because numab_t1 == 0 also
subset( !(numrac_t0 %in% 0) )
# climate format ----------------------------------------------------------------
years <- 1990:2018 #unique(fert$year)
m_obs <- 5
m_back <- 36
# calculate yearly anomalies from monthly anomalies
year_m_anom <- function(x, var ){
# set names of climate variables
clim_names <- paste0( var,c('_t0','_tm1','_t0_tm1','_t0_tm2') )
mutate(x,
avgt0 = x %>% select(V1:V12) %>% rowSums,
avgtm1 = x %>% select(V13:V24) %>% rowSums,
avgt0_tm1 = x %>% select(V1:V24) %>% rowSums,
avgt0_tm2 = x %>% select(V1:V36) %>% rowSums ) %>%
select(year, avgt0, avgtm1, avgt0_tm1, avgt0_tm2) %>%
setNames( c('year',clim_names) )
}
# calculate yearly anomalies
year_anom <- function(clim_x, clim_var = "ppt",
years, m_back, m_obs ){
# "spread" the 12 months
clim_m <- select(clim_x, -clim_var )
# select temporal extent
clim_back <- function(yrz, m_obs, dat){
id <- which(dat$year == yrz & dat$month_num == m_obs)
r <- c( id:(id - (m_back-1)) )
return(dat[r,"clim_value"])
}
# climate data in matrix form
year_by_month_mat <- function(dat, years){
do.call(rbind, dat) %>%
as.data.frame %>%
tibble::add_column(year = years, .before=1)
}
# calculate monthly precipitation values
clim_x_l <- lapply(years, clim_back, m_obs, clim_m)
x_clim <- year_by_month_mat(clim_x_l, years) %>%
gather(month,t0,V1:V12) %>%
select(year,month,t0) %>%
mutate( month = gsub('V','',month) ) %>%
mutate( month = as.numeric(month) )
if( clim_var == 'ppt'){
raw_df <- x_clim %>%
group_by(year) %>%
summarise( ppt_t0 = sum(t0) ) %>%
ungroup %>%
arrange( year ) %>%
mutate( ppt_t0 = scale(ppt_t0)[,1] ) %>%
mutate( ppt_tm1 = lag(ppt_t0) )
}
if( clim_var == 'tmp'){
raw_df <- x_clim %>%
group_by(year) %>%
summarise( tmp_t0 = mean(t0) ) %>%
ungroup %>%
arrange( year ) %>%
mutate( tmp_t0 = scale(tmp_t0)[,1] ) %>%
mutate( tmp_tm1 = lag(tmp_t0) )
}
raw_df
}
# format climate - need to select climate predictor first
ppt_mat <- subset(clim, clim_var == "ppt") %>%
year_anom("ppt", years, m_back, m_obs) #%>%
# prism_clim_form("precip", years, m_back, m_obs) %>%
# year_anom('ppt')
tmp_mat <- subset(clim, clim_var == 'tmean') %>%
year_anom("tmp", years, m_back, m_obs)
# prism_clim_form('tmean', years, m_back, m_obs) %>%
# year_anom('tmp')
enso_mat <- subset(enso, clim_var == 'oni' ) %>%
month_clim_form('oni', years, m_back, m_obs) %>%
year_m_anom('oni')
spei_mat <- subset(clim, clim_var == 'spei' ) %>%
spei_clim_form(years, m_back, m_obs) %>%
year_m_anom('spei')
# put together all climate
clim_mat <- Reduce( function(...) full_join(...),
list(ppt_mat, tmp_mat, enso_mat, spei_mat) )
# demography plus clim
fert_clim <- left_join(fert, clim_mat) %>%
subset( !is.na(location) )
# climate model selection ---------------------------------------
climate_mods <- list(
# null
numrac_t0 ~ log_area_t0 + log_area_t02 + (log_area_t0 | year) + (log_area_t0 | location),
# precipitation
numrac_t0 ~ log_area_t0 + log_area_t02 + ppt_t0 + (log_area_t0 | year) + (log_area_t0 | location),
numrac_t0 ~ log_area_t0 + log_area_t02 + ppt_tm1 + (log_area_t0 | year) + (log_area_t0 | location),
# temperature
numrac_t0 ~ log_area_t0 + log_area_t02 + tmp_t0 + (log_area_t0 | year) + (log_area_t0 | location),
numrac_t0 ~ log_area_t0 + log_area_t02 + tmp_tm1 + (log_area_t0 | year) + (log_area_t0 | location),
# enso
numrac_t0 ~ log_area_t0 + log_area_t02 + oni_t0 + (log_area_t0 | year) + (log_area_t0 | location),
numrac_t0 ~ log_area_t0 + log_area_t02 + oni_tm1 + (log_area_t0 | year) + (log_area_t0 | location),
# spei
numrac_t0 ~ log_area_t0 + log_area_t02 + spei_t0 + (log_area_t0 | year) + (log_area_t0 | location),
numrac_t0 ~ log_area_t0 + log_area_t02 + spei_tm1 + (log_area_t0 | year) + (log_area_t0 | location)
)
# years to do crossvalidation on
years_cv <- unique(fert_clim$year)
mod_nam <- c( 'null',
'ppt_t0', 'ppt_tm1',
'tmp_t0', 'tmp_tm1',
'oni_t0', 'oni_tm1',
'spei_to', 'spei_tm1' )
# function to carry out crossvalidation
crossval <- function(yr_ii){ #length(years_cv)
# set up dataframes to train and test year-specific predictions
train_df <- subset(fert_clim, !(year %in% yr_ii ) )
test_df <- subset(fert_clim, year == yr_ii ) %>%
mutate( resp = numrac_t0 )
# fit all models
mods_clim <- lapply( climate_mods,
function(x) glmer(x,
data=train_df,
family='poisson') )
pred_df <- list()
for(ii in 1:length(mods_clim)){
mod_nam <- c( 'null',
'ppt_t0', 'ppt_tm1',
'tmp_t0', 'tmp_tm1',
'oni_t0', 'oni_tm1',
'spei_to', 'spei_tm1' )
pred_df[[ii]] <- test_df %>%
# calculate predictions
mutate( pred = predict( mods_clim[[ii]],
newdata = test_df,
type = 'response',
re.form = NA )
) %>%
select( year, pred, resp ) %>%
mutate( model = mod_nam[ii] )
}
pred_df %>% bind_rows
}
# detect cores
cores <- (detectCores() - 1)
# set up as many clusters as detected by 'detectCores()'
cluster <- parallel::makePSOCKcluster(cores)
# attach packages that will be needed on each cluster
clusterEvalQ(cluster, list(library(lme4), library(boot),
library(dplyr) , library(tidyr)) )
# attach objects that will be needed on each cluster
clusterExport(cluster, c('fert_clim', 'climate_mods') )
# Fit 5 alternative models on 200 bootstrapped samples
init_t <- Sys.time()
boostr_par_l <- parLapply(cluster, years_cv, crossval)
Sys.time() - init_t
# get scores
score_df <- boostr_par_l %>%
bind_rows %>%
# calculate negative log likelihood and Squared Error
mutate( log_lik = dpois(x = resp,
lambda = pred,
log = T ) * -1 ) %>%
mutate( se = (resp - pred)^2 ) %>%
group_by( model ) %>%
# sum of neg_log_lik/ root mean squared error
summarise( log_lik_sum = sum(log_lik),
rmse = mean(se) %>% sqrt ) %>%
ungroup %>%
as.data.frame()
# logarithmic score
score_df %>%
arrange( log_lik_sum ) %>%
select( -rmse ) %>%
mutate( dScore = log_lik_sum - log_lik_sum[1] ) %>%
write.csv('results/vital_rates/crossval/fert_cv_logscore.csv',
row.names=F)
# root mean squared error
score_df %>%
arrange( rmse ) %>%
select( -log_lik_sum ) %>%
mutate( dScore = rmse - rmse[1] ) %>%
write.csv('results/vital_rates/crossval/fert_cv_rmse.csv',
row.names=F)
|
/analysis/vital_rates/crossvalidation/fert_cv_t0.R
|
no_license
|
AldoCompagnoni/lupine
|
R
| false | false | 8,895 |
r
|
rm(list=ls())
library(dplyr)
library(tidyr)
library(ggplot2)
library(testthat)
library(bbmle)
library(lme4)
library(readxl)
options(stringsAsFactors = F)
source("analysis/format_data/format_scripts.R")
source("analysis/format_data/format_functions.R")
# data
lupine_df <- read.csv( "data/lupine_all.csv")
enso <- read.csv( "data/enso_data.csv")
clim <- read.csv( "data/prism_point_reyes_87_18.csv")
fruit_rac <- read_xlsx('data/fruits_per_raceme.xlsx')
seed_x_fr <- read_xlsx('data/seedsperfruit.xlsx')
germ <- read_xlsx('data/seedbaskets.xlsx')
# data format --------------------------------------------------------------
fert <- subset(lupine_df, flow_t0 == 1 ) %>%
subset( area_t0 != 0) %>%
subset( !is.na(numrac_t0) ) %>%
# remove non-flowering individuals
subset( !(flow_t0 %in% 0) ) %>%
mutate( log_area_t0 = log_area_t0_z,
log_area_t02 = log_area_t0_z^2 ) %>%
# remove zero fertility (becase fertility should not be 0)
# NOTE: in many cases, notab_t1 == 0, because numab_t1 == 0 also
subset( !(numrac_t0 %in% 0) )
# climate format ----------------------------------------------------------------
years <- 1990:2018 #unique(fert$year)
m_obs <- 5
m_back <- 36
# calculate yearly anomalies from monthly anomalies
year_m_anom <- function(x, var ){
# set names of climate variables
clim_names <- paste0( var,c('_t0','_tm1','_t0_tm1','_t0_tm2') )
mutate(x,
avgt0 = x %>% select(V1:V12) %>% rowSums,
avgtm1 = x %>% select(V13:V24) %>% rowSums,
avgt0_tm1 = x %>% select(V1:V24) %>% rowSums,
avgt0_tm2 = x %>% select(V1:V36) %>% rowSums ) %>%
select(year, avgt0, avgtm1, avgt0_tm1, avgt0_tm2) %>%
setNames( c('year',clim_names) )
}
# calculate yearly anomalies
year_anom <- function(clim_x, clim_var = "ppt",
years, m_back, m_obs ){
# "spread" the 12 months
clim_m <- select(clim_x, -clim_var )
# select temporal extent
clim_back <- function(yrz, m_obs, dat){
id <- which(dat$year == yrz & dat$month_num == m_obs)
r <- c( id:(id - (m_back-1)) )
return(dat[r,"clim_value"])
}
# climate data in matrix form
year_by_month_mat <- function(dat, years){
do.call(rbind, dat) %>%
as.data.frame %>%
tibble::add_column(year = years, .before=1)
}
# calculate monthly precipitation values
clim_x_l <- lapply(years, clim_back, m_obs, clim_m)
x_clim <- year_by_month_mat(clim_x_l, years) %>%
gather(month,t0,V1:V12) %>%
select(year,month,t0) %>%
mutate( month = gsub('V','',month) ) %>%
mutate( month = as.numeric(month) )
if( clim_var == 'ppt'){
raw_df <- x_clim %>%
group_by(year) %>%
summarise( ppt_t0 = sum(t0) ) %>%
ungroup %>%
arrange( year ) %>%
mutate( ppt_t0 = scale(ppt_t0)[,1] ) %>%
mutate( ppt_tm1 = lag(ppt_t0) )
}
if( clim_var == 'tmp'){
raw_df <- x_clim %>%
group_by(year) %>%
summarise( tmp_t0 = mean(t0) ) %>%
ungroup %>%
arrange( year ) %>%
mutate( tmp_t0 = scale(tmp_t0)[,1] ) %>%
mutate( tmp_tm1 = lag(tmp_t0) )
}
raw_df
}
# format climate - need to select climate predictor first
ppt_mat <- subset(clim, clim_var == "ppt") %>%
year_anom("ppt", years, m_back, m_obs) #%>%
# prism_clim_form("precip", years, m_back, m_obs) %>%
# year_anom('ppt')
tmp_mat <- subset(clim, clim_var == 'tmean') %>%
year_anom("tmp", years, m_back, m_obs)
# prism_clim_form('tmean', years, m_back, m_obs) %>%
# year_anom('tmp')
enso_mat <- subset(enso, clim_var == 'oni' ) %>%
month_clim_form('oni', years, m_back, m_obs) %>%
year_m_anom('oni')
spei_mat <- subset(clim, clim_var == 'spei' ) %>%
spei_clim_form(years, m_back, m_obs) %>%
year_m_anom('spei')
# put together all climate
clim_mat <- Reduce( function(...) full_join(...),
list(ppt_mat, tmp_mat, enso_mat, spei_mat) )
# demography plus clim
fert_clim <- left_join(fert, clim_mat) %>%
subset( !is.na(location) )
# climate model selection ---------------------------------------
climate_mods <- list(
# null
numrac_t0 ~ log_area_t0 + log_area_t02 + (log_area_t0 | year) + (log_area_t0 | location),
# precipitation
numrac_t0 ~ log_area_t0 + log_area_t02 + ppt_t0 + (log_area_t0 | year) + (log_area_t0 | location),
numrac_t0 ~ log_area_t0 + log_area_t02 + ppt_tm1 + (log_area_t0 | year) + (log_area_t0 | location),
# temperature
numrac_t0 ~ log_area_t0 + log_area_t02 + tmp_t0 + (log_area_t0 | year) + (log_area_t0 | location),
numrac_t0 ~ log_area_t0 + log_area_t02 + tmp_tm1 + (log_area_t0 | year) + (log_area_t0 | location),
# enso
numrac_t0 ~ log_area_t0 + log_area_t02 + oni_t0 + (log_area_t0 | year) + (log_area_t0 | location),
numrac_t0 ~ log_area_t0 + log_area_t02 + oni_tm1 + (log_area_t0 | year) + (log_area_t0 | location),
# spei
numrac_t0 ~ log_area_t0 + log_area_t02 + spei_t0 + (log_area_t0 | year) + (log_area_t0 | location),
numrac_t0 ~ log_area_t0 + log_area_t02 + spei_tm1 + (log_area_t0 | year) + (log_area_t0 | location)
)
# years to do crossvalidation on
years_cv <- unique(fert_clim$year)
mod_nam <- c( 'null',
'ppt_t0', 'ppt_tm1',
'tmp_t0', 'tmp_tm1',
'oni_t0', 'oni_tm1',
'spei_to', 'spei_tm1' )
# function to carry out crossvalidation
crossval <- function(yr_ii){ #length(years_cv)
# set up dataframes to train and test year-specific predictions
train_df <- subset(fert_clim, !(year %in% yr_ii ) )
test_df <- subset(fert_clim, year == yr_ii ) %>%
mutate( resp = numrac_t0 )
# fit all models
mods_clim <- lapply( climate_mods,
function(x) glmer(x,
data=train_df,
family='poisson') )
pred_df <- list()
for(ii in 1:length(mods_clim)){
mod_nam <- c( 'null',
'ppt_t0', 'ppt_tm1',
'tmp_t0', 'tmp_tm1',
'oni_t0', 'oni_tm1',
'spei_to', 'spei_tm1' )
pred_df[[ii]] <- test_df %>%
# calculate predictions
mutate( pred = predict( mods_clim[[ii]],
newdata = test_df,
type = 'response',
re.form = NA )
) %>%
select( year, pred, resp ) %>%
mutate( model = mod_nam[ii] )
}
pred_df %>% bind_rows
}
# detect cores
cores <- (detectCores() - 1)
# set up as many clusters as detected by 'detectCores()'
cluster <- parallel::makePSOCKcluster(cores)
# attach packages that will be needed on each cluster
clusterEvalQ(cluster, list(library(lme4), library(boot),
library(dplyr) , library(tidyr)) )
# attach objects that will be needed on each cluster
clusterExport(cluster, c('fert_clim', 'climate_mods') )
# Fit 5 alternative models on 200 bootstrapped samples
init_t <- Sys.time()
boostr_par_l <- parLapply(cluster, years_cv, crossval)
Sys.time() - init_t
# get scores
score_df <- boostr_par_l %>%
bind_rows %>%
# calculate negative log likelihood and Squared Error
mutate( log_lik = dpois(x = resp,
lambda = pred,
log = T ) * -1 ) %>%
mutate( se = (resp - pred)^2 ) %>%
group_by( model ) %>%
# sum of neg_log_lik/ root mean squared error
summarise( log_lik_sum = sum(log_lik),
rmse = mean(se) %>% sqrt ) %>%
ungroup %>%
as.data.frame()
# logarithmic score
score_df %>%
arrange( log_lik_sum ) %>%
select( -rmse ) %>%
mutate( dScore = log_lik_sum - log_lik_sum[1] ) %>%
write.csv('results/vital_rates/crossval/fert_cv_logscore.csv',
row.names=F)
# root mean squared error
score_df %>%
arrange( rmse ) %>%
select( -log_lik_sum ) %>%
mutate( dScore = rmse - rmse[1] ) %>%
write.csv('results/vital_rates/crossval/fert_cv_rmse.csv',
row.names=F)
|
source("utility.R")
require(Hmisc) # for inc function
TrainMarkov <- function(text, lookup) {
## Creates the transition probability matrix, T[i,j] is the number
## of times word j follows word i. No need to standardize since
## all functions that use T will implicity standardize
N <- length(lookup)
T <- matrix(0, N, N)
for(i in 2:length(text)) {
inc(T[text[i - 1], text[i]]) <- 1
}
return(T)
}
SampleMarkov <- function(T, len, start) {
## Samples a sequence of length len from the Markov Chain
## described by transition matrix T, starting with start.
N <- nrow(T)
out <- rep(NA, len)
out[1] <- start
for(i in 2:len) {
out[i] <- sample(1:N, 1, replace = FALSE, prob = T[out[i-1], ])
}
return(out)
}
|
/markov.R
|
no_license
|
tpospisi/RObama
|
R
| false | false | 798 |
r
|
source("utility.R")
require(Hmisc) # for inc function
TrainMarkov <- function(text, lookup) {
## Creates the transition probability matrix, T[i,j] is the number
## of times word j follows word i. No need to standardize since
## all functions that use T will implicity standardize
N <- length(lookup)
T <- matrix(0, N, N)
for(i in 2:length(text)) {
inc(T[text[i - 1], text[i]]) <- 1
}
return(T)
}
SampleMarkov <- function(T, len, start) {
## Samples a sequence of length len from the Markov Chain
## described by transition matrix T, starting with start.
N <- nrow(T)
out <- rep(NA, len)
out[1] <- start
for(i in 2:len) {
out[i] <- sample(1:N, 1, replace = FALSE, prob = T[out[i-1], ])
}
return(out)
}
|
#####################################################################
# Directory :
# Program Name: OLS_specification.R
# Analyst : Paul Laskowski
# Last Updated: 4/3/2015
#
# Purpose:
# OLS Specification
#####################################################################
#####################################################################
# Setup
setwd("~/Desktop/data_w203")
getwd()
#####################################################################
# Load Libraries
library(car)
library(lmtest)
library(sandwich)
#####################################################################
# Analysis of baseball data.
# We look at the wage dataset to demonstrate heteroskedasticity
load("mlb1.rdata")
ls()
# desc includes descriptions of each variable
desc
# data contains the data itself.
summary(data)
# Examine the salary variable
summary(data$salary)
hist(data$salary, breaks= 200)
# This is a highly skewed distribution with a notable spike at the
# minimum value. Check out a few of the smallest values of salary
head(sort(data$salary), 50)
# It turns out that the minimum mlb salary, set by negotions
# with the MLB players association was $109,000 in 1993. This
# corresponds to the minimum value we see.
# we can also examine the log of salary
hist(log10(data$salary), breaks= 100)
# Interestingly, the distribution is not very normal and looks
# almost uniform. It could be that the minimum salary is set high
# enough to distort the usual salary distribution that we expect
# to find.
# Examine years and games per year variables
summary(data$years)
hist(data$years, breaks = 20)
summary(data$gamesyr)
hist(data$gamesyr, breaks = 100)
# both have no missing values and distributions look reasonable.
# Examine batting average
hist(data$bavg, breaks=100)
# According to baseball-almanac.com, the record for highest season
# batting average was set by Hugh Duffy at .440.
# We may be suspicious of the two outlying values.
data[data$bavg > 400,]
# Notice that these players have very few at bats, 7 and 8. The mean
# number of at bats is 2,169.
summary(data$atbats)
head(sort(data$atbats), 50)
# It seems that these players got lucky due to how few chances
# they had at bat. The values are meaningful, though we expect
# a lot of extra variation in our x-variable.
# Notive that there are similar outliers in the negative direction as well
data[data$bavg < 150,]
# We could fit a much more complicated model to account for this
# effect, but that's beyond the scope of this course.
# A simpler idea is to mitigate the problem by removing players who
# have few chances to bat.
# To be eligible for the MLB batting title, players must
# have at least 3.1 at bats per team game originally scheduled, or
# approximately 500 at bats.
# Our dataset has 73 players with less than 500 at bats
sum(data$atbats<500)
# We proceed without these players.
mlb = data[data$atbats>=500,]
summary(mlb)
nrow(mlb)
# We are left with 280 players
# Examine home runs per year and runs batted per year
summary(mlb$hrunsyr, breaks=100)
hist(mlb$hrunsyr, breaks=100)
summary(mlb$rbisyr, breaks = 100)
hist(mlb$rbisyr, breaks = 100)
# Both of these have no missing values and the distributions
# have no suspicious artifacts.
# Our full model predicts salary based on years, games per year,
# and then three performance metrics: batting average, runs batted per
# year, and home runs per year.
model1 = lm(log(salary)~ years + gamesyr + bavg + hrunsyr + rbisyr, data = mlb)
plot(model1)
# Note the evidence of heteroskedasticity in the residuals vs. fitted
# values plot and in the scale-location plot.
# We now examine the coefficients.
coeftest(model1, vcov = vcovHC)
# Out of our three performance metrics, only batting average has a significant
# effect.
# We could recreate the output in Wooldridge by putting in the full data
# including players with few at bats
model_wooldridge = lm(log(salary)~ years + gamesyr + bavg + hrunsyr + rbisyr, data = data)
plot(model_wooldridge)
# notice the outlying points in the residuals vs leverage plot with high
# leverage. These have small residuals, however, meaning that they don't
# affect our coefficients very much. In particular, a general rule is
# that a cook's distance of 1 represents a worrysome amount of influence,
# and none of our datapoints are close.
coeftest(model_wooldridge, vcov = vcovHC)
# Here, the extra variation in bavg is acting like measurement error.
# Thus, it is little surprise that we lose statistical significance,
# even though we're adding more data.
##### Joint Hypothesis Testing
# We want to test whether the three performance indicators are jointly
# significant. That is, whether the coefficients for bavg, hrunsyr, and
# rbisyr are all zero.
# Our restricted model is formed by removign the performance indivators
model_rest = lm(log(salary)~ years + gamesyr, data = mlb)
coeftest(model_rest, vcov = vcovHC)
# To test whether the difference in fit is significant, we use the wald test,
# which generalizes the usual F-test of overall significance,
# but allows for a heteroskedasticity-robust covariance matrix
waldtest(model1, model_rest, vcov = vcovHC)
# Another useful command is linearHypothesis, which allows us
# to write the hypothesis we're testing clearly in string form.
linearHypothesis(model1, c("bavg = 0", "hrunsyr = 0", "rbisyr = 0"), vcov = vcovHC)
# In this case, the three performance indicators are jointly significant.
# There is probably a great deal of multicollinearity, which explains
# why in Wooldridge's specification, none of their coefficients is
# individually significant.
#### Testing whether coefficients are different
# One question is whether a hit and a walk affect salary by
# the same amount. We write an alternate specification as follows:
model2 = lm(log(salary)~ years + gamesyr + hits + bb, data = mlb)
coeftest(model2, vcov = vcovHC)
# Our hypothesis is that the coefficients for hits and bb (walks)
# are the same.
# We can test this manually by creating a new variable to equal the total
# hits_plus_walks.
mlb$hits_plus_walks = mlb$hits + mlb$bb
# We then put this variable into our model along with hits (how many
# of the total are hits). The coefficient for hits will then measure
# the difference between the effects of hits and walks.
model3 = lm(log(salary)~ years + gamesyr + hits + hits_plus_walks, data = mlb)
coeftest(model3, vcov = vcovHC)
# The coefficient is insignificant - we did not find evidence
# that hits and walks affect salary differently.
# We could also use linearHypothesis to do the same thing, in an
# even clearer way
linearHypothesis(model2, "hits = bb", vcov = vcovHC)
# Notice that we get the same p-value as before.
|
/Async/Week 13/OLS_specification.R
|
no_license
|
shanbrianhe/W203-Statistics-for-Data-Science
|
R
| false | false | 6,725 |
r
|
#####################################################################
# Directory :
# Program Name: OLS_specification.R
# Analyst : Paul Laskowski
# Last Updated: 4/3/2015
#
# Purpose:
# OLS Specification
#####################################################################
#####################################################################
# Setup
setwd("~/Desktop/data_w203")
getwd()
#####################################################################
# Load Libraries
library(car)
library(lmtest)
library(sandwich)
#####################################################################
# Analysis of baseball data.
# We look at the wage dataset to demonstrate heteroskedasticity
load("mlb1.rdata")
ls()
# desc includes descriptions of each variable
desc
# data contains the data itself.
summary(data)
# Examine the salary variable
summary(data$salary)
hist(data$salary, breaks= 200)
# This is a highly skewed distribution with a notable spike at the
# minimum value. Check out a few of the smallest values of salary
head(sort(data$salary), 50)
# It turns out that the minimum mlb salary, set by negotions
# with the MLB players association was $109,000 in 1993. This
# corresponds to the minimum value we see.
# we can also examine the log of salary
hist(log10(data$salary), breaks= 100)
# Interestingly, the distribution is not very normal and looks
# almost uniform. It could be that the minimum salary is set high
# enough to distort the usual salary distribution that we expect
# to find.
# Examine years and games per year variables
summary(data$years)
hist(data$years, breaks = 20)
summary(data$gamesyr)
hist(data$gamesyr, breaks = 100)
# both have no missing values and distributions look reasonable.
# Examine batting average
hist(data$bavg, breaks=100)
# According to baseball-almanac.com, the record for highest season
# batting average was set by Hugh Duffy at .440.
# We may be suspicious of the two outlying values.
data[data$bavg > 400,]
# Notice that these players have very few at bats, 7 and 8. The mean
# number of at bats is 2,169.
summary(data$atbats)
head(sort(data$atbats), 50)
# It seems that these players got lucky due to how few chances
# they had at bat. The values are meaningful, though we expect
# a lot of extra variation in our x-variable.
# Notive that there are similar outliers in the negative direction as well
data[data$bavg < 150,]
# We could fit a much more complicated model to account for this
# effect, but that's beyond the scope of this course.
# A simpler idea is to mitigate the problem by removing players who
# have few chances to bat.
# To be eligible for the MLB batting title, players must
# have at least 3.1 at bats per team game originally scheduled, or
# approximately 500 at bats.
# Our dataset has 73 players with less than 500 at bats
sum(data$atbats<500)
# We proceed without these players.
mlb = data[data$atbats>=500,]
summary(mlb)
nrow(mlb)
# We are left with 280 players
# Examine home runs per year and runs batted per year
summary(mlb$hrunsyr, breaks=100)
hist(mlb$hrunsyr, breaks=100)
summary(mlb$rbisyr, breaks = 100)
hist(mlb$rbisyr, breaks = 100)
# Both of these have no missing values and the distributions
# have no suspicious artifacts.
# Our full model predicts salary based on years, games per year,
# and then three performance metrics: batting average, runs batted per
# year, and home runs per year.
model1 = lm(log(salary)~ years + gamesyr + bavg + hrunsyr + rbisyr, data = mlb)
plot(model1)
# Note the evidence of heteroskedasticity in the residuals vs. fitted
# values plot and in the scale-location plot.
# We now examine the coefficients.
coeftest(model1, vcov = vcovHC)
# Out of our three performance metrics, only batting average has a significant
# effect.
# We could recreate the output in Wooldridge by putting in the full data
# including players with few at bats
model_wooldridge = lm(log(salary)~ years + gamesyr + bavg + hrunsyr + rbisyr, data = data)
plot(model_wooldridge)
# notice the outlying points in the residuals vs leverage plot with high
# leverage. These have small residuals, however, meaning that they don't
# affect our coefficients very much. In particular, a general rule is
# that a cook's distance of 1 represents a worrysome amount of influence,
# and none of our datapoints are close.
coeftest(model_wooldridge, vcov = vcovHC)
# Here, the extra variation in bavg is acting like measurement error.
# Thus, it is little surprise that we lose statistical significance,
# even though we're adding more data.
##### Joint Hypothesis Testing
# We want to test whether the three performance indicators are jointly
# significant. That is, whether the coefficients for bavg, hrunsyr, and
# rbisyr are all zero.
# Our restricted model is formed by removign the performance indivators
model_rest = lm(log(salary)~ years + gamesyr, data = mlb)
coeftest(model_rest, vcov = vcovHC)
# To test whether the difference in fit is significant, we use the wald test,
# which generalizes the usual F-test of overall significance,
# but allows for a heteroskedasticity-robust covariance matrix
waldtest(model1, model_rest, vcov = vcovHC)
# Another useful command is linearHypothesis, which allows us
# to write the hypothesis we're testing clearly in string form.
linearHypothesis(model1, c("bavg = 0", "hrunsyr = 0", "rbisyr = 0"), vcov = vcovHC)
# In this case, the three performance indicators are jointly significant.
# There is probably a great deal of multicollinearity, which explains
# why in Wooldridge's specification, none of their coefficients is
# individually significant.
#### Testing whether coefficients are different
# One question is whether a hit and a walk affect salary by
# the same amount. We write an alternate specification as follows:
model2 = lm(log(salary)~ years + gamesyr + hits + bb, data = mlb)
coeftest(model2, vcov = vcovHC)
# Our hypothesis is that the coefficients for hits and bb (walks)
# are the same.
# We can test this manually by creating a new variable to equal the total
# hits_plus_walks.
mlb$hits_plus_walks = mlb$hits + mlb$bb
# We then put this variable into our model along with hits (how many
# of the total are hits). The coefficient for hits will then measure
# the difference between the effects of hits and walks.
model3 = lm(log(salary)~ years + gamesyr + hits + hits_plus_walks, data = mlb)
coeftest(model3, vcov = vcovHC)
# The coefficient is insignificant - we did not find evidence
# that hits and walks affect salary differently.
# We could also use linearHypothesis to do the same thing, in an
# even clearer way
linearHypothesis(model2, "hits = bb", vcov = vcovHC)
# Notice that we get the same p-value as before.
|
library(ggplot2)
library(gridExtra) #arrangeGrob
this_base <- "fig07-02_annual-report-aspect-ratio-2"
my_data <- data.frame(
income = c(117187, 202796, 357284, 392216, 163811),
year = c(1999, 2000, 2001, 2002, 2003))
p <- ggplot(my_data, aes(x = year, y = income / 1000)) +
geom_line() +
geom_point(shape = 21, size = 3, fill = "white") +
theme_bw() +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank())
p
p1 <- p +
geom_text(x = my_data$year, y = ((my_data$income / 1000) + 60),
label = my_data$income, size = 3) +
coord_fixed(ratio = 0.0008) +
scale_y_continuous(breaks = c(0, 400), limits = c(0, 460)) +
theme(axis.title = element_blank(),
axis.text.y = element_blank())
p1
p2 <- p +
scale_y_continuous(breaks = seq(0, 400, 100), limits = c(0, 400)) +
coord_fixed(ratio = 0.01) +
labs(x = NULL, y = "Net Income (thousands)") +
theme(axis.title.x = element_blank())
p2
p3 <- arrangeGrob(
p1, p2, nrow = 2, heights = c(0.25, 0.75),
main = textGrob("Fig 7.2 Annual Report: Aspect Ratio 2",
just = "top", vjust = 0.75, gp = gpar(fontsize = 16,
lineheight = 1,
fontface = "bold")))
p3
ggsave(paste0(this_base, ".png"),
p3, width = 6, height = 6)
|
/B_analysts_sources_github/jennybc/r-graph-catalog/fig07-02_annual-report-aspect-ratio-2.R
|
no_license
|
Irbis3/crantasticScrapper
|
R
| false | false | 1,383 |
r
|
library(ggplot2)
library(gridExtra) #arrangeGrob
this_base <- "fig07-02_annual-report-aspect-ratio-2"
my_data <- data.frame(
income = c(117187, 202796, 357284, 392216, 163811),
year = c(1999, 2000, 2001, 2002, 2003))
p <- ggplot(my_data, aes(x = year, y = income / 1000)) +
geom_line() +
geom_point(shape = 21, size = 3, fill = "white") +
theme_bw() +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank())
p
p1 <- p +
geom_text(x = my_data$year, y = ((my_data$income / 1000) + 60),
label = my_data$income, size = 3) +
coord_fixed(ratio = 0.0008) +
scale_y_continuous(breaks = c(0, 400), limits = c(0, 460)) +
theme(axis.title = element_blank(),
axis.text.y = element_blank())
p1
p2 <- p +
scale_y_continuous(breaks = seq(0, 400, 100), limits = c(0, 400)) +
coord_fixed(ratio = 0.01) +
labs(x = NULL, y = "Net Income (thousands)") +
theme(axis.title.x = element_blank())
p2
p3 <- arrangeGrob(
p1, p2, nrow = 2, heights = c(0.25, 0.75),
main = textGrob("Fig 7.2 Annual Report: Aspect Ratio 2",
just = "top", vjust = 0.75, gp = gpar(fontsize = 16,
lineheight = 1,
fontface = "bold")))
p3
ggsave(paste0(this_base, ".png"),
p3, width = 6, height = 6)
|
source("common.R")
#' plot2 is just a simple line graph of 'Global_active_power' over time with some extra
#' formatting.
#'
#' @param ylab the label to use on the y-axis. Defaults to the one needed for plot2 in the
#' assignment but can be overriden for plot4 which is slightly different.
#' @references `plot`
plot2.draw <- function(ylab = "Global Active Power (kilowatts)") {
local <- get.data()
x <- local$DateTime
y <- local$Global_active_power
plot(x, y, type = "l", xlab = "", ylab = ylab)
}
#' Creates and saves the second plot from the assignment.
#'
#' @references `save.graph`
plot2 <- function() {
save.graph("plot2.png", plot2.draw)
}
|
/plot2.R
|
no_license
|
jasoma/ExData_Plotting1
|
R
| false | false | 682 |
r
|
source("common.R")
#' plot2 is just a simple line graph of 'Global_active_power' over time with some extra
#' formatting.
#'
#' @param ylab the label to use on the y-axis. Defaults to the one needed for plot2 in the
#' assignment but can be overriden for plot4 which is slightly different.
#' @references `plot`
plot2.draw <- function(ylab = "Global Active Power (kilowatts)") {
local <- get.data()
x <- local$DateTime
y <- local$Global_active_power
plot(x, y, type = "l", xlab = "", ylab = ylab)
}
#' Creates and saves the second plot from the assignment.
#'
#' @references `save.graph`
plot2 <- function() {
save.graph("plot2.png", plot2.draw)
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/consume.R
\name{consume}
\alias{consume}
\title{Use a web service to score data in list (key=value) format.}
\usage{
consume(endpoint, ..., globalParam, retryDelay = 10, output = "output1",
.retry = 5)
}
\arguments{
\item{endpoint}{Either an AzureML web service endpoint returned by \code{\link{publishWebService}}, \code{\link{endpoints}}, or simply an AzureML web service from \code{\link{services}}; in the latter case the default endpoint for the service will be used.}
\item{...}{variable number of requests entered as lists in key-value format; optionally a single data frame argument.}
\item{globalParam}{global parameters entered as a list, default value is an empty list}
\item{retryDelay}{the time in seconds to delay before retrying in case of a server error}
\item{output}{name of the output port to return usually 'output1' or 'output2'; set to NULL to return everything as raw results in JSON-encoded list form}
\item{.retry}{number of tries before failing}
}
\value{
data frame containing results returned from web service call
}
\description{
Score data represented as lists where each list key represents a parameter of the web service.
}
\note{
Set \code{...} to a list of key/value pairs corresponding to web service inputs. Optionally, set \code{...} to a single data frame with columns corresponding to web service variables. The data frame approach returns output from the evaluation of each row of the data frame (see the examples).
}
\examples{
\dontrun{
# Use a default configuration in ~/.azureml, alternatively
# see help for `?workspace`.
ws <- workspace()
# Publish a simple model using the lme4::sleepdata ---------------------------
library(lme4)
set.seed(1)
train <- sleepstudy[sample(nrow(sleepstudy), 120),]
m <- lm(Reaction ~ Days + Subject, data = train)
# Deine a prediction function to publish based on the model:
sleepyPredict <- function(newdata){
predict(m, newdata=newdata)
}
ep <- publishWebService(ws, fun = sleepyPredict, name="sleepy lm",
inputSchema = sleepstudy,
data.frame=TRUE)
# OK, try this out, and compare with raw data
ans <- consume(ep, sleepstudy)$ans
plot(ans, sleepstudy$Reaction)
# Remove the service
deleteWebService(ws, "sleepy lm")
# Another data frame example -------------------------------------------------
# If your function can consume a whole data frame at once, you can also
# supply data in that form, resulting in more efficient computation.
# The following example builds a simple linear model on a subset of the
# airquality data and publishes a prediction function based on the model.
set.seed(1)
m <- lm(Ozone ~ ., data=airquality[sample(nrow(airquality), 100),])
# Define a prediction function based on the model:
fun <- function(newdata)
{
predict(m, newdata=newdata)
}
# Note the definition of inputSchema and use of the data.frame argument.
ep <- publishWebService(ws, fun=fun, name="Ozone",
inputSchema = airquality,
data.frame=TRUE)
ans <- consume(ep, airquality)$ans
plot(ans, airquality$Ozone)
deleteWebService(ws, "Ozone")
# Train a model using diamonds in ggplot2 ------------------------------------
# This example also demonstrates how to deal with factor in the data
data(diamonds, package="ggplot2")
set.seed(1)
train_idx = sample.int(nrow(diamonds), 30000)
test_idx = sample(setdiff(seq(1, nrow(diamonds)), train_idx), 500)
train <- diamonds[train_idx, ]
test <- diamonds[test_idx, ]
model <- glm(price ~ carat + clarity + color + cut - 1, data = train,
family = Gamma(link = "log"))
diamondLevels <- diamonds[1, ]
# The model works reasonably well, except for some outliers
plot(exp(predict(model, test)) ~ test$price)
# Create a prediction function that converts characters correctly to factors
predictDiamonds <- function(x){
x$cut <- factor(x$cut,
levels = levels(diamondLevels$cut), ordered = TRUE)
x$clarity <- factor(x$clarity,
levels = levels(diamondLevels$clarity), ordered = TRUE)
x$color <- factor(x$color,
levels = levels(diamondLevels$color), ordered = TRUE)
exp(predict(model, newdata = x))
}
# Publish the service
ws <- workspace()
ep <- publishWebService(ws, fun = predictDiamonds, name = "diamonds",
inputSchema = test,
data.frame = TRUE
)
# Consume the service
results <- consume(ep, test)$ans
plot(results ~ test$price)
deleteWebService(ws, "diamonds")
# Simple example using scalar input ------------------------------------------
ws <- workspace()
# Really simple example:
add <- function(x,y) x + y
endpoint <- publishWebService(ws,
fun = add,
name = "addme",
inputSchema = list(x="numeric",
y="numeric"),
outputSchema = list(ans="numeric"))
consume(endpoint, list(x=pi, y=2))
# Now remove the web service named "addme" that we just published
deleteWebService(ws, "addme")
# Send a custom R function for evaluation in AzureML -------------------------
# A neat trick to evaluate any expression in the Azure ML virtual
# machine R session and view its output:
ep <- publishWebService(ws,
fun = function(expr) {
paste(capture.output(
eval(parse(text=expr))), collapse="\\n")
},
name="commander",
inputSchema = list(x = "character"),
outputSchema = list(ans = "character"))
cat(consume(ep, list(x = "getwd()"))$ans)
cat(consume(ep, list(x = ".packages(all=TRUE)"))$ans)
cat(consume(ep, list(x = "R.Version()"))$ans)
# Remove the service we just published
deleteWebService(ws, "commander")
# Understanding the scoping rules --------------------------------------------
# The following example illustrates scoping rules. Note that the function
# refers to the variable y defined outside the function body. That value
# will be exported with the service.
y <- pi
ep <- publishWebService(ws,
fun = function(x) x + y,
name = "lexical scope",
inputSchema = list(x = "numeric"),
outputSchema = list(ans = "numeric"))
cat(consume(ep, list(x=2))$ans)
# Remove the service we just published
deleteWebService(ws, "lexical scope")
# Demonstrate scalar inputs but sending a data frame for scoring -------------
# Example showing the use of consume to score all the rows of a data frame
# at once, and other invocations for evaluating multiple sets of input
# values. The columns of the data frame correspond to the input parameters
# of the web service in this example:
f <- function(a,b,c,d) list(sum = a+b+c+d, prod = a*b*c*d)
ep <- publishWebService(ws,
f,
name = "rowSums",
inputSchema = list(
a = "numeric",
b = "numeric",
c = "numeric",
d = "numeric"
),
outputSchema = list(
sum ="numeric",
prod = "numeric")
)
x <- head(iris[,1:4]) # First four columns of iris
# Note the following will FAIL because of a name mismatch in the arguments
# (with an informative error):
consume(ep, x, retryDelay=1)
# We need the columns of the data frame to match the inputSchema:
names(x) <- letters[1:4]
# Now we can evaluate all the rows of the data frame in one call:
consume(ep, x)
# output should look like:
# sum prod
# 1 10.2 4.998
# 2 9.5 4.116
# 3 9.4 3.9104
# 4 9.4 4.278
# 5 10.2 5.04
# 6 11.4 14.3208
# You can use consume to evaluate just a single set of input values with this
# form:
consume(ep, a=1, b=2, c=3, d=4)
# or, equivalently,
consume(ep, list(a=1, b=2, c=3, d=4))
# You can evaluate multiple sets of input values with a data frame input:
consume(ep, data.frame(a=1:2, b=3:4, c=5:6, d=7:8))
# or, equivalently, with multiple lists:
consume(ep, list(a=1, b=3, c=5, d=7), list(a=2, b=4, c=6, d=8))
# Remove the service we just published
deleteWebService(ws, "rowSums")
# A more efficient way to do the same thing using data frame input/output:
f <- function(df) with(df, list(sum = a+b+c+d, prod = a*b*c*d))
ep = publishWebService(ws, f, name="rowSums2",
inputSchema = data.frame(a = 0, b = 0, c = 0, d = 0))
consume(ep, data.frame(a=1:2, b=3:4, c=5:6, d=7:8))
deleteWebService(ws, "rowSums2")
# Automatically discover dependencies ----------------------------------------
# The publishWebService function uses `miniCRAN` to include dependencies on
# packages required by your function. The next example uses the `lmer`
# function from the lme4 package, and also shows how to publish a function
# that consumes a data frame by setting data.frame=TRUE. Note! This example
# depends on a lot of packages and may take some time to upload to Azure.
library(lme4)
# Build a sample mixed effects model on just a subset of the sleepstudy data...
set.seed(1)
m <- lmer(Reaction ~ Days + (Days | Subject),
data=sleepstudy[sample(nrow(sleepstudy), 120),])
# Deine a prediction function to publish based on the model:
fun <- function(newdata)
{
predict(m, newdata=newdata)
}
ep <- publishWebService(ws, fun=fun, name="sleepy lmer",
inputSchema= sleepstudy,
packages="lme4",
data.frame=TRUE)
# OK, try this out, and compare with raw data
ans = consume(ep, sleepstudy)$ans
plot(ans, sleepstudy$Reaction)
# Remove the service
deleteWebService(ws, "sleepy lmer")
}
}
\seealso{
\code{\link{publishWebService}} \code{\link{endpoints}} \code{\link{services}} \code{\link{workspace}}
Other consumption functions: \code{\link{workspace}}
}
|
/man/consume.Rd
|
no_license
|
Vijayreddym/AzureML
|
R
| false | true | 10,201 |
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/consume.R
\name{consume}
\alias{consume}
\title{Use a web service to score data in list (key=value) format.}
\usage{
consume(endpoint, ..., globalParam, retryDelay = 10, output = "output1",
.retry = 5)
}
\arguments{
\item{endpoint}{Either an AzureML web service endpoint returned by \code{\link{publishWebService}}, \code{\link{endpoints}}, or simply an AzureML web service from \code{\link{services}}; in the latter case the default endpoint for the service will be used.}
\item{...}{variable number of requests entered as lists in key-value format; optionally a single data frame argument.}
\item{globalParam}{global parameters entered as a list, default value is an empty list}
\item{retryDelay}{the time in seconds to delay before retrying in case of a server error}
\item{output}{name of the output port to return usually 'output1' or 'output2'; set to NULL to return everything as raw results in JSON-encoded list form}
\item{.retry}{number of tries before failing}
}
\value{
data frame containing results returned from web service call
}
\description{
Score data represented as lists where each list key represents a parameter of the web service.
}
\note{
Set \code{...} to a list of key/value pairs corresponding to web service inputs. Optionally, set \code{...} to a single data frame with columns corresponding to web service variables. The data frame approach returns output from the evaluation of each row of the data frame (see the examples).
}
\examples{
\dontrun{
# Use a default configuration in ~/.azureml, alternatively
# see help for `?workspace`.
ws <- workspace()
# Publish a simple model using the lme4::sleepdata ---------------------------
library(lme4)
set.seed(1)
train <- sleepstudy[sample(nrow(sleepstudy), 120),]
m <- lm(Reaction ~ Days + Subject, data = train)
# Deine a prediction function to publish based on the model:
sleepyPredict <- function(newdata){
predict(m, newdata=newdata)
}
ep <- publishWebService(ws, fun = sleepyPredict, name="sleepy lm",
inputSchema = sleepstudy,
data.frame=TRUE)
# OK, try this out, and compare with raw data
ans <- consume(ep, sleepstudy)$ans
plot(ans, sleepstudy$Reaction)
# Remove the service
deleteWebService(ws, "sleepy lm")
# Another data frame example -------------------------------------------------
# If your function can consume a whole data frame at once, you can also
# supply data in that form, resulting in more efficient computation.
# The following example builds a simple linear model on a subset of the
# airquality data and publishes a prediction function based on the model.
set.seed(1)
m <- lm(Ozone ~ ., data=airquality[sample(nrow(airquality), 100),])
# Define a prediction function based on the model:
fun <- function(newdata)
{
predict(m, newdata=newdata)
}
# Note the definition of inputSchema and use of the data.frame argument.
ep <- publishWebService(ws, fun=fun, name="Ozone",
inputSchema = airquality,
data.frame=TRUE)
ans <- consume(ep, airquality)$ans
plot(ans, airquality$Ozone)
deleteWebService(ws, "Ozone")
# Train a model using diamonds in ggplot2 ------------------------------------
# This example also demonstrates how to deal with factor in the data
data(diamonds, package="ggplot2")
set.seed(1)
train_idx = sample.int(nrow(diamonds), 30000)
test_idx = sample(setdiff(seq(1, nrow(diamonds)), train_idx), 500)
train <- diamonds[train_idx, ]
test <- diamonds[test_idx, ]
model <- glm(price ~ carat + clarity + color + cut - 1, data = train,
family = Gamma(link = "log"))
diamondLevels <- diamonds[1, ]
# The model works reasonably well, except for some outliers
plot(exp(predict(model, test)) ~ test$price)
# Create a prediction function that converts characters correctly to factors
predictDiamonds <- function(x){
x$cut <- factor(x$cut,
levels = levels(diamondLevels$cut), ordered = TRUE)
x$clarity <- factor(x$clarity,
levels = levels(diamondLevels$clarity), ordered = TRUE)
x$color <- factor(x$color,
levels = levels(diamondLevels$color), ordered = TRUE)
exp(predict(model, newdata = x))
}
# Publish the service
ws <- workspace()
ep <- publishWebService(ws, fun = predictDiamonds, name = "diamonds",
inputSchema = test,
data.frame = TRUE
)
# Consume the service
results <- consume(ep, test)$ans
plot(results ~ test$price)
deleteWebService(ws, "diamonds")
# Simple example using scalar input ------------------------------------------
ws <- workspace()
# Really simple example:
add <- function(x,y) x + y
endpoint <- publishWebService(ws,
fun = add,
name = "addme",
inputSchema = list(x="numeric",
y="numeric"),
outputSchema = list(ans="numeric"))
consume(endpoint, list(x=pi, y=2))
# Now remove the web service named "addme" that we just published
deleteWebService(ws, "addme")
# Send a custom R function for evaluation in AzureML -------------------------
# A neat trick to evaluate any expression in the Azure ML virtual
# machine R session and view its output:
ep <- publishWebService(ws,
fun = function(expr) {
paste(capture.output(
eval(parse(text=expr))), collapse="\\n")
},
name="commander",
inputSchema = list(x = "character"),
outputSchema = list(ans = "character"))
cat(consume(ep, list(x = "getwd()"))$ans)
cat(consume(ep, list(x = ".packages(all=TRUE)"))$ans)
cat(consume(ep, list(x = "R.Version()"))$ans)
# Remove the service we just published
deleteWebService(ws, "commander")
# Understanding the scoping rules --------------------------------------------
# The following example illustrates scoping rules. Note that the function
# refers to the variable y defined outside the function body. That value
# will be exported with the service.
y <- pi
ep <- publishWebService(ws,
fun = function(x) x + y,
name = "lexical scope",
inputSchema = list(x = "numeric"),
outputSchema = list(ans = "numeric"))
cat(consume(ep, list(x=2))$ans)
# Remove the service we just published
deleteWebService(ws, "lexical scope")
# Demonstrate scalar inputs but sending a data frame for scoring -------------
# Example showing the use of consume to score all the rows of a data frame
# at once, and other invocations for evaluating multiple sets of input
# values. The columns of the data frame correspond to the input parameters
# of the web service in this example:
f <- function(a,b,c,d) list(sum = a+b+c+d, prod = a*b*c*d)
ep <- publishWebService(ws,
f,
name = "rowSums",
inputSchema = list(
a = "numeric",
b = "numeric",
c = "numeric",
d = "numeric"
),
outputSchema = list(
sum ="numeric",
prod = "numeric")
)
x <- head(iris[,1:4]) # First four columns of iris
# Note the following will FAIL because of a name mismatch in the arguments
# (with an informative error):
consume(ep, x, retryDelay=1)
# We need the columns of the data frame to match the inputSchema:
names(x) <- letters[1:4]
# Now we can evaluate all the rows of the data frame in one call:
consume(ep, x)
# output should look like:
# sum prod
# 1 10.2 4.998
# 2 9.5 4.116
# 3 9.4 3.9104
# 4 9.4 4.278
# 5 10.2 5.04
# 6 11.4 14.3208
# You can use consume to evaluate just a single set of input values with this
# form:
consume(ep, a=1, b=2, c=3, d=4)
# or, equivalently,
consume(ep, list(a=1, b=2, c=3, d=4))
# You can evaluate multiple sets of input values with a data frame input:
consume(ep, data.frame(a=1:2, b=3:4, c=5:6, d=7:8))
# or, equivalently, with multiple lists:
consume(ep, list(a=1, b=3, c=5, d=7), list(a=2, b=4, c=6, d=8))
# Remove the service we just published
deleteWebService(ws, "rowSums")
# A more efficient way to do the same thing using data frame input/output:
f <- function(df) with(df, list(sum = a+b+c+d, prod = a*b*c*d))
ep = publishWebService(ws, f, name="rowSums2",
inputSchema = data.frame(a = 0, b = 0, c = 0, d = 0))
consume(ep, data.frame(a=1:2, b=3:4, c=5:6, d=7:8))
deleteWebService(ws, "rowSums2")
# Automatically discover dependencies ----------------------------------------
# The publishWebService function uses `miniCRAN` to include dependencies on
# packages required by your function. The next example uses the `lmer`
# function from the lme4 package, and also shows how to publish a function
# that consumes a data frame by setting data.frame=TRUE. Note! This example
# depends on a lot of packages and may take some time to upload to Azure.
library(lme4)
# Build a sample mixed effects model on just a subset of the sleepstudy data...
set.seed(1)
m <- lmer(Reaction ~ Days + (Days | Subject),
data=sleepstudy[sample(nrow(sleepstudy), 120),])
# Deine a prediction function to publish based on the model:
fun <- function(newdata)
{
predict(m, newdata=newdata)
}
ep <- publishWebService(ws, fun=fun, name="sleepy lmer",
inputSchema= sleepstudy,
packages="lme4",
data.frame=TRUE)
# OK, try this out, and compare with raw data
ans = consume(ep, sleepstudy)$ans
plot(ans, sleepstudy$Reaction)
# Remove the service
deleteWebService(ws, "sleepy lmer")
}
}
\seealso{
\code{\link{publishWebService}} \code{\link{endpoints}} \code{\link{services}} \code{\link{workspace}}
Other consumption functions: \code{\link{workspace}}
}
|
source("global.R")
dashboardPage(
skin = "red",
dashboardHeader(title = "R-Lab / Milano Budget Trasparente",
titleWidth = 450),
dashboardSidebar(disable = TRUE),
dashboardBody(
navbarPage("Schede",
tabPanel("Ripartizione fondi per missione",
sidebarPanel(
helpText('Le missioni sono funzioni e obiettivi strategici del Comune: si
declinano in programmi, aggregati di attività finalizzate a realizzarli.
Dal box puoi selezionare la missione e il programma di cui
vuoi osservare i valori. Nel grafico puoi quindi osservare come si distribuisce
la spesa per quel programma, ovvero dove e quanto viene speso per ciascun livello,
per ciascun centro di costo'),
h3("Seleziona missione e programma"),
selectInput('missione', 'Missione', choices = missionValues,
selected = "ORDINE PUBBLICO E SICUREZZA"),
selectInput('programma', 'Programma', choices = 'Tutto',
selected = "POLIZIA LOCALE E AMMINISTRATIVA"),
selectInput('anno', 'Seleziona un anno:', choices = c(2013:2016),
selected = 2016)
),
mainPanel(
plotOutput('structure', click = 'plot_click', width = "auto", height = "auto")
)
),
tabPanel("Storico fondi per programma",
sidebarPanel(
helpText('I programmi sono aggregati omogenei di attività volti a perseguire
obiettivi strategici del Comune. \n
In questa visualizzazione puoi confrontare la spesa effettuata (fino al 2016)
e prevista (dal 2017 al 2019) per ciascun programma inserito in bilancio.'),
selectInput("TimeSeries1Choice", "Seleziona il programma istituzionale:",
TimeSeries1PossibleValues)
),
mainPanel(
column(12, plotOutput("TimeSeries1")),
column(6, plotOutput("TimeSeries2")),
column(6, plotOutput("TimeSeries3"))
)
),
tabPanel("Ricerca per testo",
# fluidPage(
# sidebarLayout(
sidebarPanel(
helpText("In questa scheda puoi effettuare una ricerca per parole chiave.
Inserisci un termine da cercare e clicca su Cerca: potrai visualizzare
la nuvola di parole
più associate a quel termine, e le voci di bilancio che lo contengono."),
textInput("text", label = h3("Termine da cercare:"),
value = "Asili"),
actionButton("go", "Cerca")
),
mainPanel(
wordcloud2Output('wordcloud2'),
dataTableOutput("tableWords")
)
),
tabPanel("Top fondi per centro di responsabilità",
sidebarPanel(
helpText("In questa scheda puoi visualizzare quali centri di responsabilità
(unità operative in cui il Comune è organizzato) hanno avuto a disposizione
più fondi. Seleziona il tipo di movimento, l'anno e il numero di
risultati da mostrare, e osserva la classifica."),
selectInput("tipo_movimento", "Tipo:",
c("ENTRATE", "USCITE")),
selectInput("year", "Anno",
c("2013","2014","2015","2016")),
textInput("topNum", "Risultati da mostrare:",
15)
),
mainPanel(
plotOutput("histTop"),
dataTableOutput("tableTop")
)
),
tabPanel("Distribuzione fondi per livelli",
sidebarPanel(
helpText("La struttura del bilancio comunale è stabilita dal Testo Unico degli
Enti Locali. Per ogni voce di entrata o di spesa, il bilancio è suddiviso
in 4 livelli di dettaglio. In questa visualizzazione puoi navigare dal
livello di minor dettaglio (interno del cerchio), al livello di
maggior dettaglio, e verificare la proporzione di fondi che quella
voce costituisce."),
selectInput("tipo_sun", "Tipo:",
c("ENTRATE", "USCITE")),
checkboxGroupInput("year_sun", label = "Year",
choices = 2013:2016,
selected = 2016)
),
# Show a plot of the generated distribution
mainPanel(
sunburstOutput("sun")
)
),
tabPanel("Flussi di cassa",
sidebarPanel(
selectInput("sankey_tipo", "Tipo:",
c("ENTRATE", "USCITE"), selected = "USCITE"),
selectInput("sankey_year", "Anno",
c("2013", "2014", "2015", "2016"))
# textInput("sankey_n_levels", "Risultati da mostrare:",
# 10)
),
mainPanel(
sankeyNetworkOutput(outputId = "sankey_out", height = 1000)
)
)
)
)
)
|
/app/ui.R
|
no_license
|
r-lab-milano/r-lab3-shinyMilano
|
R
| false | false | 5,326 |
r
|
source("global.R")
dashboardPage(
skin = "red",
dashboardHeader(title = "R-Lab / Milano Budget Trasparente",
titleWidth = 450),
dashboardSidebar(disable = TRUE),
dashboardBody(
navbarPage("Schede",
tabPanel("Ripartizione fondi per missione",
sidebarPanel(
helpText('Le missioni sono funzioni e obiettivi strategici del Comune: si
declinano in programmi, aggregati di attività finalizzate a realizzarli.
Dal box puoi selezionare la missione e il programma di cui
vuoi osservare i valori. Nel grafico puoi quindi osservare come si distribuisce
la spesa per quel programma, ovvero dove e quanto viene speso per ciascun livello,
per ciascun centro di costo'),
h3("Seleziona missione e programma"),
selectInput('missione', 'Missione', choices = missionValues,
selected = "ORDINE PUBBLICO E SICUREZZA"),
selectInput('programma', 'Programma', choices = 'Tutto',
selected = "POLIZIA LOCALE E AMMINISTRATIVA"),
selectInput('anno', 'Seleziona un anno:', choices = c(2013:2016),
selected = 2016)
),
mainPanel(
plotOutput('structure', click = 'plot_click', width = "auto", height = "auto")
)
),
tabPanel("Storico fondi per programma",
sidebarPanel(
helpText('I programmi sono aggregati omogenei di attività volti a perseguire
obiettivi strategici del Comune. \n
In questa visualizzazione puoi confrontare la spesa effettuata (fino al 2016)
e prevista (dal 2017 al 2019) per ciascun programma inserito in bilancio.'),
selectInput("TimeSeries1Choice", "Seleziona il programma istituzionale:",
TimeSeries1PossibleValues)
),
mainPanel(
column(12, plotOutput("TimeSeries1")),
column(6, plotOutput("TimeSeries2")),
column(6, plotOutput("TimeSeries3"))
)
),
tabPanel("Ricerca per testo",
# fluidPage(
# sidebarLayout(
sidebarPanel(
helpText("In questa scheda puoi effettuare una ricerca per parole chiave.
Inserisci un termine da cercare e clicca su Cerca: potrai visualizzare
la nuvola di parole
più associate a quel termine, e le voci di bilancio che lo contengono."),
textInput("text", label = h3("Termine da cercare:"),
value = "Asili"),
actionButton("go", "Cerca")
),
mainPanel(
wordcloud2Output('wordcloud2'),
dataTableOutput("tableWords")
)
),
tabPanel("Top fondi per centro di responsabilità",
sidebarPanel(
helpText("In questa scheda puoi visualizzare quali centri di responsabilità
(unità operative in cui il Comune è organizzato) hanno avuto a disposizione
più fondi. Seleziona il tipo di movimento, l'anno e il numero di
risultati da mostrare, e osserva la classifica."),
selectInput("tipo_movimento", "Tipo:",
c("ENTRATE", "USCITE")),
selectInput("year", "Anno",
c("2013","2014","2015","2016")),
textInput("topNum", "Risultati da mostrare:",
15)
),
mainPanel(
plotOutput("histTop"),
dataTableOutput("tableTop")
)
),
tabPanel("Distribuzione fondi per livelli",
sidebarPanel(
helpText("La struttura del bilancio comunale è stabilita dal Testo Unico degli
Enti Locali. Per ogni voce di entrata o di spesa, il bilancio è suddiviso
in 4 livelli di dettaglio. In questa visualizzazione puoi navigare dal
livello di minor dettaglio (interno del cerchio), al livello di
maggior dettaglio, e verificare la proporzione di fondi che quella
voce costituisce."),
selectInput("tipo_sun", "Tipo:",
c("ENTRATE", "USCITE")),
checkboxGroupInput("year_sun", label = "Year",
choices = 2013:2016,
selected = 2016)
),
# Show a plot of the generated distribution
mainPanel(
sunburstOutput("sun")
)
),
tabPanel("Flussi di cassa",
sidebarPanel(
selectInput("sankey_tipo", "Tipo:",
c("ENTRATE", "USCITE"), selected = "USCITE"),
selectInput("sankey_year", "Anno",
c("2013", "2014", "2015", "2016"))
# textInput("sankey_n_levels", "Risultati da mostrare:",
# 10)
),
mainPanel(
sankeyNetworkOutput(outputId = "sankey_out", height = 1000)
)
)
)
)
)
|
MAD(mean(BMI ~ diet, data = Diets1))
Diets1.null <- do(1000) * MAD(mean(shuffle(BMI) ~ diet, data = Diets1))
head(Diets1.null, 3)
dotPlot(~ result, data = Diets1.null, n = 50, groups = (result >= 0.747))
prop(~ (result >= 0.747), data = Diets1.null)
|
/inst/snippets/Exploration9.2.6.R
|
no_license
|
rpruim/ISIwithR
|
R
| false | false | 251 |
r
|
MAD(mean(BMI ~ diet, data = Diets1))
Diets1.null <- do(1000) * MAD(mean(shuffle(BMI) ~ diet, data = Diets1))
head(Diets1.null, 3)
dotPlot(~ result, data = Diets1.null, n = 50, groups = (result >= 0.747))
prop(~ (result >= 0.747), data = Diets1.null)
|
testlist <- list(bytes1 = integer(0), pmutation = 4.94065645841247e-323)
result <- do.call(mcga:::ByteCodeMutation,testlist)
str(result)
|
/mcga/inst/testfiles/ByteCodeMutation/libFuzzer_ByteCodeMutation/ByteCodeMutation_valgrind_files/1612886893-test.R
|
no_license
|
akhikolla/updatedatatype-list3
|
R
| false | false | 136 |
r
|
testlist <- list(bytes1 = integer(0), pmutation = 4.94065645841247e-323)
result <- do.call(mcga:::ByteCodeMutation,testlist)
str(result)
|
## Forest plot from odds/hazard ratios.
# xlabs = labels for the x axis (coordinates are flipped here so x is the vertical axis)
# title = plot title
# breaks = breaks in the y axis (correspond to spacing of the elements on the plot)
make_forest <- function (dataframe, xlabs, title, breaks) {
ymax <- max(dataframe$ci_high)
print(ymax)
ylim <- ceiling(max(dataframe$ci_high))
print(ylim)
xlength <- length(dataframe$predictor)
print(xlength)
forest <- ggplot (data = dataframe, aes (x = predictor, y = oddsratio)) +
geom_point(shape = 18, size = 3.5) +
geom_errorbar(aes(ymax = ci_high, ymin = ci_low), width = 0.5 , size = 0.5) +
geom_hline(yintercept = 1, linetype = "longdash") +
coord_flip(clip = "off", y = c(0, ymax + ymax/1.6 + 0.1)) +
scale_y_continuous(breaks = c(seq(0, ylim, by = breaks)), labels = c(seq(0, ylim, by = breaks))) +
scale_x_discrete(labels = xlabs) +
xlab(NULL) + ylab(NULL) +
ggtitle (title) +
theme_bw() +
theme (panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.text=element_text(colour = "black"),
plot.title = element_text(size = 12)) +
geom_text(aes(y = ymax + ymax/10 , label = or), size = 3.5) +
geom_text (aes (y = ymax + ymax/3.3, label = cirange), size = 3.5) +
geom_text (aes(y = ymax + ymax/1.6, label = p_value), size = 3.5) +
geom_text (x = xlength + 1.1, y = ymax +ymax/10 , label = "OR", alpha = 0.1) +
geom_text (x = xlength + 1.1, y = ymax + ymax/3.3, label = "CI", alpha = 0.1) +
geom_text (x = xlength + 1.1, y = ymax + ymax/1.6, label = "p", alpha = 0.1)
print(forest)
}
## Forest plot from odds/hazard ratios - y axis is on a logarithmic scale.
# xlabs = labels for the x axis (coordinates are flipped here so x is the vertical axis)
# title = plot title
# breaks = breaks in the y axis (correspond to spacing of the elements on the plot)
make_log_forest <- function (dataframe, xlabs, title = " ", breaks = 5, metric = "HR", xcoords = 1.1, barwidth = 0.5, a, b, c, alpha = 0.1) {
ymax <- max(dataframe$ci_high)
print(paste("ymax = ", ymax))
ylim <- ceiling(max(dataframe$ci_high))
print(paste( "ylim = ", ylim))
xlength <- length(dataframe$predictor)
print(paste ("xlength = ", xlength))
forest <- ggplot (data = dataframe, aes (x = predictor, y = oddsratio)) +
geom_point(shape = 18, size = 3.5) +
geom_errorbar(aes(ymax = ci_high, ymin = ci_low), width = barwidth , size = 0.5) +
geom_hline(yintercept = 1, linetype = "longdash") +
coord_flip( xlim = c(1, xlength), clip = "off") +
scale_y_log10(breaks = c(0, 1, seq(0, ylim, by = breaks)), labels = c(0, 1, seq(0, ylim, by = breaks))) +
scale_x_discrete(labels = xlabs) +
xlab(NULL) + ylab(NULL) +
ggtitle (title) +
theme_bw() +
theme (panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.text=element_text(colour = "black"),
plot.title = element_text(size = 12)) +
geom_text(aes(y = ymax + a, label = or), size = 3.5) +
geom_text (aes (y = ymax + b, label = cirange), size = 3.5) +
geom_text (aes(y = ymax + c, label = p_value), size = 3.5) +
geom_text (aes (x = xlength + xcoords, y = ymax + a, label = metric), alpha = alpha) +
geom_text (aes (x = xlength + xcoords, y = ymax + b, label = "CI"), alpha = alpha) +
geom_text (aes (x = xlength + xcoords, y = ymax + c, label = "p"), alpha = alpha)
print(forest)
}
#Function to extract hazard ratios and confidence intervals from a Cox model
HR_extractor <- function (coxmod) {
df <- as.data.frame((cbind(exp(coef(coxmod)), exp(confint(coxmod)), coef(summary(coxmod))[,5]))) %>% rownames_to_column()
colnames(df) <- c("predictor", "oddsratio", "ci_low", "ci_high","p")
df_round <- df %>%
mutate (or = format(round(oddsratio, digits=2), nsmall = 2),
cil = format(round (ci_low, digits = 2), nsmall = 2),
cih = format (round(ci_high, digits = 2), nsmall = 2)) %>%
mutate (cirange = paste ("(", cil, "-", cih, ")", sep = "")) %>%
mutate (p_value = case_when (
p < 0.001 ~ "<0.001",
p < 0.01 ~ format(round (p, digits = 3), nsmall = 3),
p >= 0.01 ~ format(round (p, digits = 2), nsmall = 2))) %>%
filter (predictor != "(Intercept)")
df_round
}
#Function to extract odds ratios and confidence intervals from a glm model
OR_extractor <- function (glm) {
df <- as.data.frame((cbind(exp(coef(glm)), exp(confint(glm)), coef(summary(glm))[,4]))) %>% rownames_to_column()
colnames(df) <- c("predictor", "oddsratio", "ci_low", "ci_high","p")
df_round <- df %>%
mutate (or = format(round(oddsratio, digits=2), nsmall = 2),
cil = format(round (ci_low, digits = 2), nsmall = 2),
cih = format (round(ci_high, digits = 2), nsmall = 2)) %>%
mutate (cirange = paste ("(", cil, "-", cih, ")", sep = "")) %>%
mutate (p_value = format(round (p, digits = 3), nsmall = 3)) %>%
mutate (p_value = case_when (
p < 0.001 ~ "<0.001",
p < 0.01 ~ format(round (p, digits = 3), nsmall = 3),
p >= 0.01 ~ format(round (p, digits = 2), nsmall = 2))) %>%
filter (predictor != "(Intercept)")
df_round
}
# CDEPI eGFR function (from John)
ckdepicre <- function(sex,cre,age,race){ifelse(race==1,A<-1.159,A<-1);ifelse(sex==0,{B<--0.329;K<-0.7;Z<-144},{B<--0.411;K<-0.9;Z<-141});ifelse(cre/K<1,D<-(cre/K)^B,D<-(cre/K)^-1.209);return(A*Z*D*(0.993^age))} ## CKDEPI GFR FORMULA CREATININE
#X$GFR<-mapply(ckdepicre,age=X$Age,sex=X$Sex=="Male",cre=X$cre/88.4,race=X$blackethnicity)
# calculating the number of unique elements of a vector
lunique <- function (x) {length(unique(x))}
|
/functions.R
|
no_license
|
zuz-bien/covid_aki
|
R
| false | false | 5,775 |
r
|
## Forest plot from odds/hazard ratios.
# xlabs = labels for the x axis (coordinates are flipped here so x is the vertical axis)
# title = plot title
# breaks = breaks in the y axis (correspond to spacing of the elements on the plot)
make_forest <- function (dataframe, xlabs, title, breaks) {
ymax <- max(dataframe$ci_high)
print(ymax)
ylim <- ceiling(max(dataframe$ci_high))
print(ylim)
xlength <- length(dataframe$predictor)
print(xlength)
forest <- ggplot (data = dataframe, aes (x = predictor, y = oddsratio)) +
geom_point(shape = 18, size = 3.5) +
geom_errorbar(aes(ymax = ci_high, ymin = ci_low), width = 0.5 , size = 0.5) +
geom_hline(yintercept = 1, linetype = "longdash") +
coord_flip(clip = "off", y = c(0, ymax + ymax/1.6 + 0.1)) +
scale_y_continuous(breaks = c(seq(0, ylim, by = breaks)), labels = c(seq(0, ylim, by = breaks))) +
scale_x_discrete(labels = xlabs) +
xlab(NULL) + ylab(NULL) +
ggtitle (title) +
theme_bw() +
theme (panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.text=element_text(colour = "black"),
plot.title = element_text(size = 12)) +
geom_text(aes(y = ymax + ymax/10 , label = or), size = 3.5) +
geom_text (aes (y = ymax + ymax/3.3, label = cirange), size = 3.5) +
geom_text (aes(y = ymax + ymax/1.6, label = p_value), size = 3.5) +
geom_text (x = xlength + 1.1, y = ymax +ymax/10 , label = "OR", alpha = 0.1) +
geom_text (x = xlength + 1.1, y = ymax + ymax/3.3, label = "CI", alpha = 0.1) +
geom_text (x = xlength + 1.1, y = ymax + ymax/1.6, label = "p", alpha = 0.1)
print(forest)
}
## Forest plot from odds/hazard ratios - y axis is on a logarithmic scale.
# xlabs = labels for the x axis (coordinates are flipped here so x is the vertical axis)
# title = plot title
# breaks = breaks in the y axis (correspond to spacing of the elements on the plot)
make_log_forest <- function (dataframe, xlabs, title = " ", breaks = 5, metric = "HR", xcoords = 1.1, barwidth = 0.5, a, b, c, alpha = 0.1) {
ymax <- max(dataframe$ci_high)
print(paste("ymax = ", ymax))
ylim <- ceiling(max(dataframe$ci_high))
print(paste( "ylim = ", ylim))
xlength <- length(dataframe$predictor)
print(paste ("xlength = ", xlength))
forest <- ggplot (data = dataframe, aes (x = predictor, y = oddsratio)) +
geom_point(shape = 18, size = 3.5) +
geom_errorbar(aes(ymax = ci_high, ymin = ci_low), width = barwidth , size = 0.5) +
geom_hline(yintercept = 1, linetype = "longdash") +
coord_flip( xlim = c(1, xlength), clip = "off") +
scale_y_log10(breaks = c(0, 1, seq(0, ylim, by = breaks)), labels = c(0, 1, seq(0, ylim, by = breaks))) +
scale_x_discrete(labels = xlabs) +
xlab(NULL) + ylab(NULL) +
ggtitle (title) +
theme_bw() +
theme (panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.text=element_text(colour = "black"),
plot.title = element_text(size = 12)) +
geom_text(aes(y = ymax + a, label = or), size = 3.5) +
geom_text (aes (y = ymax + b, label = cirange), size = 3.5) +
geom_text (aes(y = ymax + c, label = p_value), size = 3.5) +
geom_text (aes (x = xlength + xcoords, y = ymax + a, label = metric), alpha = alpha) +
geom_text (aes (x = xlength + xcoords, y = ymax + b, label = "CI"), alpha = alpha) +
geom_text (aes (x = xlength + xcoords, y = ymax + c, label = "p"), alpha = alpha)
print(forest)
}
#Function to extract hazard ratios and confidence intervals from a Cox model
HR_extractor <- function (coxmod) {
df <- as.data.frame((cbind(exp(coef(coxmod)), exp(confint(coxmod)), coef(summary(coxmod))[,5]))) %>% rownames_to_column()
colnames(df) <- c("predictor", "oddsratio", "ci_low", "ci_high","p")
df_round <- df %>%
mutate (or = format(round(oddsratio, digits=2), nsmall = 2),
cil = format(round (ci_low, digits = 2), nsmall = 2),
cih = format (round(ci_high, digits = 2), nsmall = 2)) %>%
mutate (cirange = paste ("(", cil, "-", cih, ")", sep = "")) %>%
mutate (p_value = case_when (
p < 0.001 ~ "<0.001",
p < 0.01 ~ format(round (p, digits = 3), nsmall = 3),
p >= 0.01 ~ format(round (p, digits = 2), nsmall = 2))) %>%
filter (predictor != "(Intercept)")
df_round
}
#Function to extract odds ratios and confidence intervals from a glm model
OR_extractor <- function (glm) {
df <- as.data.frame((cbind(exp(coef(glm)), exp(confint(glm)), coef(summary(glm))[,4]))) %>% rownames_to_column()
colnames(df) <- c("predictor", "oddsratio", "ci_low", "ci_high","p")
df_round <- df %>%
mutate (or = format(round(oddsratio, digits=2), nsmall = 2),
cil = format(round (ci_low, digits = 2), nsmall = 2),
cih = format (round(ci_high, digits = 2), nsmall = 2)) %>%
mutate (cirange = paste ("(", cil, "-", cih, ")", sep = "")) %>%
mutate (p_value = format(round (p, digits = 3), nsmall = 3)) %>%
mutate (p_value = case_when (
p < 0.001 ~ "<0.001",
p < 0.01 ~ format(round (p, digits = 3), nsmall = 3),
p >= 0.01 ~ format(round (p, digits = 2), nsmall = 2))) %>%
filter (predictor != "(Intercept)")
df_round
}
# CDEPI eGFR function (from John)
ckdepicre <- function(sex,cre,age,race){ifelse(race==1,A<-1.159,A<-1);ifelse(sex==0,{B<--0.329;K<-0.7;Z<-144},{B<--0.411;K<-0.9;Z<-141});ifelse(cre/K<1,D<-(cre/K)^B,D<-(cre/K)^-1.209);return(A*Z*D*(0.993^age))} ## CKDEPI GFR FORMULA CREATININE
#X$GFR<-mapply(ckdepicre,age=X$Age,sex=X$Sex=="Male",cre=X$cre/88.4,race=X$blackethnicity)
# calculating the number of unique elements of a vector
lunique <- function (x) {length(unique(x))}
|
\name{Bisect}
\alias{Bisect}
%- Also NEED an '\alias' for EACH other topic documented here.
\title{
An implementation of the bisection algorithm for root finding
}
\description{
Most of the optimization is \code{Icens} have a one dimensional root-finding component. Since the quantities involved are generally restricted to a subset of \eqn{[0, 1]} we use bisection to find the roots. This function is borrowed from package \code{Icens}.
}
%\usage{
%Bisect(tA, pvec, ndir, Meps, tolbis=1e-07)
%}
%- maybe also 'usage' for other objects documented here.
%\arguments{
% \item{tA}{The transpose of the clique matrix.}
% \item{pvec}{The current estimate of the probability vector.}
% \item{ndir{The direction to explore.}
% \item{Meps}{Machine epsilon, elements of \code{pvec} that are less than this are assumed to be zero.}
% \item{tolbis}{The tolerance used to determine if the algorithm has converged.}
%}
\details{
We search from \code{pvec} in the direction \code{ndir} to obtain the new value of \code{pvec} that maximizes the likelihood.
}
%\value{
%The new estimate of \code{pvec}.
%}
\references{
Any book on optimization.
}
\author{
Alain Vandal and Robert Gentleman
}
\note{
It is used in \code{\link{ModifiedEMICMmac}} and not to be called by the user.
}
%% ~Make other sections like Warning with \section{Warning }{....} ~
\seealso{
\code{\link{ModifiedEMICMmac}}
}
%\examples
% Add one or more standard keywords, see file 'KEYWORDS' in the
% R documentation directory.
%\keyword{ ~kwd1 }
%\keyword{ ~kwd2 }% __ONLY ONE__ keyword per line
|
/man/Bisect.Rd
|
no_license
|
cran/glrt
|
R
| false | false | 1,559 |
rd
|
\name{Bisect}
\alias{Bisect}
%- Also NEED an '\alias' for EACH other topic documented here.
\title{
An implementation of the bisection algorithm for root finding
}
\description{
Most of the optimization is \code{Icens} have a one dimensional root-finding component. Since the quantities involved are generally restricted to a subset of \eqn{[0, 1]} we use bisection to find the roots. This function is borrowed from package \code{Icens}.
}
%\usage{
%Bisect(tA, pvec, ndir, Meps, tolbis=1e-07)
%}
%- maybe also 'usage' for other objects documented here.
%\arguments{
% \item{tA}{The transpose of the clique matrix.}
% \item{pvec}{The current estimate of the probability vector.}
% \item{ndir{The direction to explore.}
% \item{Meps}{Machine epsilon, elements of \code{pvec} that are less than this are assumed to be zero.}
% \item{tolbis}{The tolerance used to determine if the algorithm has converged.}
%}
\details{
We search from \code{pvec} in the direction \code{ndir} to obtain the new value of \code{pvec} that maximizes the likelihood.
}
%\value{
%The new estimate of \code{pvec}.
%}
\references{
Any book on optimization.
}
\author{
Alain Vandal and Robert Gentleman
}
\note{
It is used in \code{\link{ModifiedEMICMmac}} and not to be called by the user.
}
%% ~Make other sections like Warning with \section{Warning }{....} ~
\seealso{
\code{\link{ModifiedEMICMmac}}
}
%\examples
% Add one or more standard keywords, see file 'KEYWORDS' in the
% R documentation directory.
%\keyword{ ~kwd1 }
%\keyword{ ~kwd2 }% __ONLY ONE__ keyword per line
|
library(leaps)
library(glmnet)
library(randomForest)
fit_glm <- function (f, df, fold, k, type = NULL, use_saved = TRUE) {
modelname <- getModelName("glm", type)
model_path <- getModelPath(dataname, fold, k = k, modelname = modelname)
if (use_saved) {
if (file.exists(model_path)) {
glm_model <- read_model(model_path)
}
}
if (!exists("glm_model")) {
glm_model <-
glm(f, family = "binomial", data = df)
}
glm_model
}
pred_glm <- function (model, df_new, y_new, ids, dataname,
fold, k, type = NULL) {
modelname <- getModelName("glm", type)
pred <- predict(model, df_new, type = "response")
nz <- model$rank
setPredDf(pred, y_new, dataname, modelname, ids, fold, nz = nz,
numfeats = k)
}
fit_lasso <- function (X, y, fold, k, type = NULL,
use_saved = FALSE) {
modelname <- getModelName("lasso", type)
model_path <- getModelPath(dataname, fold, k = k, modelname = modelname)
lambda <- 1000
if (use_saved) {
if (file.exists(model_path)) {
lasso_model <- read_model(model_path)
}
}
if (!exists("lasso_model")) {
lasso_model <- cv.glmnet(X, y, type.measure = "auc", alpha = 1,
nlambda = lambda, family = "binomial")
}
lasso_model
}
pred_lasso <- function (model, X_new, y_new, ids, dataname, fold, k,
type = NULL) {
modelname <- getModelName("lasso", type)
pred <- predict(model, X_new, type = "response", s = "lambda.1se")
lambda_ind <- model$lambda == model$lambda.1se
nz <- model$nzero[lambda_ind]
setPredDf(pred, y_new, dataname, modelname, ids, fold, nz, numfeats = k)
}
fit_rf <- function (X, y, fold, k, type = NULL) {
modelname <- getModelName("rf", type)
model_path <- getModelPath(dataname, fold, k = k, modelname = modelname)
ntrees <- 1000
randomForest(X, factor(y), ntree = ntrees)
}
pred_rf <- function (model, X_new, y_new, ids, dataname, fold, k,
type = NULL) {
modelname <- getModelName("rf", type)
pred <- predict(model, X_new, type = "prob")[, 2]
setPredDf(pred, y_new, dataname, modelname, ids, fold, nz = k, numfeats = k)
}
get_subsets <- function (mm, y) {
# Given a model.matrix and labels y, return a logical matrix of subsets
# Args:
# mm: model.matrix
# y: corresponding labels
# Returns:
# list of (subsets, assign)
real_mm_cols <- colnames(mm) != "(Intercept)"
ass <- attr(mm, "assign")
mm <- mm[, real_mm_cols]
ass <- ass[real_mm_cols]
maxfeats <- dim(mm)[2] # number of total columns
sink("/dev/null") # Redirect output from leaps
search <- regsubsets(mm, y, method = "forward", intercept = TRUE,
really.big = TRUE, nvmax = maxfeats)
sink() # END: redirect output from leaps
subsets <- summary(search)$which
non_intercept_cols <- colnames(subsets) != "(Intercept)"
subsets <- subsets[, non_intercept_cols] # Remove (Intercept) term
e <- assert_that(dim(subsets)[2] == length(ass),
msg = "subsets and assign have incompatible dimensions!")
list(subsets = subsets, ass = ass)
}
get_formulas <- function(ass, subsets, features) {
# Get forula from subsets that use exactly n original features
# Args:
# ass: the "assign" attribute from a full model.matrix
# subsets: a summary.regsubsets object
# features: character vector of original feature columns
# Returns:
# data.frame with columns k and corresponding formula
ret <- bind_rows(apply(subsets, 1, function(s) {
# Extract original index of variables that are included
v <- unique(ass[s])
f <- features[v]
nv <- length(f)
tibble(n = nv, feats = list(f))
})) %>%
distinct(n, .keep_all = TRUE) %>%
mutate(formula = map(feats, ~ make_formula("label", .x)))
ret
}
discretize <- function(d_train, d_test, n_bins) {
# Discretize numerical columns in train/test data to n_bins of equal size,
# based on cutoffs derived from the training data
# Args:
# d_train, d_test: data frames for train and test
# n_bins: number of bins for each numeric column
# Return:
# list of two data frames, $train and $test
numeric_cols <- names(d_train[, unlist(lapply(d_train, is.numeric))])
qs <- seq(1/n_bins, 1, 1/n_bins)
disc_train <- d_train
disc_test <- d_test
if (length(numeric_cols) > 0) { # Non-zero numeric columns
for (cn in numeric_cols) {
col_train <- d_train[[cn]]
col_test <- d_test[[cn]]
breaks <- unique(quantile(col_train, qs))
breaks[n_bins] <- Inf
disc_train[[cn]] <- as.factor(cut(col_train, c(-Inf, breaks)))
disc_test[[cn]] <- as.factor(cut(col_test, c(-Inf, breaks)))
}
}
list(train = disc_train, test = disc_test)
}
get_k_feat_model <- function(ass, subsets, features,
train_df, train_labels, k){
# Get forula from subsets that use exactly n original features
# Args:
# ass: the "assign" attribute from a full model.matrix
# subsets: a summary.regsubsets object
# features: character vector of original feature columns
# train_df, test_df: original train/test data frames
# train_labels, test_labels: original train/test labels
# k: parameter k to get model for
#
# Note: Intermediate models are saved as a side effect
#
# Returns:
# data.frame of all predictions over k models
formulas <- get_formulas(ass, subsets, features)
if (k > max(formulas$n)) {
stop("k=", k," is too large; max is ", max(formulas$n))
}
ss_formula <- formulas %>%
filter(n == k) %>%
pull(formula) %>%
first()
get_k_feat_model_from_formula(ss_formula, train_df, train_labels, k)
}
get_k_feat_model_from_formula <- function(formula, train_df, train_labels, k){
# Get SRR model for k given formula
# Args:
# formula: model formula
# train_df, test_df: original train/test data frames
# train_labels, test_labels: original train/test labels
# k: parameter k to get model for
# Update the selected subset
train_ssmm <- model.matrix(formula, data = train_df)
# Lasso model is used for SRR, so we keep a copy
m_lasso_k <- fit_lasso(train_ssmm, train_labels, fold = 5, k)
# Use trained model to generate heuristics
roundM_model <- as.matrix(coef(m_lasso_k, s = "lambda.min"))
inf_model <- as.matrix(coef(m_lasso_k, s = "lambda.min"))
coef_names <- rownames(roundM_model)
ind_non_intercept <- coef_names != "(Intercept)"
nfeat <- dim(roundM_model)[1]
roundM_model <- array(roundM_model, c(nfeat, length(Ms)))
max_coef <- max(abs(roundM_model[ind_non_intercept, ]))
tmp.rounds <- roundM_model[ind_non_intercept, ]
tmp.rounds <- (tmp.rounds/max_coef) %*% diag(Ms + 0.499)
tmp.rounds <- round(tmp.rounds)
roundM_model[ind_non_intercept, ] <- tmp.rounds
rownames(roundM_model) <- coef_names
colnames(roundM_model) <- Ms
list(model = m_lasso_k, round = roundM_model[ind_non_intercept,])
}
|
/src/subfuncs.R
|
no_license
|
stanford-policylab/simple-rules
|
R
| false | false | 6,981 |
r
|
library(leaps)
library(glmnet)
library(randomForest)
fit_glm <- function (f, df, fold, k, type = NULL, use_saved = TRUE) {
modelname <- getModelName("glm", type)
model_path <- getModelPath(dataname, fold, k = k, modelname = modelname)
if (use_saved) {
if (file.exists(model_path)) {
glm_model <- read_model(model_path)
}
}
if (!exists("glm_model")) {
glm_model <-
glm(f, family = "binomial", data = df)
}
glm_model
}
pred_glm <- function (model, df_new, y_new, ids, dataname,
fold, k, type = NULL) {
modelname <- getModelName("glm", type)
pred <- predict(model, df_new, type = "response")
nz <- model$rank
setPredDf(pred, y_new, dataname, modelname, ids, fold, nz = nz,
numfeats = k)
}
fit_lasso <- function (X, y, fold, k, type = NULL,
use_saved = FALSE) {
modelname <- getModelName("lasso", type)
model_path <- getModelPath(dataname, fold, k = k, modelname = modelname)
lambda <- 1000
if (use_saved) {
if (file.exists(model_path)) {
lasso_model <- read_model(model_path)
}
}
if (!exists("lasso_model")) {
lasso_model <- cv.glmnet(X, y, type.measure = "auc", alpha = 1,
nlambda = lambda, family = "binomial")
}
lasso_model
}
pred_lasso <- function (model, X_new, y_new, ids, dataname, fold, k,
type = NULL) {
modelname <- getModelName("lasso", type)
pred <- predict(model, X_new, type = "response", s = "lambda.1se")
lambda_ind <- model$lambda == model$lambda.1se
nz <- model$nzero[lambda_ind]
setPredDf(pred, y_new, dataname, modelname, ids, fold, nz, numfeats = k)
}
fit_rf <- function (X, y, fold, k, type = NULL) {
modelname <- getModelName("rf", type)
model_path <- getModelPath(dataname, fold, k = k, modelname = modelname)
ntrees <- 1000
randomForest(X, factor(y), ntree = ntrees)
}
pred_rf <- function (model, X_new, y_new, ids, dataname, fold, k,
type = NULL) {
modelname <- getModelName("rf", type)
pred <- predict(model, X_new, type = "prob")[, 2]
setPredDf(pred, y_new, dataname, modelname, ids, fold, nz = k, numfeats = k)
}
get_subsets <- function (mm, y) {
# Given a model.matrix and labels y, return a logical matrix of subsets
# Args:
# mm: model.matrix
# y: corresponding labels
# Returns:
# list of (subsets, assign)
real_mm_cols <- colnames(mm) != "(Intercept)"
ass <- attr(mm, "assign")
mm <- mm[, real_mm_cols]
ass <- ass[real_mm_cols]
maxfeats <- dim(mm)[2] # number of total columns
sink("/dev/null") # Redirect output from leaps
search <- regsubsets(mm, y, method = "forward", intercept = TRUE,
really.big = TRUE, nvmax = maxfeats)
sink() # END: redirect output from leaps
subsets <- summary(search)$which
non_intercept_cols <- colnames(subsets) != "(Intercept)"
subsets <- subsets[, non_intercept_cols] # Remove (Intercept) term
e <- assert_that(dim(subsets)[2] == length(ass),
msg = "subsets and assign have incompatible dimensions!")
list(subsets = subsets, ass = ass)
}
get_formulas <- function(ass, subsets, features) {
# Get forula from subsets that use exactly n original features
# Args:
# ass: the "assign" attribute from a full model.matrix
# subsets: a summary.regsubsets object
# features: character vector of original feature columns
# Returns:
# data.frame with columns k and corresponding formula
ret <- bind_rows(apply(subsets, 1, function(s) {
# Extract original index of variables that are included
v <- unique(ass[s])
f <- features[v]
nv <- length(f)
tibble(n = nv, feats = list(f))
})) %>%
distinct(n, .keep_all = TRUE) %>%
mutate(formula = map(feats, ~ make_formula("label", .x)))
ret
}
discretize <- function(d_train, d_test, n_bins) {
# Discretize numerical columns in train/test data to n_bins of equal size,
# based on cutoffs derived from the training data
# Args:
# d_train, d_test: data frames for train and test
# n_bins: number of bins for each numeric column
# Return:
# list of two data frames, $train and $test
numeric_cols <- names(d_train[, unlist(lapply(d_train, is.numeric))])
qs <- seq(1/n_bins, 1, 1/n_bins)
disc_train <- d_train
disc_test <- d_test
if (length(numeric_cols) > 0) { # Non-zero numeric columns
for (cn in numeric_cols) {
col_train <- d_train[[cn]]
col_test <- d_test[[cn]]
breaks <- unique(quantile(col_train, qs))
breaks[n_bins] <- Inf
disc_train[[cn]] <- as.factor(cut(col_train, c(-Inf, breaks)))
disc_test[[cn]] <- as.factor(cut(col_test, c(-Inf, breaks)))
}
}
list(train = disc_train, test = disc_test)
}
get_k_feat_model <- function(ass, subsets, features,
train_df, train_labels, k){
# Get forula from subsets that use exactly n original features
# Args:
# ass: the "assign" attribute from a full model.matrix
# subsets: a summary.regsubsets object
# features: character vector of original feature columns
# train_df, test_df: original train/test data frames
# train_labels, test_labels: original train/test labels
# k: parameter k to get model for
#
# Note: Intermediate models are saved as a side effect
#
# Returns:
# data.frame of all predictions over k models
formulas <- get_formulas(ass, subsets, features)
if (k > max(formulas$n)) {
stop("k=", k," is too large; max is ", max(formulas$n))
}
ss_formula <- formulas %>%
filter(n == k) %>%
pull(formula) %>%
first()
get_k_feat_model_from_formula(ss_formula, train_df, train_labels, k)
}
get_k_feat_model_from_formula <- function(formula, train_df, train_labels, k){
# Get SRR model for k given formula
# Args:
# formula: model formula
# train_df, test_df: original train/test data frames
# train_labels, test_labels: original train/test labels
# k: parameter k to get model for
# Update the selected subset
train_ssmm <- model.matrix(formula, data = train_df)
# Lasso model is used for SRR, so we keep a copy
m_lasso_k <- fit_lasso(train_ssmm, train_labels, fold = 5, k)
# Use trained model to generate heuristics
roundM_model <- as.matrix(coef(m_lasso_k, s = "lambda.min"))
inf_model <- as.matrix(coef(m_lasso_k, s = "lambda.min"))
coef_names <- rownames(roundM_model)
ind_non_intercept <- coef_names != "(Intercept)"
nfeat <- dim(roundM_model)[1]
roundM_model <- array(roundM_model, c(nfeat, length(Ms)))
max_coef <- max(abs(roundM_model[ind_non_intercept, ]))
tmp.rounds <- roundM_model[ind_non_intercept, ]
tmp.rounds <- (tmp.rounds/max_coef) %*% diag(Ms + 0.499)
tmp.rounds <- round(tmp.rounds)
roundM_model[ind_non_intercept, ] <- tmp.rounds
rownames(roundM_model) <- coef_names
colnames(roundM_model) <- Ms
list(model = m_lasso_k, round = roundM_model[ind_non_intercept,])
}
|
library(ape)
testtree <- read.tree("7597_0.txt")
unrooted_tr <- unroot(testtree)
write.tree(unrooted_tr, file="7597_0_unrooted.txt")
|
/codeml_files/newick_trees_processed/7597_0/rinput.R
|
no_license
|
DaniBoo/cyanobacteria_project
|
R
| false | false | 135 |
r
|
library(ape)
testtree <- read.tree("7597_0.txt")
unrooted_tr <- unroot(testtree)
write.tree(unrooted_tr, file="7597_0_unrooted.txt")
|
# Load Data
NEI <- readRDS("summarySCC_PM25.rds")
SCC <- readRDS("Source_Classification_Code.rds")
# Plot
png("plot2.png")
NEI.Baltimore <- NEI[NEI$fips == "24510", ]
NEI.Baltimore.groups.sum <- with(NEI.Baltimore, tapply(Emissions, year, sum))
plot(NEI.Baltimore.groups.sum ~ names(NEI.Baltimore.groups.sum), type = "l", xlab = "year", ylab = "sum")
title("Trend of Total PM2.5 Emissions in Baltimore City")
dev.off()
|
/plot2.R
|
no_license
|
sun33170161/ExData_Plotting2
|
R
| false | false | 423 |
r
|
# Load Data
NEI <- readRDS("summarySCC_PM25.rds")
SCC <- readRDS("Source_Classification_Code.rds")
# Plot
png("plot2.png")
NEI.Baltimore <- NEI[NEI$fips == "24510", ]
NEI.Baltimore.groups.sum <- with(NEI.Baltimore, tapply(Emissions, year, sum))
plot(NEI.Baltimore.groups.sum ~ names(NEI.Baltimore.groups.sum), type = "l", xlab = "year", ylab = "sum")
title("Trend of Total PM2.5 Emissions in Baltimore City")
dev.off()
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/data.R
\docType{data}
\name{data_dictionary_MFD}
\alias{data_dictionary_MFD}
\title{Moral Foundations Dictionary}
\format{An object of class \code{dictionary2} of length 11.}
\source{
\url{http://moralfoundations.org/othermaterials}
}
\usage{
data_dictionary_MFD
}
\description{
A \pkg{quanteda} \link[quanteda]{dictionary} object containing
the Moral Foundations Dictionary, a publicly available dictionaries with
information on the proportions of virtue and vice words for each foundation.
The categories are harm (vice/virtue), fairness (vice/virtue), ingroup (vice/virtue),
authority (vice/virtue), purity (vice/virtue) and morality (general).
}
\references{
Haidt, J., Graham, J., and Nosek, B.A. (2009). "Liberals and Conservatives
Rely on Different Sets of Moral Foundations. \emph{Journal of Personality and Social
Inquiry} 20(2-3): 110-119.
Graham, J., and Haidt, J. (2016). \href{http://moralfoundations.org/othermaterials}{Moral
Foundations Dictionary.}: \url{http://moralfoundations.org/othermaterials}.
}
\keyword{data}
|
/man/data_dictionary_MFD.Rd
|
no_license
|
evanodell/quanteda.dictionaries
|
R
| false | true | 1,120 |
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/data.R
\docType{data}
\name{data_dictionary_MFD}
\alias{data_dictionary_MFD}
\title{Moral Foundations Dictionary}
\format{An object of class \code{dictionary2} of length 11.}
\source{
\url{http://moralfoundations.org/othermaterials}
}
\usage{
data_dictionary_MFD
}
\description{
A \pkg{quanteda} \link[quanteda]{dictionary} object containing
the Moral Foundations Dictionary, a publicly available dictionaries with
information on the proportions of virtue and vice words for each foundation.
The categories are harm (vice/virtue), fairness (vice/virtue), ingroup (vice/virtue),
authority (vice/virtue), purity (vice/virtue) and morality (general).
}
\references{
Haidt, J., Graham, J., and Nosek, B.A. (2009). "Liberals and Conservatives
Rely on Different Sets of Moral Foundations. \emph{Journal of Personality and Social
Inquiry} 20(2-3): 110-119.
Graham, J., and Haidt, J. (2016). \href{http://moralfoundations.org/othermaterials}{Moral
Foundations Dictionary.}: \url{http://moralfoundations.org/othermaterials}.
}
\keyword{data}
|
cl_trend_plot <- reactive({
validate(
need(!is.null(rawData_data$qw_data), "Click the 'Get QW Data' button")
)
plot_title <- paste(attr(qwData(), "siteInfo")[["station_nm"]],
attr(qwData(), "siteInfo")[["site_no"]], sep = "\n")
chl_plot <- trend_plot(qwData(), plot_title = plot_title)
return(chl_plot)
})
cl_trend_table <- reactive({
validate(
need(!is.null(rawData_data$qw_data), "Click the 'Get QW Data' button")
)
qw_data <- qwData()
qw_table <- kendell_test_5_20_years(dplyr::filter(qw_data,
parm_cd %in% c("00940","99220")),
seasonal = TRUE,
enough_5 = 1,
enough_20 = 1,
date_col = "sample_dt",
value_col = "result_va")
qw_table_DT <- DT::datatable(qw_table,
rownames = FALSE,
extensions = 'Buttons',
options = list(dom = 'tB',
ordering = FALSE,
buttons = c('csv'))) %>%
DT::formatSignif(2:3, digits = 2)
return(qw_table_DT)
})
cl_trend_plot_out <- reactive({
code_out <- paste0(setup(),'
cl_trend <- trend_plot(qw_data,
pcode = c("00940","99220"),
norm_range = c(225,999),
plot_title = plot_title)
cl_trend
kendell_test_5_20_years(dplyr::filter(qw_data,
parm_cd %in% c("00940","99220")),
seasonal = TRUE,
enough_5 = 1,
enough_20 = 1,
date_col = "sample_dt",
value_col = "result_va")
qw_summary(qw_data,
pcode = c("00940","99220"),
norm_range = c(225,999))
# To save:
# Fiddle with height and width (in inches) for best results:
# Change file name extension to save as png.
# ggplot2::ggsave(cl_trend, file="cl_trend.pdf",
# height = 9,
# width = 11)
')
code_out
})
cl_sc_plot <- reactive({
validate(
need(!is.null(rawData_data$qw_data), "Click the 'Get QW Data' button")
)
plot_title <- paste(attr(qwData(), "siteInfo")[["station_nm"]],
attr(qwData(), "siteInfo")[["site_no"]], sep = "\n")
Sc_Cl <- Sc_Cl_plot(qwData(), plot_title = plot_title)
return(Sc_Cl)
})
cl_sc_table_df <- reactive({
validate(
need(!is.null(rawData_data$qw_data), "Please select a data set")
)
sl_cl_table <- Sc_Cl_table(qwData())
return(sl_cl_table)
})
cl_sc_table <- reactive({
sl_cl_table_DT <- DT::datatable(cl_sc_table_df(),
rownames = FALSE,
options = list(dom = 't'))
return(sl_cl_table_DT)
})
cl_sc_plot_out <- reactive({
code_out <- paste0(setup(),'
Sc_Cl <- Sc_Cl_plot(qw_data,
plot_title = plot_title)
Sc_Cl
Sc_Cl_df <- Sc_Cl_table(qw_data)
# To save:
# Fiddle with height and width (in inches) for best results:
# Change file name extension to save as png.
# ggplot2::ggsave(Sc_Cl, file="Sc_Cl.pdf",
# height = 9,
# width = 11)
')
code_out
})
qw1_plot <- reactive({
validate(
need(!is.null(rawData_data$qw_data), "Click the 'Get QW Data' button")
)
pcode <- input$pcode_plot
plot_title <- paste(attr(qwData(), "siteInfo")[["station_nm"]],
attr(qwData(), "siteInfo")[["site_no"]], sep = "\n")
qwplot <- qw_plot(qwData(),
pcode = pcode,
plot_title = plot_title)
return(qwplot)
})
qw1_table <- reactive({
validate(
need(!is.null(rawData_data$qw_data), "Click the 'Get QW Data' button")
)
pcode <- input$pcode_plot
qw_table <- qw_summary(qwData(), pcode = pcode)
qw_table_DT <- DT::datatable(qw_table,
colnames = "",
rownames = FALSE,
extensions = 'Buttons',
options = list(dom = 'tB',
ordering = FALSE,
buttons = c('csv')))
return(qw_table_DT)
})
qw1_plot_out <- reactive({
pcode <- input$pcode_plot
code_out <- paste0(setup(),'
qw_pcodes <- c("', paste(pcode, collapse = '", "'), '")
qw_dt_plot <- qw_plot(qw_data,
plot_title = plot_title)
qw_dt_plot
qw_table <- qw_summary(qw_data, pcode)
# To save:
# Fiddle with height and width (in inches) for best results:
# Change file name extension to save as png.
# ggplot2::ggsave(Sc_Cl, file="Sc_Cl.pdf",
# height = 9,
# width = 11)
')
code_out
})
|
/inst/single_site/qw_plots.R
|
permissive
|
PatrickEslick/HASP
|
R
| false | false | 5,086 |
r
|
cl_trend_plot <- reactive({
validate(
need(!is.null(rawData_data$qw_data), "Click the 'Get QW Data' button")
)
plot_title <- paste(attr(qwData(), "siteInfo")[["station_nm"]],
attr(qwData(), "siteInfo")[["site_no"]], sep = "\n")
chl_plot <- trend_plot(qwData(), plot_title = plot_title)
return(chl_plot)
})
cl_trend_table <- reactive({
validate(
need(!is.null(rawData_data$qw_data), "Click the 'Get QW Data' button")
)
qw_data <- qwData()
qw_table <- kendell_test_5_20_years(dplyr::filter(qw_data,
parm_cd %in% c("00940","99220")),
seasonal = TRUE,
enough_5 = 1,
enough_20 = 1,
date_col = "sample_dt",
value_col = "result_va")
qw_table_DT <- DT::datatable(qw_table,
rownames = FALSE,
extensions = 'Buttons',
options = list(dom = 'tB',
ordering = FALSE,
buttons = c('csv'))) %>%
DT::formatSignif(2:3, digits = 2)
return(qw_table_DT)
})
cl_trend_plot_out <- reactive({
code_out <- paste0(setup(),'
cl_trend <- trend_plot(qw_data,
pcode = c("00940","99220"),
norm_range = c(225,999),
plot_title = plot_title)
cl_trend
kendell_test_5_20_years(dplyr::filter(qw_data,
parm_cd %in% c("00940","99220")),
seasonal = TRUE,
enough_5 = 1,
enough_20 = 1,
date_col = "sample_dt",
value_col = "result_va")
qw_summary(qw_data,
pcode = c("00940","99220"),
norm_range = c(225,999))
# To save:
# Fiddle with height and width (in inches) for best results:
# Change file name extension to save as png.
# ggplot2::ggsave(cl_trend, file="cl_trend.pdf",
# height = 9,
# width = 11)
')
code_out
})
cl_sc_plot <- reactive({
validate(
need(!is.null(rawData_data$qw_data), "Click the 'Get QW Data' button")
)
plot_title <- paste(attr(qwData(), "siteInfo")[["station_nm"]],
attr(qwData(), "siteInfo")[["site_no"]], sep = "\n")
Sc_Cl <- Sc_Cl_plot(qwData(), plot_title = plot_title)
return(Sc_Cl)
})
cl_sc_table_df <- reactive({
validate(
need(!is.null(rawData_data$qw_data), "Please select a data set")
)
sl_cl_table <- Sc_Cl_table(qwData())
return(sl_cl_table)
})
cl_sc_table <- reactive({
sl_cl_table_DT <- DT::datatable(cl_sc_table_df(),
rownames = FALSE,
options = list(dom = 't'))
return(sl_cl_table_DT)
})
cl_sc_plot_out <- reactive({
code_out <- paste0(setup(),'
Sc_Cl <- Sc_Cl_plot(qw_data,
plot_title = plot_title)
Sc_Cl
Sc_Cl_df <- Sc_Cl_table(qw_data)
# To save:
# Fiddle with height and width (in inches) for best results:
# Change file name extension to save as png.
# ggplot2::ggsave(Sc_Cl, file="Sc_Cl.pdf",
# height = 9,
# width = 11)
')
code_out
})
qw1_plot <- reactive({
validate(
need(!is.null(rawData_data$qw_data), "Click the 'Get QW Data' button")
)
pcode <- input$pcode_plot
plot_title <- paste(attr(qwData(), "siteInfo")[["station_nm"]],
attr(qwData(), "siteInfo")[["site_no"]], sep = "\n")
qwplot <- qw_plot(qwData(),
pcode = pcode,
plot_title = plot_title)
return(qwplot)
})
qw1_table <- reactive({
validate(
need(!is.null(rawData_data$qw_data), "Click the 'Get QW Data' button")
)
pcode <- input$pcode_plot
qw_table <- qw_summary(qwData(), pcode = pcode)
qw_table_DT <- DT::datatable(qw_table,
colnames = "",
rownames = FALSE,
extensions = 'Buttons',
options = list(dom = 'tB',
ordering = FALSE,
buttons = c('csv')))
return(qw_table_DT)
})
qw1_plot_out <- reactive({
pcode <- input$pcode_plot
code_out <- paste0(setup(),'
qw_pcodes <- c("', paste(pcode, collapse = '", "'), '")
qw_dt_plot <- qw_plot(qw_data,
plot_title = plot_title)
qw_dt_plot
qw_table <- qw_summary(qw_data, pcode)
# To save:
# Fiddle with height and width (in inches) for best results:
# Change file name extension to save as png.
# ggplot2::ggsave(Sc_Cl, file="Sc_Cl.pdf",
# height = 9,
# width = 11)
')
code_out
})
|
#' Mutate a set of node attribute values
#' @description Within a graph's internal node data
#' frame (ndf), mutate numeric node attribute values
#' using one or more expressions. Optionally, one can
#' specify a different node attribute name and create
#' a new node attribute while retaining the original
#' node attribute and its values.
#' @param graph a graph object of class
#' \code{dgr_graph}.
#' @param node_attr_from the name of the node attribute
#' column from which values will be mutated. An
#' \code{NA} value can be provided here if node
#' attribute names are used in \code{expressions}
#' statements. Note that if \code{NA} is used, a value
#' must be provided for \code{node_attr_to}.
#' @param expressions one or more expressions for
#' mutation of all node attribute values specified by
#' \code{node_attr_from}. To reference the node
#' attribute given in \code{node_attr_from}, use the
#' \code{~} character. Otherwise, all node attributes
#' can be referenced by using the names of those node
#' attributes directly in the expressions. Expressions
#' are evaluated in the order provided.
#' @param node_attr_to an optionally supplied name of
#' a new node attribute to which the mutated values
#' will be applied. This will retain the original node
#' attribute(s) and its values. If \code{NA} is used
#' with \code{node_attr_from}, a value must be provided
#' here (since mutated values must be placed
#' somewhere).
#' @return a graph object of class \code{dgr_graph}.
#' @examples
#' # Create a graph with 3 nodes
#' graph <-
#' create_graph() %>%
#' add_path(n = 3) %>%
#' set_node_attrs(
#' node_attr = width,
#' values = c(3.4, 2.3, 7.2))
#'
#' # Get the graph's internal ndf to show which
#' # node attributes are available
#' get_node_df(graph)
#' #> id type label width
#' #> 1 1 <NA> 1 3.4
#' #> 2 2 <NA> 2 2.3
#' #> 3 3 <NA> 3 7.2
#'
#' # Mutate the `width` node attribute, dividing
#' # each value by 2
#' graph <-
#' graph %>%
#' mutate_node_attrs(
#' node_attr_from = width,
#' expressions = "~ / 2")
#'
#' # Get the graph's internal ndf to show that the
#' # node attribute `width` had its values changed
#' get_node_df(graph)
#' #> id type label width
#' #> 1 1 <NA> 1 1.70
#' #> 2 2 <NA> 2 1.15
#' #> 3 3 <NA> 3 3.60
#'
#' # Create a new node attribute, called `length`,
#' # that is the log of values in `width` plus 2
#' # (and round all values to 2 decimal places)
#' graph <-
#' graph %>%
#' mutate_node_attrs(
#' node_attr_from = width,
#' expressions = "round(log(~) + 2, 2)",
#' node_attr_to = length)
#'
#' # Get the graph's internal ndf to show that
#' # the node attribute values had been mutated
#' # and used as the new node attribute `length`
#' get_node_df(graph)
#' #> id type label width length
#' #> 1 1 <NA> 1 1.70 2.53
#' #> 2 2 <NA> 2 1.15 2.14
#' #> 3 3 <NA> 3 3.60 3.28
#'
#' # Create a new node attribute called `area`,
#' # which is the product of the `width` and
#' # `length` attributes; note that we can provide
#' # NA to `node_attr_from` since we are naming
#' # at least one of the node attributes in the
#' # `expressions` vector (and providing a new
#' # node attribute name: `area`)
#' graph <-
#' graph %>%
#' mutate_node_attrs(
#' node_attr_from = NA,
#' expressions = "width * length",
#' node_attr_to = area)
#'
#' # Get the graph's internal ndf to show that
#' # the node attribute values had been multiplied
#' # together, creating a new node attribute `area`
#' get_node_df(graph)
#' #> id type label width length area
#' #> 1 1 <NA> 1 1.70 2.53 4.301
#' #> 2 2 <NA> 2 1.15 2.14 2.461
#' #> 3 3 <NA> 3 3.60 3.28 11.808
#' @importFrom stringr str_replace_all str_detect
#' @importFrom dplyr mutate_
#' @importFrom rlang enquo UQ
#' @export mutate_node_attrs
mutate_node_attrs <- function(graph,
node_attr_from,
expressions,
node_attr_to = NULL) {
# Get the time of function start
time_function_start <- Sys.time()
node_attr_from <- rlang::enquo(node_attr_from)
node_attr_from <- (rlang::UQ(node_attr_from) %>% paste())[2]
node_attr_to <- rlang::enquo(node_attr_to)
node_attr_to <- (rlang::UQ(node_attr_to) %>% paste())[2]
if (node_attr_to == "NULL") {
node_attr_to <- NULL
}
if (node_attr_from == "NA") {
node_attr_from <- as.character(NA)
}
# Validation: Graph object is valid
if (graph_object_valid(graph) == FALSE) {
stop("The graph object is not valid.")
}
# Extract the graph's ndf
ndf <- get_node_df(graph)
# Get column names from the graph's ndf
column_names_graph <- colnames(ndf)
# Stop function if `node_attr_from` is not one
# of the graph's node attributes
if (!is.na(node_attr_from)) {
if (!any(column_names_graph %in% node_attr_from)) {
stop("The node attribute to mutate is not in the ndf.")
}
}
# Replace `~` with node attribute undergoing mutation
if (!is.na(node_attr_from)) {
expressions <-
stringr::str_replace_all(
expressions, "~", node_attr_from)
}
# Stop function if NA provided for `node_attr_from` but
# no value provided for `node_attr_to`
if (is.na(node_attr_from)) {
if (is.null(node_attr_to)) {
stop("If NA provided for `node_attr_from`, a value must be provided for `node_attr_to`.")
}
}
# If NA provided for `node_attr_from`, ensure that at
# least one node attribute value exists in each of the
# provided expressions
if (is.na(node_attr_from)) {
for (i in 1:length(expressions)) {
if (all(
stringr::str_detect(
expressions[i],
column_names_graph[-1]) == FALSE)) {
stop("At least one node attribute should exist in `expressions`.")
}
}
}
if (!is.null(node_attr_to)) {
# Stop function if `node_attr_to` is `id`
if (node_attr_to == "id") {
stop("You cannot `id` as the value for `node_attr_to`.")
}
for (i in 1:length(expressions)) {
ndf <-
ndf %>%
dplyr::mutate_(.dots = setNames(list(expressions[i]), node_attr_to))
}
} else {
for (i in 1:length(expressions)) {
ndf <-
ndf %>%
dplyr::mutate_(.dots = setNames(list(expressions[i]), node_attr_from))
}
}
# Update the graph
graph$nodes_df <- ndf
# Update the `graph_log` df with an action
graph$graph_log <-
add_action_to_log(
graph_log = graph$graph_log,
version_id = nrow(graph$graph_log) + 1,
function_used = "mutate_node_attrs",
time_modified = time_function_start,
duration = graph_function_duration(time_function_start),
nodes = nrow(graph$nodes_df),
edges = nrow(graph$edges_df))
# Write graph backup if the option is set
if (graph$graph_info$write_backups) {
save_graph_as_rds(graph = graph)
}
graph
}
|
/R/mutate_node_attrs.R
|
no_license
|
applied-statistic-using-r/DiagrammeR
|
R
| false | false | 6,967 |
r
|
#' Mutate a set of node attribute values
#' @description Within a graph's internal node data
#' frame (ndf), mutate numeric node attribute values
#' using one or more expressions. Optionally, one can
#' specify a different node attribute name and create
#' a new node attribute while retaining the original
#' node attribute and its values.
#' @param graph a graph object of class
#' \code{dgr_graph}.
#' @param node_attr_from the name of the node attribute
#' column from which values will be mutated. An
#' \code{NA} value can be provided here if node
#' attribute names are used in \code{expressions}
#' statements. Note that if \code{NA} is used, a value
#' must be provided for \code{node_attr_to}.
#' @param expressions one or more expressions for
#' mutation of all node attribute values specified by
#' \code{node_attr_from}. To reference the node
#' attribute given in \code{node_attr_from}, use the
#' \code{~} character. Otherwise, all node attributes
#' can be referenced by using the names of those node
#' attributes directly in the expressions. Expressions
#' are evaluated in the order provided.
#' @param node_attr_to an optionally supplied name of
#' a new node attribute to which the mutated values
#' will be applied. This will retain the original node
#' attribute(s) and its values. If \code{NA} is used
#' with \code{node_attr_from}, a value must be provided
#' here (since mutated values must be placed
#' somewhere).
#' @return a graph object of class \code{dgr_graph}.
#' @examples
#' # Create a graph with 3 nodes
#' graph <-
#' create_graph() %>%
#' add_path(n = 3) %>%
#' set_node_attrs(
#' node_attr = width,
#' values = c(3.4, 2.3, 7.2))
#'
#' # Get the graph's internal ndf to show which
#' # node attributes are available
#' get_node_df(graph)
#' #> id type label width
#' #> 1 1 <NA> 1 3.4
#' #> 2 2 <NA> 2 2.3
#' #> 3 3 <NA> 3 7.2
#'
#' # Mutate the `width` node attribute, dividing
#' # each value by 2
#' graph <-
#' graph %>%
#' mutate_node_attrs(
#' node_attr_from = width,
#' expressions = "~ / 2")
#'
#' # Get the graph's internal ndf to show that the
#' # node attribute `width` had its values changed
#' get_node_df(graph)
#' #> id type label width
#' #> 1 1 <NA> 1 1.70
#' #> 2 2 <NA> 2 1.15
#' #> 3 3 <NA> 3 3.60
#'
#' # Create a new node attribute, called `length`,
#' # that is the log of values in `width` plus 2
#' # (and round all values to 2 decimal places)
#' graph <-
#' graph %>%
#' mutate_node_attrs(
#' node_attr_from = width,
#' expressions = "round(log(~) + 2, 2)",
#' node_attr_to = length)
#'
#' # Get the graph's internal ndf to show that
#' # the node attribute values had been mutated
#' # and used as the new node attribute `length`
#' get_node_df(graph)
#' #> id type label width length
#' #> 1 1 <NA> 1 1.70 2.53
#' #> 2 2 <NA> 2 1.15 2.14
#' #> 3 3 <NA> 3 3.60 3.28
#'
#' # Create a new node attribute called `area`,
#' # which is the product of the `width` and
#' # `length` attributes; note that we can provide
#' # NA to `node_attr_from` since we are naming
#' # at least one of the node attributes in the
#' # `expressions` vector (and providing a new
#' # node attribute name: `area`)
#' graph <-
#' graph %>%
#' mutate_node_attrs(
#' node_attr_from = NA,
#' expressions = "width * length",
#' node_attr_to = area)
#'
#' # Get the graph's internal ndf to show that
#' # the node attribute values had been multiplied
#' # together, creating a new node attribute `area`
#' get_node_df(graph)
#' #> id type label width length area
#' #> 1 1 <NA> 1 1.70 2.53 4.301
#' #> 2 2 <NA> 2 1.15 2.14 2.461
#' #> 3 3 <NA> 3 3.60 3.28 11.808
#' @importFrom stringr str_replace_all str_detect
#' @importFrom dplyr mutate_
#' @importFrom rlang enquo UQ
#' @export mutate_node_attrs
mutate_node_attrs <- function(graph,
node_attr_from,
expressions,
node_attr_to = NULL) {
# Get the time of function start
time_function_start <- Sys.time()
node_attr_from <- rlang::enquo(node_attr_from)
node_attr_from <- (rlang::UQ(node_attr_from) %>% paste())[2]
node_attr_to <- rlang::enquo(node_attr_to)
node_attr_to <- (rlang::UQ(node_attr_to) %>% paste())[2]
if (node_attr_to == "NULL") {
node_attr_to <- NULL
}
if (node_attr_from == "NA") {
node_attr_from <- as.character(NA)
}
# Validation: Graph object is valid
if (graph_object_valid(graph) == FALSE) {
stop("The graph object is not valid.")
}
# Extract the graph's ndf
ndf <- get_node_df(graph)
# Get column names from the graph's ndf
column_names_graph <- colnames(ndf)
# Stop function if `node_attr_from` is not one
# of the graph's node attributes
if (!is.na(node_attr_from)) {
if (!any(column_names_graph %in% node_attr_from)) {
stop("The node attribute to mutate is not in the ndf.")
}
}
# Replace `~` with node attribute undergoing mutation
if (!is.na(node_attr_from)) {
expressions <-
stringr::str_replace_all(
expressions, "~", node_attr_from)
}
# Stop function if NA provided for `node_attr_from` but
# no value provided for `node_attr_to`
if (is.na(node_attr_from)) {
if (is.null(node_attr_to)) {
stop("If NA provided for `node_attr_from`, a value must be provided for `node_attr_to`.")
}
}
# If NA provided for `node_attr_from`, ensure that at
# least one node attribute value exists in each of the
# provided expressions
if (is.na(node_attr_from)) {
for (i in 1:length(expressions)) {
if (all(
stringr::str_detect(
expressions[i],
column_names_graph[-1]) == FALSE)) {
stop("At least one node attribute should exist in `expressions`.")
}
}
}
if (!is.null(node_attr_to)) {
# Stop function if `node_attr_to` is `id`
if (node_attr_to == "id") {
stop("You cannot `id` as the value for `node_attr_to`.")
}
for (i in 1:length(expressions)) {
ndf <-
ndf %>%
dplyr::mutate_(.dots = setNames(list(expressions[i]), node_attr_to))
}
} else {
for (i in 1:length(expressions)) {
ndf <-
ndf %>%
dplyr::mutate_(.dots = setNames(list(expressions[i]), node_attr_from))
}
}
# Update the graph
graph$nodes_df <- ndf
# Update the `graph_log` df with an action
graph$graph_log <-
add_action_to_log(
graph_log = graph$graph_log,
version_id = nrow(graph$graph_log) + 1,
function_used = "mutate_node_attrs",
time_modified = time_function_start,
duration = graph_function_duration(time_function_start),
nodes = nrow(graph$nodes_df),
edges = nrow(graph$edges_df))
# Write graph backup if the option is set
if (graph$graph_info$write_backups) {
save_graph_as_rds(graph = graph)
}
graph
}
|
#filter out snp positions that have less than 4 reads to eliminate the structure I found in the data
#######
#snp<-read.table("/Users/wendy/Dropbox/Sol96_LogitRegression/Minor_Major_SNP_data.txt",header=T,sep=",")
geno.reads<-read.table("/Users/wendy/Dropbox/Sol96_LogitRegression/vcf_geno_depth_filter_200KSNP.txt",header=T,sep="\t")
reads.mat<-as.matrix(geno.reads[,9:99])
#row.col.idx<-which(reads.mat < 4, arr.ind =TRUE)
pos.con <-paste(geno.reads$CHROM,geno.reads$POS,geno.reads$REF, sep="_")
row.names(reads.mat)<-pos.con
#######
#use file below for PCA: Genoytpes coded 0,0.5,1
#snp<-read.table("/Users/wendy/Dropbox/Sol96_LogitRegression/LogitRegression_Files/Sol96_Freq_min2reads.55.Major_Minor_Allele.txt",header=T,sep=",")
#use file below for Ordinal Log Regression: genotypes coded by genotype freq --> 1,2,3
snp <-read.table("/Users/wendy/Dropbox/Sol96_LogitRegression/LogitRegression_Files/LogisticReg_GenoFrq_Recode_Cat.txt",header=T,sep=",")
#file key for Log Reg analysis: identifies the genotypes (0,0.5,1) from genotype freq file above
snp.key <- read.table("/Users/wendy/Dropbox/Sol96_LogitRegression/LogitRegression_Files/LogisticReg_GenoFrq_Recode_Cat_Key.txt",header=T,sep=",")
snp.60<-read.table("/Users/wendy/Dropbox/Sol96_LogitRegression/LogitRegression_Files/Sol96_Freq_min2reads.60.Major_Minor_Allele.txt",header=T,sep=",")
het.55<-read.table("/Users/wendy/Dropbox/Sol96_LogitRegression/LogitRegression_Files/Sol96_Freq_min2reads.55.het",header=T, sep="\t" )
het.60<-read.table("/Users/wendy/Dropbox/Sol96_LogitRegression/LogitRegression_Files/Sol96_Freq_min2reads.60.het",header=T, sep="\t" )
#ref vcftools for genotype filter: https://github.com/jpuritz/dDocent/blob/master/tutorials/Filtering%20Tutorial.md
###Logit Regression#######################
#Preparing snp.pf dataframe for Logit regression
snp.frq<-t(snp.pos)
class(snp.frq) <- "numeric"
#preparing phenotype/predictor data for logit regression
base<-read.csv("/Users/wendy/Dropbox/Tails_Data_Soliman250/GPS_96tails/GPS_BaseCamp_Soliman_Points.csv")
sol96<-read.csv("/Users/wendy/Dropbox/Tails_Data_Soliman250/Sol96_Pheno_Analysis/Pheno_Sol_Seq96_Orig.csv")
geno.names<-colnames(snp[,4:length(colnames(snp))])
avgec96<-aggregate(sol96[,6],list(line=sol96$line),mean)
base96<-base[base[,1] %in% avgec96[,1],]
mean.seed<-aggregate(sol96[,9],list(line=sol96$line),mean,na.rm=T)
mean.leaf<-aggregate(sol96[,27],list(line=sol96$line),mean, na.rm=T)
mean.flo96<-aggregate(sol96[,34],list(line=sol96$line),mean,na.rm=T)
mean.pod<-aggregate(sol96[,37],list(line=sol96$line),mean, na.rm=T)
pheno<-cbind(base96[,c(1,3:5)],avgec96[,2],mean.seed[,2],mean.leaf[,2],mean.flo96[,2],mean.pod[,2])
pheno<-pheno[,-1]
colnames(pheno)<-c("Lat","Long","Ele","EC","SeedMass","LeafNum","FlowerTime","PodNum")
rownames(pheno)<-geno.names
#removing rows/genotypes with NA values from pheno and then corresponding snp.frq data
row.has.na <- apply(pheno, 1, function(x){any(is.na(x))})
remove.geno<-names(which(row.has.na=="TRUE"))
pheno1<-pheno[!(rownames(pheno) %in% remove.geno),]
snp.frq1<-snp.frq[!(rownames(snp.frq) %in% remove.geno),]
#STREAMLINING the OLR to analyze ~100K snps independently
#NOTE: This model will only work for response variable with 3 or more levels or categories
library(foreign)
library(ggplot2)
library(MASS)
library(Hmisc)
library(reshape2)
#####Components for function
my.snp<-snp.frq[,3]
polr(as.factor(my.snp) ~ lon + ele + ec, Hess=TRUE)->m
(t.val<-coef(summary(m))[,3])
pnorm(abs(t.val),lower.tail=FALSE)*2
#intercept == cutpoints:
#####
#ERROR:OLR will only analyze 3 or more response levels/categories. Some of the snps have < 3 levels, so we must use tryCatch method to catch the error and continue to the next snp
#http://stackoverflow.com/questions/8093914/skip-to-next-value-of-loop-upon-error-in-r-trycatch
#####FINAL SCRIPT to run Ordered logistic regression
snp.frq1<-snp.frq[,1:4643]
snp.frq2<-snp.frq[,4645:12766]
snp.frq3<-snp.frq[,12768:16868]
snp.frq4<-snp.frq[,16870:length(snp.frq[1,])]
lat<-pheno[,1]
lon<-pheno[,2]
ele<-pheno[,3]
ec<-pheno[,4]
###Pvalue matrix for the additive model
i=1
do.olr<-function(i){
print(i)
my.snp<-snp.frq[,i]
error<-tryCatch(polr(as.factor(my.snp) ~ lon + log(ele) + log(ec), Hess=TRUE,method="logistic",na.action=na.omit), error=function(e) e)
# e= is any error messages that originate in the expression that you are tryCatch - ing.
#print(error) This tells you the class of the error
#class(error) This returns an object that can be used for a conditional statement below
if(!inherits(error,"simpleError")){ #if the snp doesn't generate an error, run ols model and calculate pval
model<-polr(as.factor(my.snp) ~ lat + lon + log(ele) + log(ec), Hess=TRUE, method="logistic",na.action=na.omit)
t.val<-coef(summary(model))[,3] #extracting t.val from coefficient table
pnorm(abs(t.val),lower.tail=FALSE)*2
} else{c("NA","NA","NA","NA","NA","NA")} #returns NA's if there is an error (there are six variables in the output)
}
sapply(1:length(snp.frq[1,]),do.olr)->ols.pval
#ols.pval: columns correspond to snp position
#rows correspond to lat, lon, ele, ec, intercept 0|0.5, intercept 0.5|1
gene_id<-colnames(snp.frq)
variable_id<-rownames(ols.pval)
colnames(ols.pval)<-gene_id #add gene id to column names
pval<-t(ols.pval) #transpose matrix column-->row
#Filter out the snps with less 3 levels before fdr correction: remove snps with NA's
class(pval)<-"numeric"
idx<-apply(pval, 1, function(x) all(is.na(x)))
pval<-pval[!idx,] #After filtering there are 5225 snps that were interrogated
##FDR correction for multiple testing
i=1
correct.multi.test<-function(i){
p.adjust(as.numeric(pval[,i]),method="fdr")
}
sapply(1:length(pval[1,]),correct.multi.test)->fdr
gene_id<-rownames(pval)
variable_id<-colnames(pval)
colnames(fdr)<-variable_id
rownames(fdr)<-gene_id
fdr1<-fdr
fdr2<-fdr
fdr3<-fdr
fdr4<-fdr
fdr<-rbind(fdr1,fdr2,fdr3,fdr4)
fdr.fin <-as.data.frame(cbind(rownames(fdr),fdr))
colnames(fdr.fin)[1]<-"SNP_Pos_Ref"
write.table(fdr.fin,"/Users/wendy/Dropbox/Sol96_LogitRegression/LogitRegression_Files/FDR_NONFiltered_Logit_pval.txt",
col.names=TRUE,row.names = FALSE,quote=FALSE,sep=",")
#FDR < 0.05
sig.lat<-fdr[which(fdr[,1] < 0.05),]
sig.lon<-fdr[which(fdr[,2] < 0.05),]
sig.ele<-fdr[which(fdr[,3] < 0.05),]
sig.ec<-fdr[which(fdr[,4] < 0.05),]
###SNPs filtered at 55% criteria
#filter out pval = 0 from data
# snp.frq[,1:4643]
sig.lat1<-sig.lat[which(sig.lat[,1]!=0),1]
sig.lon1<-sig.lon[which(sig.lon[,2]!=0),2]
sig.ele1<-sig.ele[which(sig.ele[,3]!=0),3]
sig.ec1<-sig.ec[which(sig.ec[,4]!=0),4]
#snp.frq[,4645:12766]
sig.lat2<-sig.lat[which(sig.lat[,1]!=0),1]
sig.lon2<-sig.lon[which(sig.lon[,2]!=0),2]
sig.ele2<-sig.ele[which(sig.ele[,3]!=0),3]
sig.ec2<-sig.ec[which(sig.ec[,4]!=0),4]
#snp.frq[,12768:16868]
sig.lat3<-sig.lat[which(sig.lat[,1]!=0),1]
sig.lon3<-sig.lon[which(sig.lon[,2]!=0),2]
sig.ele3<-sig.ele[which(sig.ele[,3]!=0),3]
sig.ec3<-sig.ec[which(sig.ec[,4]!=0),4]
#snp.frq[,16870:length(snp.frq[1,])]
sig.lat4<-sig.lat[which(sig.lat[,1]!=0),1]
sig.lon4<-sig.lon[which(sig.lon[,2]!=0),2]
sig.ele4<-sig.ele[which(sig.ele[,3]!=0),3]
sig.ec4<-sig.ec[which(sig.ec[,4]!=0),4]
##Combine
#SNPs filtered at 55% criteria
sig.lat.fdr <- c(sig.lat1,sig.lat2,sig.lat3,sig.lat4) #6192 snps
sig.lon.fdr <- c(sig.lon1,sig.lon2,sig.lon3,sig.lon4) #300 snps
sig.ele.fdr <- c(sig.ele1,sig.ele2,sig.ele3,sig.ele4) #191 snps
sig.ec.fdr <- c(sig.ec1,sig.ec2,sig.ec3,sig.ec4) #60 snps
sig.lat.fdr.55 <-cbind(names(sig.lat.fdr),as.data.frame(sig.lat.fdr),rep("lat",times=length(sig.lat.fdr)))
sig.lon.fdr.55 <-cbind(names(sig.lon.fdr),as.data.frame(sig.lon.fdr),rep("lon",times=length(sig.lon.fdr)))
sig.ele.fdr.55 <-cbind(names(sig.ele.fdr),as.data.frame(sig.ele.fdr),rep("ele",times=length(sig.ele.fdr)))
sig.ec.fdr.55 <-cbind(names(sig.ec.fdr),as.data.frame(sig.ec.fdr),rep("ec",times=length(sig.ec.fdr)))
colnames(sig.ec.fdr.55) <- c("SNP_Pos","Pval_FDR","Factor")
sig.all.fdr.55 <-rbind(sig.lat.fdr.55, sig.lon.fdr.55, sig.ele.fdr.55, sig.ec.fdr.55)
write.table(sig.all.fdr.55,"/Users/wendy/Dropbox/Sol96_LogitRegression/LogitRegression_Files/Sig.Lat.Lon.Ele.EC.fdr.55.txt",quote=FALSE, row.names = FALSE,col.names = TRUE,sep="\t")
#What is the relationship between STRUCTURE and heterozygosity estimates?
plot(str.sort.geno[,6],het[,5],col=ifelse(str.sort.geno[,8]=="hap1","black","red"),pch=19,xlab="Proportion of Haplotype 1 (Dark blue)", ylab="Inbreeding coefficient (F)")
#What is the relationship between heterozygosity estimates and genetic diversity
idx<-c(1:96)
het<-cbind(idx,het)
het.sort<-het[order(het[,6],decreasing=FALSE),]
het.num<-c(rep("het1",times=length(which(het.sort[,6]<0))),rep("het2",times=length(which(het.sort[,6]>0))))
het1<-cbind(het.sort,het.num)
het.sort.geno<-het1[order(het1[,1]),]
plot(pc1, pc2, col=ifelse(het.sort.geno[,7]=="het1","black","red"),xlab="PC1 (71.7%)",ylab="PC2 (1.2%)",pch=19,main="PC1-PC2 by Het")
|
/Regression_Scripts/LogisticRegression_Script.R
|
no_license
|
wendyvu216/Oil-Palm-Genetic-Diversity-and-Conservation-Program
|
R
| false | false | 9,012 |
r
|
#filter out snp positions that have less than 4 reads to eliminate the structure I found in the data
#######
#snp<-read.table("/Users/wendy/Dropbox/Sol96_LogitRegression/Minor_Major_SNP_data.txt",header=T,sep=",")
geno.reads<-read.table("/Users/wendy/Dropbox/Sol96_LogitRegression/vcf_geno_depth_filter_200KSNP.txt",header=T,sep="\t")
reads.mat<-as.matrix(geno.reads[,9:99])
#row.col.idx<-which(reads.mat < 4, arr.ind =TRUE)
pos.con <-paste(geno.reads$CHROM,geno.reads$POS,geno.reads$REF, sep="_")
row.names(reads.mat)<-pos.con
#######
#use file below for PCA: Genoytpes coded 0,0.5,1
#snp<-read.table("/Users/wendy/Dropbox/Sol96_LogitRegression/LogitRegression_Files/Sol96_Freq_min2reads.55.Major_Minor_Allele.txt",header=T,sep=",")
#use file below for Ordinal Log Regression: genotypes coded by genotype freq --> 1,2,3
snp <-read.table("/Users/wendy/Dropbox/Sol96_LogitRegression/LogitRegression_Files/LogisticReg_GenoFrq_Recode_Cat.txt",header=T,sep=",")
#file key for Log Reg analysis: identifies the genotypes (0,0.5,1) from genotype freq file above
snp.key <- read.table("/Users/wendy/Dropbox/Sol96_LogitRegression/LogitRegression_Files/LogisticReg_GenoFrq_Recode_Cat_Key.txt",header=T,sep=",")
snp.60<-read.table("/Users/wendy/Dropbox/Sol96_LogitRegression/LogitRegression_Files/Sol96_Freq_min2reads.60.Major_Minor_Allele.txt",header=T,sep=",")
het.55<-read.table("/Users/wendy/Dropbox/Sol96_LogitRegression/LogitRegression_Files/Sol96_Freq_min2reads.55.het",header=T, sep="\t" )
het.60<-read.table("/Users/wendy/Dropbox/Sol96_LogitRegression/LogitRegression_Files/Sol96_Freq_min2reads.60.het",header=T, sep="\t" )
#ref vcftools for genotype filter: https://github.com/jpuritz/dDocent/blob/master/tutorials/Filtering%20Tutorial.md
###Logit Regression#######################
#Preparing snp.pf dataframe for Logit regression
snp.frq<-t(snp.pos)
class(snp.frq) <- "numeric"
#preparing phenotype/predictor data for logit regression
base<-read.csv("/Users/wendy/Dropbox/Tails_Data_Soliman250/GPS_96tails/GPS_BaseCamp_Soliman_Points.csv")
sol96<-read.csv("/Users/wendy/Dropbox/Tails_Data_Soliman250/Sol96_Pheno_Analysis/Pheno_Sol_Seq96_Orig.csv")
geno.names<-colnames(snp[,4:length(colnames(snp))])
avgec96<-aggregate(sol96[,6],list(line=sol96$line),mean)
base96<-base[base[,1] %in% avgec96[,1],]
mean.seed<-aggregate(sol96[,9],list(line=sol96$line),mean,na.rm=T)
mean.leaf<-aggregate(sol96[,27],list(line=sol96$line),mean, na.rm=T)
mean.flo96<-aggregate(sol96[,34],list(line=sol96$line),mean,na.rm=T)
mean.pod<-aggregate(sol96[,37],list(line=sol96$line),mean, na.rm=T)
pheno<-cbind(base96[,c(1,3:5)],avgec96[,2],mean.seed[,2],mean.leaf[,2],mean.flo96[,2],mean.pod[,2])
pheno<-pheno[,-1]
colnames(pheno)<-c("Lat","Long","Ele","EC","SeedMass","LeafNum","FlowerTime","PodNum")
rownames(pheno)<-geno.names
#removing rows/genotypes with NA values from pheno and then corresponding snp.frq data
row.has.na <- apply(pheno, 1, function(x){any(is.na(x))})
remove.geno<-names(which(row.has.na=="TRUE"))
pheno1<-pheno[!(rownames(pheno) %in% remove.geno),]
snp.frq1<-snp.frq[!(rownames(snp.frq) %in% remove.geno),]
#STREAMLINING the OLR to analyze ~100K snps independently
#NOTE: This model will only work for response variable with 3 or more levels or categories
library(foreign)
library(ggplot2)
library(MASS)
library(Hmisc)
library(reshape2)
#####Components for function
my.snp<-snp.frq[,3]
polr(as.factor(my.snp) ~ lon + ele + ec, Hess=TRUE)->m
(t.val<-coef(summary(m))[,3])
pnorm(abs(t.val),lower.tail=FALSE)*2
#intercept == cutpoints:
#####
#ERROR:OLR will only analyze 3 or more response levels/categories. Some of the snps have < 3 levels, so we must use tryCatch method to catch the error and continue to the next snp
#http://stackoverflow.com/questions/8093914/skip-to-next-value-of-loop-upon-error-in-r-trycatch
#####FINAL SCRIPT to run Ordered logistic regression
snp.frq1<-snp.frq[,1:4643]
snp.frq2<-snp.frq[,4645:12766]
snp.frq3<-snp.frq[,12768:16868]
snp.frq4<-snp.frq[,16870:length(snp.frq[1,])]
lat<-pheno[,1]
lon<-pheno[,2]
ele<-pheno[,3]
ec<-pheno[,4]
###Pvalue matrix for the additive model
i=1
do.olr<-function(i){
print(i)
my.snp<-snp.frq[,i]
error<-tryCatch(polr(as.factor(my.snp) ~ lon + log(ele) + log(ec), Hess=TRUE,method="logistic",na.action=na.omit), error=function(e) e)
# e= is any error messages that originate in the expression that you are tryCatch - ing.
#print(error) This tells you the class of the error
#class(error) This returns an object that can be used for a conditional statement below
if(!inherits(error,"simpleError")){ #if the snp doesn't generate an error, run ols model and calculate pval
model<-polr(as.factor(my.snp) ~ lat + lon + log(ele) + log(ec), Hess=TRUE, method="logistic",na.action=na.omit)
t.val<-coef(summary(model))[,3] #extracting t.val from coefficient table
pnorm(abs(t.val),lower.tail=FALSE)*2
} else{c("NA","NA","NA","NA","NA","NA")} #returns NA's if there is an error (there are six variables in the output)
}
sapply(1:length(snp.frq[1,]),do.olr)->ols.pval
#ols.pval: columns correspond to snp position
#rows correspond to lat, lon, ele, ec, intercept 0|0.5, intercept 0.5|1
gene_id<-colnames(snp.frq)
variable_id<-rownames(ols.pval)
colnames(ols.pval)<-gene_id #add gene id to column names
pval<-t(ols.pval) #transpose matrix column-->row
#Filter out the snps with less 3 levels before fdr correction: remove snps with NA's
class(pval)<-"numeric"
idx<-apply(pval, 1, function(x) all(is.na(x)))
pval<-pval[!idx,] #After filtering there are 5225 snps that were interrogated
##FDR correction for multiple testing
i=1
correct.multi.test<-function(i){
p.adjust(as.numeric(pval[,i]),method="fdr")
}
sapply(1:length(pval[1,]),correct.multi.test)->fdr
gene_id<-rownames(pval)
variable_id<-colnames(pval)
colnames(fdr)<-variable_id
rownames(fdr)<-gene_id
fdr1<-fdr
fdr2<-fdr
fdr3<-fdr
fdr4<-fdr
fdr<-rbind(fdr1,fdr2,fdr3,fdr4)
fdr.fin <-as.data.frame(cbind(rownames(fdr),fdr))
colnames(fdr.fin)[1]<-"SNP_Pos_Ref"
write.table(fdr.fin,"/Users/wendy/Dropbox/Sol96_LogitRegression/LogitRegression_Files/FDR_NONFiltered_Logit_pval.txt",
col.names=TRUE,row.names = FALSE,quote=FALSE,sep=",")
#FDR < 0.05
sig.lat<-fdr[which(fdr[,1] < 0.05),]
sig.lon<-fdr[which(fdr[,2] < 0.05),]
sig.ele<-fdr[which(fdr[,3] < 0.05),]
sig.ec<-fdr[which(fdr[,4] < 0.05),]
###SNPs filtered at 55% criteria
#filter out pval = 0 from data
# snp.frq[,1:4643]
sig.lat1<-sig.lat[which(sig.lat[,1]!=0),1]
sig.lon1<-sig.lon[which(sig.lon[,2]!=0),2]
sig.ele1<-sig.ele[which(sig.ele[,3]!=0),3]
sig.ec1<-sig.ec[which(sig.ec[,4]!=0),4]
#snp.frq[,4645:12766]
sig.lat2<-sig.lat[which(sig.lat[,1]!=0),1]
sig.lon2<-sig.lon[which(sig.lon[,2]!=0),2]
sig.ele2<-sig.ele[which(sig.ele[,3]!=0),3]
sig.ec2<-sig.ec[which(sig.ec[,4]!=0),4]
#snp.frq[,12768:16868]
sig.lat3<-sig.lat[which(sig.lat[,1]!=0),1]
sig.lon3<-sig.lon[which(sig.lon[,2]!=0),2]
sig.ele3<-sig.ele[which(sig.ele[,3]!=0),3]
sig.ec3<-sig.ec[which(sig.ec[,4]!=0),4]
#snp.frq[,16870:length(snp.frq[1,])]
sig.lat4<-sig.lat[which(sig.lat[,1]!=0),1]
sig.lon4<-sig.lon[which(sig.lon[,2]!=0),2]
sig.ele4<-sig.ele[which(sig.ele[,3]!=0),3]
sig.ec4<-sig.ec[which(sig.ec[,4]!=0),4]
##Combine
#SNPs filtered at 55% criteria
sig.lat.fdr <- c(sig.lat1,sig.lat2,sig.lat3,sig.lat4) #6192 snps
sig.lon.fdr <- c(sig.lon1,sig.lon2,sig.lon3,sig.lon4) #300 snps
sig.ele.fdr <- c(sig.ele1,sig.ele2,sig.ele3,sig.ele4) #191 snps
sig.ec.fdr <- c(sig.ec1,sig.ec2,sig.ec3,sig.ec4) #60 snps
sig.lat.fdr.55 <-cbind(names(sig.lat.fdr),as.data.frame(sig.lat.fdr),rep("lat",times=length(sig.lat.fdr)))
sig.lon.fdr.55 <-cbind(names(sig.lon.fdr),as.data.frame(sig.lon.fdr),rep("lon",times=length(sig.lon.fdr)))
sig.ele.fdr.55 <-cbind(names(sig.ele.fdr),as.data.frame(sig.ele.fdr),rep("ele",times=length(sig.ele.fdr)))
sig.ec.fdr.55 <-cbind(names(sig.ec.fdr),as.data.frame(sig.ec.fdr),rep("ec",times=length(sig.ec.fdr)))
colnames(sig.ec.fdr.55) <- c("SNP_Pos","Pval_FDR","Factor")
sig.all.fdr.55 <-rbind(sig.lat.fdr.55, sig.lon.fdr.55, sig.ele.fdr.55, sig.ec.fdr.55)
write.table(sig.all.fdr.55,"/Users/wendy/Dropbox/Sol96_LogitRegression/LogitRegression_Files/Sig.Lat.Lon.Ele.EC.fdr.55.txt",quote=FALSE, row.names = FALSE,col.names = TRUE,sep="\t")
#What is the relationship between STRUCTURE and heterozygosity estimates?
plot(str.sort.geno[,6],het[,5],col=ifelse(str.sort.geno[,8]=="hap1","black","red"),pch=19,xlab="Proportion of Haplotype 1 (Dark blue)", ylab="Inbreeding coefficient (F)")
#What is the relationship between heterozygosity estimates and genetic diversity
idx<-c(1:96)
het<-cbind(idx,het)
het.sort<-het[order(het[,6],decreasing=FALSE),]
het.num<-c(rep("het1",times=length(which(het.sort[,6]<0))),rep("het2",times=length(which(het.sort[,6]>0))))
het1<-cbind(het.sort,het.num)
het.sort.geno<-het1[order(het1[,1]),]
plot(pc1, pc2, col=ifelse(het.sort.geno[,7]=="het1","black","red"),xlab="PC1 (71.7%)",ylab="PC2 (1.2%)",pch=19,main="PC1-PC2 by Het")
|
list2matrix.bma = function(x, what, which.models=NULL) {
namesx = x$namesx
if (is.null(which.models)) which.models= 1:x$n.models
listobj = x[[what]][which.models]
which = x$which[which.models]
n.models = length(which.models)
p = length(namesx)
mat = matrix(0, nrow=n.models, ncol=p)
for (i in 1:n.models) {
mat[i, which[[i]]+1] = listobj[[i]]
}
colnames(mat) = namesx
return(mat)
}
list2matrix.which = function(x, which.models=NULL) {
namesx = x$namesx
listobj = x$which
if (!is.null(which.models)) listobj = listobj[which.models]
p = length(namesx)
mat = t(sapply(listobj,
function(x, dimp) {
xx = rep(0,dimp)
xx[x+1] = 1
xx},
p))
colnames(mat) = namesx
mat}
which.matrix = function(which, n.vars) {
mat = t(sapply(which,
function(x, dimp) {
xx = rep(0,dimp)
xx[x+1] = 1
xx},
n.vars))
mat}
bin2int = function(model) {
if (length(model) > 1) {
i = sum(2^(model[-1] - 1)) + 1}
else{ i = 1}
# if (!is.integer(i)) warning("Exceeded the largest integer for this machine")
return(unlist(i))
}
|
/supplementaries/Mode Jumping MCMC/supplementary/examples/BAS archive/BAS/R/as.matrix.R
|
no_license
|
aliaksah/EMJMCMC2016
|
R
| false | false | 1,209 |
r
|
list2matrix.bma = function(x, what, which.models=NULL) {
namesx = x$namesx
if (is.null(which.models)) which.models= 1:x$n.models
listobj = x[[what]][which.models]
which = x$which[which.models]
n.models = length(which.models)
p = length(namesx)
mat = matrix(0, nrow=n.models, ncol=p)
for (i in 1:n.models) {
mat[i, which[[i]]+1] = listobj[[i]]
}
colnames(mat) = namesx
return(mat)
}
list2matrix.which = function(x, which.models=NULL) {
namesx = x$namesx
listobj = x$which
if (!is.null(which.models)) listobj = listobj[which.models]
p = length(namesx)
mat = t(sapply(listobj,
function(x, dimp) {
xx = rep(0,dimp)
xx[x+1] = 1
xx},
p))
colnames(mat) = namesx
mat}
which.matrix = function(which, n.vars) {
mat = t(sapply(which,
function(x, dimp) {
xx = rep(0,dimp)
xx[x+1] = 1
xx},
n.vars))
mat}
bin2int = function(model) {
if (length(model) > 1) {
i = sum(2^(model[-1] - 1)) + 1}
else{ i = 1}
# if (!is.integer(i)) warning("Exceeded the largest integer for this machine")
return(unlist(i))
}
|
# server.R
library(dplyr)
library(shiny)
library(plotly)
# Read in data
source('./scripts/build_map.R')
df <- read.csv('./data/electoral_college.csv', stringsAsFactors = FALSE)
state_codes <- read.csv('./data/state_codes.csv', stringsAsFactors = FALSE)
# Join together state.codes and df
joined_data <- left_join(df, state_codes, by="state")
# Compute the electoral votes per 100K people in each state
joined_data <- joined_data %>% mutate(ratio = votes/population * 100000)
# Define server function
server <- function(input, output) {
# Render a plotly object that returns your map
ouput$map <- renderPlotly({
return(build_map(joined_data, input$mapvar))
})
}
|
/chapter-19-exercises/exercise-6/app_server.R
|
permissive
|
sumeetwaraich/book-exercises
|
R
| false | false | 675 |
r
|
# server.R
library(dplyr)
library(shiny)
library(plotly)
# Read in data
source('./scripts/build_map.R')
df <- read.csv('./data/electoral_college.csv', stringsAsFactors = FALSE)
state_codes <- read.csv('./data/state_codes.csv', stringsAsFactors = FALSE)
# Join together state.codes and df
joined_data <- left_join(df, state_codes, by="state")
# Compute the electoral votes per 100K people in each state
joined_data <- joined_data %>% mutate(ratio = votes/population * 100000)
# Define server function
server <- function(input, output) {
# Render a plotly object that returns your map
ouput$map <- renderPlotly({
return(build_map(joined_data, input$mapvar))
})
}
|
# Race group differences in social dist variables in tempdiscsocialdist data set
# 7.14.20
# load required packages
library(here)
library(tidyverse)
library(rstatix)
# load source functions
# set hard-coded variables
# load data
if (sample == 1) {
dt <- read.csv(here::here("data", "tdsd_s1_data.csv"))
dd <- read.csv(here::here("data", 'tdsd_s1_data_dictionary.csv'), stringsAsFactors=FALSE)
filename <- 'r1.csv'
} else {
dt <- read.csv(here::here("data", "tdsd_s2_data.csv"))
dd <- read.csv(here::here("data", 'tdsd_s2_data_dictionary.csv'), stringsAsFactors=FALSE)
filename <- 'r2.csv'
}
# add social/health discounting difference score
dt$discountdiff <- dt$SC5 - dt$SC4
# add social/health valuedifference score
dt$valuediff <- dt$Q169_2 - dt$Q169_3
# group differences by race
dt$Race <- factor(dt$Q6)
levels(dt$Race)[levels(dt$Race) == 1] <- 'White/Caucasian'
levels(dt$Race)[levels(dt$Race) == 2] <- 'Black/African American'
levels(dt$Race)[levels(dt$Race) == 4] <- 'Hispanic/Latinx'
dt$Race <- factor(dt$Race, levels = c('White/Caucasian', 'Black/African American', 'Hispanic/Latinx'))
race_diff <- function(data, y) {
model <- anova_test(data, dv = y, between = Race)
return(model)
}
if (sample == 1){
d1 <- dt[c(11:15, 24, 39:41, 181:183, 186:191, 193:194)]
} else {
d1 <- dt[c(11:15, 24, 39:41, 181:183, 187:192, 194:195)]
}
race_sig <- matrix(nrow = ncol(d1), ncol = 3)
for (x in colnames(d1)) {
index <- grep(x, colnames(d1))
race_sig[index, 1] <- x
race_sig[index, 2] <- race_diff(dt, x)$p
race_sig[index, 3] <- race_diff(dt, x)$`p<.05`
}
colnames(race_sig) <- c("Variable", "pvalue", "significance")
write.csv(race_sig, here::here('output', filename))
# race_models <- vector(mode = 'list')
# for (x in colnames(d1)) {
# index <- grep(x, colnames(d1))
# race_models[[index]] <- race_diff(dt, x)
# }
|
/12_racial_differences.R
|
no_license
|
klsea/tempdiscsocialdist
|
R
| false | false | 1,864 |
r
|
# Race group differences in social dist variables in tempdiscsocialdist data set
# 7.14.20
# load required packages
library(here)
library(tidyverse)
library(rstatix)
# load source functions
# set hard-coded variables
# load data
if (sample == 1) {
dt <- read.csv(here::here("data", "tdsd_s1_data.csv"))
dd <- read.csv(here::here("data", 'tdsd_s1_data_dictionary.csv'), stringsAsFactors=FALSE)
filename <- 'r1.csv'
} else {
dt <- read.csv(here::here("data", "tdsd_s2_data.csv"))
dd <- read.csv(here::here("data", 'tdsd_s2_data_dictionary.csv'), stringsAsFactors=FALSE)
filename <- 'r2.csv'
}
# add social/health discounting difference score
dt$discountdiff <- dt$SC5 - dt$SC4
# add social/health valuedifference score
dt$valuediff <- dt$Q169_2 - dt$Q169_3
# group differences by race
dt$Race <- factor(dt$Q6)
levels(dt$Race)[levels(dt$Race) == 1] <- 'White/Caucasian'
levels(dt$Race)[levels(dt$Race) == 2] <- 'Black/African American'
levels(dt$Race)[levels(dt$Race) == 4] <- 'Hispanic/Latinx'
dt$Race <- factor(dt$Race, levels = c('White/Caucasian', 'Black/African American', 'Hispanic/Latinx'))
race_diff <- function(data, y) {
model <- anova_test(data, dv = y, between = Race)
return(model)
}
if (sample == 1){
d1 <- dt[c(11:15, 24, 39:41, 181:183, 186:191, 193:194)]
} else {
d1 <- dt[c(11:15, 24, 39:41, 181:183, 187:192, 194:195)]
}
race_sig <- matrix(nrow = ncol(d1), ncol = 3)
for (x in colnames(d1)) {
index <- grep(x, colnames(d1))
race_sig[index, 1] <- x
race_sig[index, 2] <- race_diff(dt, x)$p
race_sig[index, 3] <- race_diff(dt, x)$`p<.05`
}
colnames(race_sig) <- c("Variable", "pvalue", "significance")
write.csv(race_sig, here::here('output', filename))
# race_models <- vector(mode = 'list')
# for (x in colnames(d1)) {
# index <- grep(x, colnames(d1))
# race_models[[index]] <- race_diff(dt, x)
# }
|
ReadIntercatch <- function(file){
IC <- read.table(file ,sep=",", col.names=as.character(1:33), fill=T)
HI <- subset(IC,X1=='HI')[,1:12]
names(HI) <- c("RecordType", "Country", "Year", "SeasonType", "Season", "Fleet",
"AreaType", "FishingArea", "DepthRange", "UnitEffort", "Effort",
"AreaQualifier")
SI <- subset(IC,X1=='SI')[,1:24]
names(SI) <- c("RecordType", "Country", "Year", "SeasonType", "Season", "Fleet",
"AreaType", "FishingArea", "DepthRange", "Species", "Stock", "CatchCategory",
"ReportingCategory", "DataToFrom", "Usage", "SamplesOrigin", "Qualityflag",
"UnitCaton", "CATON", "OffLandings", "VarCaton", "InfoFleet",
"InfoStockCoordinator", "InfoGeneral")
if(sum(!SI$UnitCaton %in% c("t","kg"))>0)
stop("Invalid UnitCaton: only 't' or 'kg' allowed")
x <- ifelse(SI$UnitCaton == "kg", 0.001, 1)
SI$CATON <- SI$CATON * x
SI$UnitCaton <- "t"
SD <- subset(IC,X1=='SD')[,1:33]
names(SD) <- c("RecordType", "Country", "Year", "SeasonType", "Season", "Fleet",
"AreaType", "FishingArea", "DepthRange", "Species", "Stock", "CatchCategory",
"ReportingCategory", "Sex", "CANUMtype", "AgeLength", "PlusGroup",
"SampledCatch", "NumSamplesLngt", "NumLngtMeas", "NumSamplesAge", "NumAgeMeas",
"unitMeanWeight", "unitCANUM", "UnitAgeOrLength", "UnitMeanLength", "Maturity",
"NumberCaught", "MeanWeight", "MeanLength", "VarNumLanded", "VarWeightLanded",
"VarLngthLanded")
if(sum(!SD$unitMeanWeight %in% c("g","kg"))>0)
stop("Invalid unitMeanWeight: only 'g' or 'kg' allowed")
x <- ifelse(SD$unitMeanWeight == "g", 0.001, 1)
SD$MeanWeight <- SD$MeanWeight * x
SD$unitMeanWeight <- 'kg'
if(sum(!SD$unitCANUM %in% c("k","m","n"))>0)
stop("Invalid unitCANUM: only 'k', 'm' or 'n' allowed")
x <- ifelse(SD$unitCANUM == "m", 0.001, ifelse(SD$unitCANUM == "n", 1000, 1))
SD$NumberCaught <- SD$NumberCaught * x
SD$unitCANUM <- 'k'
# if(sum(!SD$UnitAgeOrLength %in% c("cm","mm"))>0)
# stop("Invalid UnitAgeOrLength: only 'cm' or 'mm' allowed for this datacall")
x <- ifelse(SD$UnitAgeOrLength == "mm", 0.1, 1)
SD$AgeLength <- as.numeric(as.character(SD$AgeLength)) * x
SD$unitMeanWeight <- 'cm'
return(list(HI=HI,SI=SI,SD=SD))
}
|
/WKRDB-EST/Personal_folders/Hans/ReadIntercatch.R
|
no_license
|
ices-eg/WK_RDBES
|
R
| false | false | 2,384 |
r
|
ReadIntercatch <- function(file){
IC <- read.table(file ,sep=",", col.names=as.character(1:33), fill=T)
HI <- subset(IC,X1=='HI')[,1:12]
names(HI) <- c("RecordType", "Country", "Year", "SeasonType", "Season", "Fleet",
"AreaType", "FishingArea", "DepthRange", "UnitEffort", "Effort",
"AreaQualifier")
SI <- subset(IC,X1=='SI')[,1:24]
names(SI) <- c("RecordType", "Country", "Year", "SeasonType", "Season", "Fleet",
"AreaType", "FishingArea", "DepthRange", "Species", "Stock", "CatchCategory",
"ReportingCategory", "DataToFrom", "Usage", "SamplesOrigin", "Qualityflag",
"UnitCaton", "CATON", "OffLandings", "VarCaton", "InfoFleet",
"InfoStockCoordinator", "InfoGeneral")
if(sum(!SI$UnitCaton %in% c("t","kg"))>0)
stop("Invalid UnitCaton: only 't' or 'kg' allowed")
x <- ifelse(SI$UnitCaton == "kg", 0.001, 1)
SI$CATON <- SI$CATON * x
SI$UnitCaton <- "t"
SD <- subset(IC,X1=='SD')[,1:33]
names(SD) <- c("RecordType", "Country", "Year", "SeasonType", "Season", "Fleet",
"AreaType", "FishingArea", "DepthRange", "Species", "Stock", "CatchCategory",
"ReportingCategory", "Sex", "CANUMtype", "AgeLength", "PlusGroup",
"SampledCatch", "NumSamplesLngt", "NumLngtMeas", "NumSamplesAge", "NumAgeMeas",
"unitMeanWeight", "unitCANUM", "UnitAgeOrLength", "UnitMeanLength", "Maturity",
"NumberCaught", "MeanWeight", "MeanLength", "VarNumLanded", "VarWeightLanded",
"VarLngthLanded")
if(sum(!SD$unitMeanWeight %in% c("g","kg"))>0)
stop("Invalid unitMeanWeight: only 'g' or 'kg' allowed")
x <- ifelse(SD$unitMeanWeight == "g", 0.001, 1)
SD$MeanWeight <- SD$MeanWeight * x
SD$unitMeanWeight <- 'kg'
if(sum(!SD$unitCANUM %in% c("k","m","n"))>0)
stop("Invalid unitCANUM: only 'k', 'm' or 'n' allowed")
x <- ifelse(SD$unitCANUM == "m", 0.001, ifelse(SD$unitCANUM == "n", 1000, 1))
SD$NumberCaught <- SD$NumberCaught * x
SD$unitCANUM <- 'k'
# if(sum(!SD$UnitAgeOrLength %in% c("cm","mm"))>0)
# stop("Invalid UnitAgeOrLength: only 'cm' or 'mm' allowed for this datacall")
x <- ifelse(SD$UnitAgeOrLength == "mm", 0.1, 1)
SD$AgeLength <- as.numeric(as.character(SD$AgeLength)) * x
SD$unitMeanWeight <- 'cm'
return(list(HI=HI,SI=SI,SD=SD))
}
|
### make plot for eaf reference ###
# load data
library(data.table)
setwd("/home/common/projects/ovine_selection/ovines_gwas_map/sheep_reference")
reference <- fread("sheep_reference.txt", head=T, stringsAsFactors=F, data.table=F)
# make table for plot
for_plot <- matrix(ncol=4, nrow=6)
for_plot[1,1] <- 0
for_plot[2,1] <- 0.01
for_plot[3,1] <- 0.05
for_plot[4,1] <- 0.1
for_plot[5,1] <- 0.2
for_plot[6,1] <- 0.25
for_plot[1,2] <- 0.01
for_plot[2,2] <- 0.05
for_plot[3,2] <- 0.1
for_plot[4,2] <- 0.2
for_plot[5,2] <- 0.25
for_plot[6,2] <- 0.5
maf <- pmin(1-reference$eaf,reference$eaf)
for (n in (1:nrow(for_plot))) {
for_plot[n,3] <- length(maf[maf > for_plot[n,1] & maf <= for_plot[n,2]])
}
for_plot[,4] <- paste(for_plot[,1], for_plot[,2], sep="-")
colnames(for_plot) <- c("range1", "range2", "count", "range")
# make plot
library(ggplot2)
library(scales)
tiff("/home/common/projects/ovine_selection/ovines_gwas_map/results/for_reports/maf_distribution.tiff")
ggplot(as.data.frame(for_plot[,(3:4)]), aes(x=factor(range), y=as.numeric(as.matrix(count)))) +
geom_bar(stat = "identity", fill="steelblue") +
xlab("Minor allele frequency") +
ylab("Number of SNPs") +
theme_classic() +
scale_y_continuous(label = comma) +
geom_text(aes(label = count),
vjust = -0.25,
color = "black",
position=position_dodge(width=1)
) +
theme_classic()
dev.off()
|
/04_do_plots_and_tables_for_reports/04b_make_plot_for_eaf_reference.R
|
no_license
|
Defrag1236/ovines_gwas_map
|
R
| false | false | 1,485 |
r
|
### make plot for eaf reference ###
# load data
library(data.table)
setwd("/home/common/projects/ovine_selection/ovines_gwas_map/sheep_reference")
reference <- fread("sheep_reference.txt", head=T, stringsAsFactors=F, data.table=F)
# make table for plot
for_plot <- matrix(ncol=4, nrow=6)
for_plot[1,1] <- 0
for_plot[2,1] <- 0.01
for_plot[3,1] <- 0.05
for_plot[4,1] <- 0.1
for_plot[5,1] <- 0.2
for_plot[6,1] <- 0.25
for_plot[1,2] <- 0.01
for_plot[2,2] <- 0.05
for_plot[3,2] <- 0.1
for_plot[4,2] <- 0.2
for_plot[5,2] <- 0.25
for_plot[6,2] <- 0.5
maf <- pmin(1-reference$eaf,reference$eaf)
for (n in (1:nrow(for_plot))) {
for_plot[n,3] <- length(maf[maf > for_plot[n,1] & maf <= for_plot[n,2]])
}
for_plot[,4] <- paste(for_plot[,1], for_plot[,2], sep="-")
colnames(for_plot) <- c("range1", "range2", "count", "range")
# make plot
library(ggplot2)
library(scales)
tiff("/home/common/projects/ovine_selection/ovines_gwas_map/results/for_reports/maf_distribution.tiff")
ggplot(as.data.frame(for_plot[,(3:4)]), aes(x=factor(range), y=as.numeric(as.matrix(count)))) +
geom_bar(stat = "identity", fill="steelblue") +
xlab("Minor allele frequency") +
ylab("Number of SNPs") +
theme_classic() +
scale_y_continuous(label = comma) +
geom_text(aes(label = count),
vjust = -0.25,
color = "black",
position=position_dodge(width=1)
) +
theme_classic()
dev.off()
|
\name{difshannonbio}
\alias{difshannonbio}
\title{ Empirical confidence interval of the bootstrap of the difference between two Shannon indices }
\description{
Computes the empirical confidence interval of the bootstrap of the difference between two Shannon indices
}
\usage{
difshannonbio(dat1, dat2, R = 1000, probs = c(0.025, 0.975))
}
%- maybe also 'usage' for other objects documented here.
\arguments{
\item{dat1}{ a data.frame of two columns; column = category, column 2 = biomass }
\item{dat2}{ a data.frame of two columns; column = category, column 2 = biomass }
\item{R}{ number of permutations }
\item{probs}{ the limits of the confidence interval }
}
\details{
Designated to compare the difference between two Shannon's indices computed from two data frames. In each data frame, the first column is the category of prey item, and the second column the estimated biomass.
}
\value{
A list with the confidence interval of H' and J'
}
\seealso{ \code{\link{shannonbio}}}
\examples{
data(preybiom)
attach(preybiom)
jackal<-preybiom[site=="Y" & sp=="C",5:6]
genet<-preybiom[site=="Y" & sp=="G",5:6]
difshannonbio(jackal,genet,R=150)
}
\keyword{ misc }% at least one, from doc/KEYWORDS
|
/pgirmess/man/difshannonbio.rd
|
no_license
|
pgiraudoux/pgirmess
|
R
| false | false | 1,214 |
rd
|
\name{difshannonbio}
\alias{difshannonbio}
\title{ Empirical confidence interval of the bootstrap of the difference between two Shannon indices }
\description{
Computes the empirical confidence interval of the bootstrap of the difference between two Shannon indices
}
\usage{
difshannonbio(dat1, dat2, R = 1000, probs = c(0.025, 0.975))
}
%- maybe also 'usage' for other objects documented here.
\arguments{
\item{dat1}{ a data.frame of two columns; column = category, column 2 = biomass }
\item{dat2}{ a data.frame of two columns; column = category, column 2 = biomass }
\item{R}{ number of permutations }
\item{probs}{ the limits of the confidence interval }
}
\details{
Designated to compare the difference between two Shannon's indices computed from two data frames. In each data frame, the first column is the category of prey item, and the second column the estimated biomass.
}
\value{
A list with the confidence interval of H' and J'
}
\seealso{ \code{\link{shannonbio}}}
\examples{
data(preybiom)
attach(preybiom)
jackal<-preybiom[site=="Y" & sp=="C",5:6]
genet<-preybiom[site=="Y" & sp=="G",5:6]
difshannonbio(jackal,genet,R=150)
}
\keyword{ misc }% at least one, from doc/KEYWORDS
|
### R code from vignette source 'intro.Rnw'
### Encoding: UTF-8
###################################################
### code chunk number 1: intro.Rnw:26-27
###################################################
options(keep.source=TRUE)
###################################################
### code chunk number 2: intro.Rnw:111-115
###################################################
print("Hello world.")
4+5
4^5
8*(7+3)
###################################################
### code chunk number 3: intro.Rnw:126-130
###################################################
# R will completely ignore this line of text
3+4 #R will execute the first part of this line and ignore the rest
# if you need to include a long note with several lines of text,
# be certain that each line is preceded by a #
###################################################
### code chunk number 4: intro.Rnw:138-139
###################################################
3*4 # This is a comment
###################################################
### code chunk number 5: intro.Rnw:164-165
###################################################
?cor.test # this will open up the help file for the "cor.test" function
###################################################
### code chunk number 6: intro.Rnw:184-185
###################################################
library(deSolve) # this will load the deSolve package
###################################################
### code chunk number 7: intro.Rnw:190-191
###################################################
?deSolve # this accesses the main page of the deSolve help files if deSolve is loaded.
###################################################
### code chunk number 8: intro.Rnw:209-214
###################################################
4 * 6
5 ^ 4
119 / 10
119 %/% 10
119 %% 10
###################################################
### code chunk number 9: intro.Rnw:241-243
###################################################
4 + 2 * 3 + 4
(4 + 2) * (3 + 4)
###################################################
### code chunk number 10: intro.Rnw:248-249
###################################################
119/10; 119 %/% 10; 119 %% 10
###################################################
### code chunk number 11: intro.Rnw:270-274
###################################################
4 == 6
6 == 6
4 != 6
4 > 6
###################################################
### code chunk number 12: intro.Rnw:314-319
###################################################
floor(3.4)
ceiling(3.4)
log(304)
log10(304)
abs(44)
###################################################
### code chunk number 13: intro.Rnw:362-364
###################################################
bob <- 20
bob
###################################################
### code chunk number 14: intro.Rnw:388-390
###################################################
infectious.period <- 20 # infectious period in units of days
infectious.period
###################################################
### code chunk number 15: intro.Rnw:395-397
###################################################
log10(bob)
bob*2
###################################################
### code chunk number 16: intro.Rnw:402-404
###################################################
bob <- 40
bob
###################################################
### code chunk number 17: intro.Rnw:409-411
###################################################
bob <- bob+2
bob
###################################################
### code chunk number 18: intro.Rnw:416-417
###################################################
str(bob)
###################################################
### code chunk number 19: intro.Rnw:432-434
###################################################
x <- c(1,3,5,7,2,8,4,4,10)
x
###################################################
### code chunk number 20: intro.Rnw:439-442
###################################################
1:10
x <- c(1:10)
x
###################################################
### code chunk number 21: intro.Rnw:447-450
###################################################
rep(2, 5)
x <- rep(2,10)
x
###################################################
### code chunk number 22: intro.Rnw:455-459
###################################################
x <- rnorm(10)
x
x <- rnorm(10, mean = 5)
x
###################################################
### code chunk number 23: intro.Rnw:464-468
###################################################
x <- rbinom(10, 1, 0.5)
x
x <- rbinom(10, 4, 0.5)
x
###################################################
### code chunk number 24: intro.Rnw:473-475
###################################################
x <- c(1,3,5,7, 1:8, rep(2,3))
x
###################################################
### code chunk number 25: intro.Rnw:480-486
###################################################
x <- c(1:10)
x
x <- append(x, 11)
x
x <- append(x, x)
x
###################################################
### code chunk number 26: intro.Rnw:500-503
###################################################
x <- c(1:20)
x[4]
x[4:15]
###################################################
### code chunk number 27: intro.Rnw:508-511
###################################################
x[-4:-10]
x <- x[-4]
x
###################################################
### code chunk number 28: intro.Rnw:516-520
###################################################
x <- c(1:20)
y <- c(3, 5, 12)
x[y]
x[-y]
###################################################
### code chunk number 29: intro.Rnw:525-530
###################################################
x <- c(1:5,2,2,2,2,2)
x[x > 4]
x[x < 4]
which(x < 4)
which(x == 2)
###################################################
### code chunk number 30: intro.Rnw:545-553
###################################################
x <- c(1:10)
x/2
x-2
log10(x)
###################################################
### code chunk number 31: intro.Rnw:559-566
###################################################
x <- c(1:10)
y <- c(1:5,2,2,2,2,2)
y <- x+y
x/y
###################################################
### code chunk number 32: intro.Rnw:582-593
###################################################
x <- c(1,3,5,7,20,2,8,4,4,10,2,2,1,1,15,3)
head(x)
max(x)
unique(x)
sort(x)
mean(x)
###################################################
### code chunk number 33: intro.Rnw:623-624
###################################################
length(unique(x))
###################################################
### code chunk number 34: intro.Rnw:629-634
###################################################
x <- c(1:20)
sample(x)
sample(x, replace = T)
###################################################
### code chunk number 35: intro.Rnw:652-654
###################################################
y <- c("Escherichia","Chlamydia","Bacillus","Brachyspira","Leptonema")
y
###################################################
### code chunk number 36: intro.Rnw:659-663
###################################################
x <- c(1:5)
names(x) <- y
x
###################################################
### code chunk number 37: intro.Rnw:668-671
###################################################
names(x) <- c("Escherichia","Chlamydia","Bacillus","Brachyspira","Leptonema")
x
###################################################
### code chunk number 38: intro.Rnw:687-690
###################################################
x <- c(1:25)
y <- matrix(x, nrow=5)
y
###################################################
### code chunk number 39: intro.Rnw:695-697
###################################################
z <- matrix(x, byrow=T, nrow=5)
z
###################################################
### code chunk number 40: intro.Rnw:708-709
###################################################
z[2,5]
###################################################
### code chunk number 41: intro.Rnw:714-716
###################################################
z[2,]
z[,5]
###################################################
### code chunk number 42: intro.Rnw:733-737
###################################################
z
z*2
z+2
z*z
###################################################
### code chunk number 43: intro.Rnw:742-744
###################################################
z%*%z
z%/%y
###################################################
### code chunk number 44: intro.Rnw:749-753
###################################################
max(z)
mean(z)
mean(z[2,])
sample(z[2,], replace=T)
###################################################
### code chunk number 45: intro.Rnw:758-761
###################################################
dim(z)
t(z) #transpose
colMeans(z)
###################################################
### code chunk number 46: intro.Rnw:802-807
###################################################
sums <- rowSums(z)
z2 <- rbind(z, sums)
z2
z2 <- cbind(z, sums)
z2
###################################################
### code chunk number 47: intro.Rnw:812-818
###################################################
data <- matrix(c(0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1), nrow=5)
cols <- c("Escherichia","Chlamydia","Bacillus","Brachyspira","Leptonema")
rows <-c("Ovis", "Canis", "Felis", "Capra", "Sus")
colnames(data) <- cols
rownames(data) <- rows
data
###################################################
### code chunk number 48: intro.Rnw:829-839
###################################################
#first create some data vectors
disease <- c("Cpox","ADisentary","Malaria","Flu","Plague")
agent <- c("Viral","Protozoan","Protozoan","Viral","Bacterial")
trans <- c(1,0,0,1,0)
vector <- c(0,0,1,0,1)
vir <- c(4,4,3,2,5)
#now combine them into a data frame
diseases <- data.frame(disease,agent,trans,vector,vir)
diseases
#now combine them into a data frame, this time assigning names
diseases <- data.frame(name=disease,type=agent,tmode=trans,vecborne=vector,virulence=vir)
diseases
###################################################
### code chunk number 49: intro.Rnw:844-845
###################################################
str(diseases)
###################################################
### code chunk number 50: intro.Rnw:850-853
###################################################
diseases[,2]
diseases$type
###################################################
### code chunk number 51: intro.Rnw:863-865
###################################################
stuff <- list(1:10, z2, diseases)
str(stuff)
###################################################
### code chunk number 52: intro.Rnw:870-872
###################################################
x <- stuff[[1]]
x
###################################################
### code chunk number 53: intro.Rnw:877-880
###################################################
stuff <- list(numbers=1:10, matrix=z2, dis=diseases)
stuff[[3]]
stuff$dis
###################################################
### code chunk number 54: intro.Rnw:898-906
###################################################
Rounder <- function(x){
#this function uses the floor function to
#do what the round function does
x <- x+0.5
floor(x)
}
ls()
###################################################
### code chunk number 55: intro.Rnw:912-915
###################################################
Rounder(3.1)
Rounder(3.7)
Rounder(z2*3.8)
###################################################
### code chunk number 56: intro.Rnw:926-946
###################################################
#The same function as above written following Google style guidelines:
Rounder2 <- function(x){
#this function uses the floor function to
#do what the round function does
#
#Args:
# x: x must be of type numeric
#
#Returns:
# x or all elements of x rounded to the nearest integer
#
#Error handling
if (is.numeric(x)==FALSE){
stop("x is not of type numeric")
}
x <- x+0.5
y <- floor(x)
return(y)
}
###################################################
### code chunk number 57: intro.Rnw:962-973
###################################################
# A simple function that needs functions from the ape library to run
# ape is a library of functions for analysis of evolutionary relationships:
RandTreePlotter <- function(x){
#this function creates a plot of a random evolutionary tree
#of size x
require(ape)
tree <- rcoal(x)
plot(tree)
}
RandTreePlotter(20)
###################################################
### code chunk number 58: intro.Rnw:992-999
###################################################
x <- 8
if (x < 9) print("x is less than nine")
x <- 10
if (x < 9) print("x is less than nine")
###################################################
### code chunk number 59: intro.Rnw:1009-1019
###################################################
Isitaten <- function(x){
if (x == 10)
print("It's a ten!")
else print("Not a ten")
}
Isitaten(11)
Isitaten(10)
###################################################
### code chunk number 60: intro.Rnw:1030-1033
###################################################
for (i in 10:20) print(2*i)
y <- c(2.3, 4.4, 3.7, 1.2)
for (i in y) print(2*i)
###################################################
### code chunk number 61: intro.Rnw:1045-1052
###################################################
y <- 1
while(y < 10){
print(y)
y <- y+1
}
print("Thank goodness that's done")
|
/REU R Workshop/REU R Workshop/W1_Intro/intro_v2.R
|
no_license
|
jwaring8/REU
|
R
| false | false | 14,053 |
r
|
### R code from vignette source 'intro.Rnw'
### Encoding: UTF-8
###################################################
### code chunk number 1: intro.Rnw:26-27
###################################################
options(keep.source=TRUE)
###################################################
### code chunk number 2: intro.Rnw:111-115
###################################################
print("Hello world.")
4+5
4^5
8*(7+3)
###################################################
### code chunk number 3: intro.Rnw:126-130
###################################################
# R will completely ignore this line of text
3+4 #R will execute the first part of this line and ignore the rest
# if you need to include a long note with several lines of text,
# be certain that each line is preceded by a #
###################################################
### code chunk number 4: intro.Rnw:138-139
###################################################
3*4 # This is a comment
###################################################
### code chunk number 5: intro.Rnw:164-165
###################################################
?cor.test # this will open up the help file for the "cor.test" function
###################################################
### code chunk number 6: intro.Rnw:184-185
###################################################
library(deSolve) # this will load the deSolve package
###################################################
### code chunk number 7: intro.Rnw:190-191
###################################################
?deSolve # this accesses the main page of the deSolve help files if deSolve is loaded.
###################################################
### code chunk number 8: intro.Rnw:209-214
###################################################
4 * 6
5 ^ 4
119 / 10
119 %/% 10
119 %% 10
###################################################
### code chunk number 9: intro.Rnw:241-243
###################################################
4 + 2 * 3 + 4
(4 + 2) * (3 + 4)
###################################################
### code chunk number 10: intro.Rnw:248-249
###################################################
119/10; 119 %/% 10; 119 %% 10
###################################################
### code chunk number 11: intro.Rnw:270-274
###################################################
4 == 6
6 == 6
4 != 6
4 > 6
###################################################
### code chunk number 12: intro.Rnw:314-319
###################################################
floor(3.4)
ceiling(3.4)
log(304)
log10(304)
abs(44)
###################################################
### code chunk number 13: intro.Rnw:362-364
###################################################
bob <- 20
bob
###################################################
### code chunk number 14: intro.Rnw:388-390
###################################################
infectious.period <- 20 # infectious period in units of days
infectious.period
###################################################
### code chunk number 15: intro.Rnw:395-397
###################################################
log10(bob)
bob*2
###################################################
### code chunk number 16: intro.Rnw:402-404
###################################################
bob <- 40
bob
###################################################
### code chunk number 17: intro.Rnw:409-411
###################################################
bob <- bob+2
bob
###################################################
### code chunk number 18: intro.Rnw:416-417
###################################################
str(bob)
###################################################
### code chunk number 19: intro.Rnw:432-434
###################################################
x <- c(1,3,5,7,2,8,4,4,10)
x
###################################################
### code chunk number 20: intro.Rnw:439-442
###################################################
1:10
x <- c(1:10)
x
###################################################
### code chunk number 21: intro.Rnw:447-450
###################################################
rep(2, 5)
x <- rep(2,10)
x
###################################################
### code chunk number 22: intro.Rnw:455-459
###################################################
x <- rnorm(10)
x
x <- rnorm(10, mean = 5)
x
###################################################
### code chunk number 23: intro.Rnw:464-468
###################################################
x <- rbinom(10, 1, 0.5)
x
x <- rbinom(10, 4, 0.5)
x
###################################################
### code chunk number 24: intro.Rnw:473-475
###################################################
x <- c(1,3,5,7, 1:8, rep(2,3))
x
###################################################
### code chunk number 25: intro.Rnw:480-486
###################################################
x <- c(1:10)
x
x <- append(x, 11)
x
x <- append(x, x)
x
###################################################
### code chunk number 26: intro.Rnw:500-503
###################################################
x <- c(1:20)
x[4]
x[4:15]
###################################################
### code chunk number 27: intro.Rnw:508-511
###################################################
x[-4:-10]
x <- x[-4]
x
###################################################
### code chunk number 28: intro.Rnw:516-520
###################################################
x <- c(1:20)
y <- c(3, 5, 12)
x[y]
x[-y]
###################################################
### code chunk number 29: intro.Rnw:525-530
###################################################
x <- c(1:5,2,2,2,2,2)
x[x > 4]
x[x < 4]
which(x < 4)
which(x == 2)
###################################################
### code chunk number 30: intro.Rnw:545-553
###################################################
x <- c(1:10)
x/2
x-2
log10(x)
###################################################
### code chunk number 31: intro.Rnw:559-566
###################################################
x <- c(1:10)
y <- c(1:5,2,2,2,2,2)
y <- x+y
x/y
###################################################
### code chunk number 32: intro.Rnw:582-593
###################################################
x <- c(1,3,5,7,20,2,8,4,4,10,2,2,1,1,15,3)
head(x)
max(x)
unique(x)
sort(x)
mean(x)
###################################################
### code chunk number 33: intro.Rnw:623-624
###################################################
length(unique(x))
###################################################
### code chunk number 34: intro.Rnw:629-634
###################################################
x <- c(1:20)
sample(x)
sample(x, replace = T)
###################################################
### code chunk number 35: intro.Rnw:652-654
###################################################
y <- c("Escherichia","Chlamydia","Bacillus","Brachyspira","Leptonema")
y
###################################################
### code chunk number 36: intro.Rnw:659-663
###################################################
x <- c(1:5)
names(x) <- y
x
###################################################
### code chunk number 37: intro.Rnw:668-671
###################################################
names(x) <- c("Escherichia","Chlamydia","Bacillus","Brachyspira","Leptonema")
x
###################################################
### code chunk number 38: intro.Rnw:687-690
###################################################
x <- c(1:25)
y <- matrix(x, nrow=5)
y
###################################################
### code chunk number 39: intro.Rnw:695-697
###################################################
z <- matrix(x, byrow=T, nrow=5)
z
###################################################
### code chunk number 40: intro.Rnw:708-709
###################################################
z[2,5]
###################################################
### code chunk number 41: intro.Rnw:714-716
###################################################
z[2,]
z[,5]
###################################################
### code chunk number 42: intro.Rnw:733-737
###################################################
z
z*2
z+2
z*z
###################################################
### code chunk number 43: intro.Rnw:742-744
###################################################
z%*%z
z%/%y
###################################################
### code chunk number 44: intro.Rnw:749-753
###################################################
max(z)
mean(z)
mean(z[2,])
sample(z[2,], replace=T)
###################################################
### code chunk number 45: intro.Rnw:758-761
###################################################
dim(z)
t(z) #transpose
colMeans(z)
###################################################
### code chunk number 46: intro.Rnw:802-807
###################################################
sums <- rowSums(z)
z2 <- rbind(z, sums)
z2
z2 <- cbind(z, sums)
z2
###################################################
### code chunk number 47: intro.Rnw:812-818
###################################################
data <- matrix(c(0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1), nrow=5)
cols <- c("Escherichia","Chlamydia","Bacillus","Brachyspira","Leptonema")
rows <-c("Ovis", "Canis", "Felis", "Capra", "Sus")
colnames(data) <- cols
rownames(data) <- rows
data
###################################################
### code chunk number 48: intro.Rnw:829-839
###################################################
#first create some data vectors
disease <- c("Cpox","ADisentary","Malaria","Flu","Plague")
agent <- c("Viral","Protozoan","Protozoan","Viral","Bacterial")
trans <- c(1,0,0,1,0)
vector <- c(0,0,1,0,1)
vir <- c(4,4,3,2,5)
#now combine them into a data frame
diseases <- data.frame(disease,agent,trans,vector,vir)
diseases
#now combine them into a data frame, this time assigning names
diseases <- data.frame(name=disease,type=agent,tmode=trans,vecborne=vector,virulence=vir)
diseases
###################################################
### code chunk number 49: intro.Rnw:844-845
###################################################
str(diseases)
###################################################
### code chunk number 50: intro.Rnw:850-853
###################################################
diseases[,2]
diseases$type
###################################################
### code chunk number 51: intro.Rnw:863-865
###################################################
stuff <- list(1:10, z2, diseases)
str(stuff)
###################################################
### code chunk number 52: intro.Rnw:870-872
###################################################
x <- stuff[[1]]
x
###################################################
### code chunk number 53: intro.Rnw:877-880
###################################################
stuff <- list(numbers=1:10, matrix=z2, dis=diseases)
stuff[[3]]
stuff$dis
###################################################
### code chunk number 54: intro.Rnw:898-906
###################################################
Rounder <- function(x){
#this function uses the floor function to
#do what the round function does
x <- x+0.5
floor(x)
}
ls()
###################################################
### code chunk number 55: intro.Rnw:912-915
###################################################
Rounder(3.1)
Rounder(3.7)
Rounder(z2*3.8)
###################################################
### code chunk number 56: intro.Rnw:926-946
###################################################
#The same function as above written following Google style guidelines:
Rounder2 <- function(x){
#this function uses the floor function to
#do what the round function does
#
#Args:
# x: x must be of type numeric
#
#Returns:
# x or all elements of x rounded to the nearest integer
#
#Error handling
if (is.numeric(x)==FALSE){
stop("x is not of type numeric")
}
x <- x+0.5
y <- floor(x)
return(y)
}
###################################################
### code chunk number 57: intro.Rnw:962-973
###################################################
# A simple function that needs functions from the ape library to run
# ape is a library of functions for analysis of evolutionary relationships:
RandTreePlotter <- function(x){
#this function creates a plot of a random evolutionary tree
#of size x
require(ape)
tree <- rcoal(x)
plot(tree)
}
RandTreePlotter(20)
###################################################
### code chunk number 58: intro.Rnw:992-999
###################################################
x <- 8
if (x < 9) print("x is less than nine")
x <- 10
if (x < 9) print("x is less than nine")
###################################################
### code chunk number 59: intro.Rnw:1009-1019
###################################################
Isitaten <- function(x){
if (x == 10)
print("It's a ten!")
else print("Not a ten")
}
Isitaten(11)
Isitaten(10)
###################################################
### code chunk number 60: intro.Rnw:1030-1033
###################################################
for (i in 10:20) print(2*i)
y <- c(2.3, 4.4, 3.7, 1.2)
for (i in y) print(2*i)
###################################################
### code chunk number 61: intro.Rnw:1045-1052
###################################################
y <- 1
while(y < 10){
print(y)
y <- y+1
}
print("Thank goodness that's done")
|
sum_i <- function(v, i) {
if (i < 1) {
return(0)
}
j <- i
if (j > length(v)) {
j <- length(v)
}
sum(v[1]:v[j])
}
|
/src/week_2/prob-1.R
|
permissive
|
haunt98/R-learn
|
R
| false | false | 153 |
r
|
sum_i <- function(v, i) {
if (i < 1) {
return(0)
}
j <- i
if (j > length(v)) {
j <- length(v)
}
sum(v[1]:v[j])
}
|
# R commands for working with Mr. Doyle's data
library(lubridate)
library(tidyverse)
x <- read_csv("spreadspoke_scores.csv", guess_max = 10000) %>%
mutate(schedule_week = recode(schedule_week,
"SuperBowl" = "Superbowl",
"WildCard" = "Wildcard")) %>%
mutate(schedule_date = mdy(schedule_date)) %>%
mutate(schedule_week = fct_relevel(schedule_week,
c(as.character(1:18),
"Wildcard", "Division", "Conference", "Superbowl"))) %>%
mutate(weather_humidity = parse_number(weather_humidity))
write_rds(x, "spreads.rds")
|
/kane.R
|
no_license
|
tianan2/Final-Project
|
R
| false | false | 671 |
r
|
# R commands for working with Mr. Doyle's data
library(lubridate)
library(tidyverse)
x <- read_csv("spreadspoke_scores.csv", guess_max = 10000) %>%
mutate(schedule_week = recode(schedule_week,
"SuperBowl" = "Superbowl",
"WildCard" = "Wildcard")) %>%
mutate(schedule_date = mdy(schedule_date)) %>%
mutate(schedule_week = fct_relevel(schedule_week,
c(as.character(1:18),
"Wildcard", "Division", "Conference", "Superbowl"))) %>%
mutate(weather_humidity = parse_number(weather_humidity))
write_rds(x, "spreads.rds")
|
library(tidyverse)
range01 <- function(x){(x-min(x))/(max(x)-min(x))}
# alumnos -----------------------------------------------------------------
set.seed(1)
N <- 3000
x <- rnorm(N)
m <- -0.5555556
b <- 8.3333333
y <- m * x + b + rnorm(length(x))
plot(x, y, col="gray", pch=20, asp=1)
fit <- lm(y ~ x)
abline(fit, lty=2, lwd=2)
confounded_data_frame <- function(x, y, m, num_grp){
b <- 0 # intercept doesn't matter
d <- point_line_distance(b, m, x, y)
d_scaled <- 0.0005 + 0.999 * (d - min(d))/(max(d) - min(d)) # avoid 0 and 1
data.frame(x=x, y=y,
group=as.factor(sprintf("grp%02d", ceiling(num_grp*(d_scaled)))))
}
find_group_coefficients <- function(data){
coef <- t(sapply(levels(data$group),
function(grp) coefficients(lm(y ~ x, data=data[data$group==grp,]))))
coef[!is.na(coef[,1]) & ! is.na(coef[,2]),]
}
striped_scatterplot <- function(formula, grouped_data){
# blue on top and red on bottom, to match the Wikipedia figure
colors <- rev(rainbow(length(levels(grouped_data$group)), end=2/3))
plot(formula, grouped_data, bg=colors[grouped_data$group], pch=21, asp=1)
grp_coef <- find_group_coefficients(grouped_data)
# if some coefficents get dropped, colors won't match exactly
for (r in 1:nrow(grp_coef))
abline(grp_coef[r,1], grp_coef[r,2], col=colors[r], lwd=2)
}
point_line_distance <- function(b, m, x, y)
(y - (m*x + b))/sqrt(m^2 + 1)
m_new <- 1 # the new coefficient we want x to have
cdf <- confounded_data_frame(x, y, m_new, num_grp=5) # see function below
striped_scatterplot(y ~ x, cdf) # also see below
graphics.off()
data <- cdf %>%
tbl_df() %>%
mutate(
x = round(range01(x) * 100, 2),
y = round(range01(y) * 50 + 30, 2)
) %>%
rename(dificultad = x, satisfaccion = y, grupo = group)
ggplot(data) +
geom_point(aes(dificultad, satisfaccion), alpha = 0.5)
writexl::write_xlsx(data, "data/alumnos.xlsx")
alumnos <- read_csv("https://goo.gl/Wy3GsU")
# temperatura -------------------------------------------------------------
temp <- read_csv("https://raw.githubusercontent.com/hrbrmstr/hadcrut/master/data/temps.csv")
write_csv(temp, "data/temperatura.csv")
temperatura <- read_csv("https://docs.google.com/spreadsheets/u/0/d/1dFEFGKBIBBNjoejtFhthn_k9UTiGYhkDiy383fcdRvU/export?format=csv&id=1dFEFGKBIBBNjoejtFhthn_k9UTiGYhkDiy383fcdRvU&gid=0")
temperatura <- read_csv("https://goo.gl/3JUCma")
temperatura
|
/R/99-data.R
|
no_license
|
jbkunst/puc-introduccion-a-R
|
R
| false | false | 2,424 |
r
|
library(tidyverse)
range01 <- function(x){(x-min(x))/(max(x)-min(x))}
# alumnos -----------------------------------------------------------------
set.seed(1)
N <- 3000
x <- rnorm(N)
m <- -0.5555556
b <- 8.3333333
y <- m * x + b + rnorm(length(x))
plot(x, y, col="gray", pch=20, asp=1)
fit <- lm(y ~ x)
abline(fit, lty=2, lwd=2)
confounded_data_frame <- function(x, y, m, num_grp){
b <- 0 # intercept doesn't matter
d <- point_line_distance(b, m, x, y)
d_scaled <- 0.0005 + 0.999 * (d - min(d))/(max(d) - min(d)) # avoid 0 and 1
data.frame(x=x, y=y,
group=as.factor(sprintf("grp%02d", ceiling(num_grp*(d_scaled)))))
}
find_group_coefficients <- function(data){
coef <- t(sapply(levels(data$group),
function(grp) coefficients(lm(y ~ x, data=data[data$group==grp,]))))
coef[!is.na(coef[,1]) & ! is.na(coef[,2]),]
}
striped_scatterplot <- function(formula, grouped_data){
# blue on top and red on bottom, to match the Wikipedia figure
colors <- rev(rainbow(length(levels(grouped_data$group)), end=2/3))
plot(formula, grouped_data, bg=colors[grouped_data$group], pch=21, asp=1)
grp_coef <- find_group_coefficients(grouped_data)
# if some coefficents get dropped, colors won't match exactly
for (r in 1:nrow(grp_coef))
abline(grp_coef[r,1], grp_coef[r,2], col=colors[r], lwd=2)
}
point_line_distance <- function(b, m, x, y)
(y - (m*x + b))/sqrt(m^2 + 1)
m_new <- 1 # the new coefficient we want x to have
cdf <- confounded_data_frame(x, y, m_new, num_grp=5) # see function below
striped_scatterplot(y ~ x, cdf) # also see below
graphics.off()
data <- cdf %>%
tbl_df() %>%
mutate(
x = round(range01(x) * 100, 2),
y = round(range01(y) * 50 + 30, 2)
) %>%
rename(dificultad = x, satisfaccion = y, grupo = group)
ggplot(data) +
geom_point(aes(dificultad, satisfaccion), alpha = 0.5)
writexl::write_xlsx(data, "data/alumnos.xlsx")
alumnos <- read_csv("https://goo.gl/Wy3GsU")
# temperatura -------------------------------------------------------------
temp <- read_csv("https://raw.githubusercontent.com/hrbrmstr/hadcrut/master/data/temps.csv")
write_csv(temp, "data/temperatura.csv")
temperatura <- read_csv("https://docs.google.com/spreadsheets/u/0/d/1dFEFGKBIBBNjoejtFhthn_k9UTiGYhkDiy383fcdRvU/export?format=csv&id=1dFEFGKBIBBNjoejtFhthn_k9UTiGYhkDiy383fcdRvU&gid=0")
temperatura <- read_csv("https://goo.gl/3JUCma")
temperatura
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/binCounts.R
\name{binCounts}
\alias{binCounts}
\title{Fast element counting in non-overlapping bins}
\usage{
binCounts(x, idxs = NULL, bx, right = FALSE, ...)
}
\arguments{
\item{x}{A \code{\link[base]{numeric}} \code{\link[base]{vector}} of K
positions for to be binned and counted.}
\item{idxs}{A \code{\link[base]{vector}} indicating subset of elements to
operate over. If \code{\link[base]{NULL}}, no subsetting is done.}
\item{bx}{A \code{\link[base]{numeric}} \code{\link[base]{vector}} of B + 1
ordered positions specifying the B > 0 bins \code{[bx[1], bx[2])},
\code{[bx[2], bx[3])}, ..., \code{[bx[B], bx[B + 1])}.}
\item{right}{If \code{\link[base:logical]{TRUE}}, the bins are right-closed
(left open), otherwise left-closed (right open).}
\item{...}{Not used.}
}
\value{
Returns an \code{\link[base]{integer}} \code{\link[base]{vector}} of
length B with non-negative integers.
}
\description{
Counts the number of elements in non-overlapping bins
}
\details{
\code{binCounts(x, bx, right = TRUE)} gives equivalent results as
\code{rev(binCounts(-x, bx = rev(-bx), right = FALSE))}, but is faster
and more memory efficient.
}
\section{Missing and non-finite values}{
Missing values in \code{x} are ignored/dropped. Missing values in \code{bx}
are not allowed and gives an error.
}
\seealso{
An alternative for counting occurrences within bins is
\code{\link[graphics]{hist}}, e.g. \code{hist(x, breaks = bx,
plot = FALSE)$counts}. That approach is ~30-60\% slower than
\code{binCounts(..., right = TRUE)}.
To count occurrences of indices \code{x} (positive
\code{\link[base]{integer}}s) in \code{[1, B]}, use \code{tabulate(x,
nbins = B)}, where \code{x} does \emph{not} have to be sorted first. For
details, see \code{\link[base]{tabulate}}().
To average values within bins, see \code{\link{binMeans}}().
}
\author{
Henrik Bengtsson
}
\keyword{univar}
|
/man/binCounts.Rd
|
no_license
|
HenrikBengtsson/matrixStats
|
R
| false | true | 1,953 |
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/binCounts.R
\name{binCounts}
\alias{binCounts}
\title{Fast element counting in non-overlapping bins}
\usage{
binCounts(x, idxs = NULL, bx, right = FALSE, ...)
}
\arguments{
\item{x}{A \code{\link[base]{numeric}} \code{\link[base]{vector}} of K
positions for to be binned and counted.}
\item{idxs}{A \code{\link[base]{vector}} indicating subset of elements to
operate over. If \code{\link[base]{NULL}}, no subsetting is done.}
\item{bx}{A \code{\link[base]{numeric}} \code{\link[base]{vector}} of B + 1
ordered positions specifying the B > 0 bins \code{[bx[1], bx[2])},
\code{[bx[2], bx[3])}, ..., \code{[bx[B], bx[B + 1])}.}
\item{right}{If \code{\link[base:logical]{TRUE}}, the bins are right-closed
(left open), otherwise left-closed (right open).}
\item{...}{Not used.}
}
\value{
Returns an \code{\link[base]{integer}} \code{\link[base]{vector}} of
length B with non-negative integers.
}
\description{
Counts the number of elements in non-overlapping bins
}
\details{
\code{binCounts(x, bx, right = TRUE)} gives equivalent results as
\code{rev(binCounts(-x, bx = rev(-bx), right = FALSE))}, but is faster
and more memory efficient.
}
\section{Missing and non-finite values}{
Missing values in \code{x} are ignored/dropped. Missing values in \code{bx}
are not allowed and gives an error.
}
\seealso{
An alternative for counting occurrences within bins is
\code{\link[graphics]{hist}}, e.g. \code{hist(x, breaks = bx,
plot = FALSE)$counts}. That approach is ~30-60\% slower than
\code{binCounts(..., right = TRUE)}.
To count occurrences of indices \code{x} (positive
\code{\link[base]{integer}}s) in \code{[1, B]}, use \code{tabulate(x,
nbins = B)}, where \code{x} does \emph{not} have to be sorted first. For
details, see \code{\link[base]{tabulate}}().
To average values within bins, see \code{\link{binMeans}}().
}
\author{
Henrik Bengtsson
}
\keyword{univar}
|
## Put comments here that give an overall description of what your
## functions do
## Write a short comment describing this function
## This function creates a special "matrix" object that can cache its inverse.
## x is the input matrix, defaulf value is matrix().
## set() can change the input matrix.
## get() can get the input matrix.
## setinv() can cache the inverse.
## getinv() can get the cached inversion. It will return NULL if there is no cached inversion.
makeCacheMatrix <- function(x = matrix()) {
inv <- NULL
set <- function(y) {
x <<- y
inv <<- NULL
}
get <- function() x
setinv <- function(inversion) inv <<- inversion
getinv <- function() inv
list(set = set, get = get,
setinv = setinv,
getinv = getinv)
}
## Write a short comment describing this function
## This function computes the inverse of the special
## "matrix" returned by `makeCacheMatrix` above. If the inverse has
## already been calculated (and the matrix has not changed), then
## `cacheSolve` should retrieve the inverse from the cache.
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
inv <- x$getinv()
if(!is.null(inv)) {
message("getting cached data")
return(inv)
}
data <- x$get()
inv <- solve(data, ...)
x$setinv(inv)
inv
}
|
/cachematrix.R
|
no_license
|
hanruyu/ProgrammingAssignment2
|
R
| false | false | 1,305 |
r
|
## Put comments here that give an overall description of what your
## functions do
## Write a short comment describing this function
## This function creates a special "matrix" object that can cache its inverse.
## x is the input matrix, defaulf value is matrix().
## set() can change the input matrix.
## get() can get the input matrix.
## setinv() can cache the inverse.
## getinv() can get the cached inversion. It will return NULL if there is no cached inversion.
makeCacheMatrix <- function(x = matrix()) {
inv <- NULL
set <- function(y) {
x <<- y
inv <<- NULL
}
get <- function() x
setinv <- function(inversion) inv <<- inversion
getinv <- function() inv
list(set = set, get = get,
setinv = setinv,
getinv = getinv)
}
## Write a short comment describing this function
## This function computes the inverse of the special
## "matrix" returned by `makeCacheMatrix` above. If the inverse has
## already been calculated (and the matrix has not changed), then
## `cacheSolve` should retrieve the inverse from the cache.
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
inv <- x$getinv()
if(!is.null(inv)) {
message("getting cached data")
return(inv)
}
data <- x$get()
inv <- solve(data, ...)
x$setinv(inv)
inv
}
|
#
# Utilities needed for preprocessing & analysing NCDC weather dataset
# (Can be regularly updated)
#
# String for latitude-longitude projection (can be passed into CRS)
g_latlongProj_str <- "+proj=longlat +datum=WGS84"
# Function to remove temporary objects
## Convention: name starting with 'c_'
rmMyTemp_fn <- function(pattern="^c_.*$") {
rm(list=apropos(pattern), pos=globalenv())
# CAREFUL: accesses global environment. Know what you are doing
}
# Function to parse string -> POSIX
parserDate_fn <- function(str, tz) {
if (!("package:lubridate" %in% search())) require(lubridate)
## PRE: string containing information about date and time (well-formatted)
## tz is a string for time zone -- here, restricted to US time zones.
## POST: UTC converted, POSIX vector
time <- as.POSIXct(str, tz=tz)
as_datetime(time, tz="UTC")
}
# Image saving function (png format, fixed resolution)
# (For ggplot use ggsave instead)
savePlot_fn <- function(filename, plotfn, ...) {
## PRE: plotfn can be plot. method or external plot functions
## ... passed onto plotfn as arguments
resultPlot <- plotfn(...)
png(filename, width=1080, height=720)
print(resultPlot)
dev.off()
}
# Function to display pairwise ggplots
# that do not necessarily share the same variables
# (May be generalized to include multiple, distinct ggplots)
pairGG_fn <- function(g1, g2, ...) {
## ... passed to ggmatrix fn
plotList <- list(g1, g2)
resultPlotMat <- ggmatrix(plotList, nrow=1, ncol=2, ...)
# Parameters: label / legend / aes, etc.
resultPlotMat
}
#---
# Function that creates a binary weights matrix for time series (see Griffith, 2013)
binAdjTime_fn <- function(n, lags=NULL) {
# only parameter is n, the dimension (number of time points)
adjMat <- matrix(0, n, n)
if (is.null(lags)) {
for (i in 1:n) {
if (i==1) adjMat[i,c(i,i+1)] <- c(1,-1)
else if (i==n) adjMat[i,c(i-1,i)] <- c(-1,1)
else adjMat[i,c(i-1,i,i+1)] <- c(-1,2,-1)
}
return(adjMat)
}
# if lags specified, not Griffith style.
for (i in 1:n) {
for (l in lags) {
if (i+l<=n) adjMat[i,(i+l)] <- 1
if (i-l>0) adjMat[i,(i-l)] <- 1
}
}
return(adjMat)
}
# Function that performs a Moran basis operation given covariates and adjacency matrix
# (see Griffith, 2013; Hughes and Haran, 2013 -- can be accommodated to either setting)
moranEigen_fn <- function(X=NULL, A, k, attractive=T) {
# PRE: X is n x p covariates (default is NULL -- no orthogonality restriction).
# A is the adjacency matrix that the user specifies.
# POST: Returns a list of k eigenvalues and eigenvectors of the Moran basis matrix.
if (require(Matrix) && require(RSpectra)) {
n <- nrow(A)
if (is.null(X)) X <- rep(1,n) # if NULL, no covariates -- all 1's
projection <- X %*% solve(t(X) %*% X) %*% t(X) # Projection matrix onto col. space of X
I <- diag(1,n,n) # identity matrix
Mx <- t(I-projection) %*% as(A, "dgCMatrix") %*% (I-projection) # Moran expansion on the adj. matrix.
result <- eigs_sym(k=k, as(Mx, "dgeMatrix")) # Returns a list.
if (attractive) return(result$vectors[,result$values > 0])
return(result)
}
}
#---
# Header for CSV files in dataset
g_header_str <- c("STATION", "STATION_NAME", "ELEVATION", "LATITUDE", "LONGITUDE", "DATE",
"REPORTTPYE", "HOURLYSKYCONDITIONS", "HOURLYVISIBILITY", "HOURLYPRSENTWEATHERTYPE",
"HOURLYDRYBULBTEMPF", "HOURLYDRYBULBTEMPC", "HOURLYWETBULBTEMPF", "HOURLYWETBULBTEMPC",
"HOURLYDewPointTempF", "HOURLYDewPointTempC", "HOURLYRelativeHumidity",
"HOURLYWindSpeed", "HOURLYWindDirection", "HOURLYWindGustSpeed", "HOURLYStationPressure",
"HOURLYPressureTendency", "HOURLYPressureChange", "HOURLYSeaLevelPressure",
"HOURLYPrecip", "HOURLYAltimeterSetting", "DAILYMaximumDryBulbTemp", "DAILYMinimumDryBulbTemp",
"DAILYAverageDryBulbTemp", "DAILYDeptFromNormalAverageTemp", "DAILYAverageRelativeHumidity",
"DAILYAverageDewPointTemp", "DAILYAverageWetBulbTemp", "DAILYHeatingDegreeDays",
"DAILYCoolingDegreeDays", "DAILYSunrise", "DAILYSunset", "DAILYWeather", "DAILYPrecip",
"DAILYSnowfall", "DAILYSnowDepth", "DAILYAverageStationPressure", "DAILYAverageSeaLevelPressure",
"DAILYAverageWindSpeed", "DAILYPeakWindSpeed", "PeakWindDirection", "DAILYSustainedWindSpeed",
"DAILYSustainedWindDirection", "MonthlyMaximumTemp", "MonthlyMinimumTemp",
"MonthlyMeanTemp", "MonthlyAverageRH", "MonthlyDewpointTemp", "MonthlyWetBulbTemp",
"MonthlyAvgHeatingDegreeDays", "MonthlyAvgCoolingDegreeDays", "MonthlyStationPressure",
"MonthlySeaLevelPressure", "MonthlyAverageWindSpeed", "MonthlyTotalSnowfall", "MonthlyDeptFromNormalMaximumTemp",
"MonthlyDeptFromNormalMinimumTemp", "MonthlyDeptFromNormalAverageTemp", "MonthlyDeptFromNormalPrecip",
"MonthlyTotalLiquidPrecip", "MonthlyGreatestPrecip", "MonthlyGreatestPrecipDate", "MonthlyGreatestSnowfall",
"MonthlyGreatestSnowfallDate", "MonthlyGreatestSnowDepth", "MonthlyGreatestSnowDepthDate", "MonthlyDaysWithGT90Temp",
"MonthlyDaysWithLT32Temp", "MonthlyDaysWithGT32Temp", "MonthlyDaysWithLT0Temp", "MonthlyDaysWithGT001Precip", "MonthlyDaysWithGT010Precip",
"MonthlyDaysWithGT1Snow", "MonthlyMaxSeaLevelPressureValue", "MonthlyMaxSeaLevelPressureDate", "MonthlyMaxSeaLevelPressureTime",
"MonthlyMinSeaLevelPressureValue", "MonthlyMinSeaLevelPressureDate", "MonthlyMinSeaLevelPressureTime", "MonthlyTotalHeatingDegreeDays",
"MonthlyTotalCoolingDegreeDays", "MonthlyDeptFromNormalHeatingDD", "MonthlyDeptFromNormalCoolingDD", "MonthlyTotalSeasonToDateHeatingDD",
"MonthlyTotalSeasonToDateCoolingDD")
# Reading CSV files with options preset
myRead_csv <- function(file) read.csv(file, header=T, stringsAsFactors=F)
# Reading CSV without header (for merging use)
readNoHeader_csv <- function(file) {
read.csv(file, header=F, stringsAsFactors=F, skip=1)
}
# Function to merge all CSV files in the path to one data frame
mergeFiles_csv <- function(path) {
fileNames <- list.files(path, "*.csv", full.names=T)
allFiles <- lapply(fileNames, readNoHeader_csv)
result <- do.call(rbind.data.frame, allFiles)
names(result) <- g_header_str
return(result)
}
rm(g_header_str, myRead_csv, readNoHeader_csv)
|
/000_utils.R
|
no_license
|
ybaek/undergrad
|
R
| false | false | 6,200 |
r
|
#
# Utilities needed for preprocessing & analysing NCDC weather dataset
# (Can be regularly updated)
#
# String for latitude-longitude projection (can be passed into CRS)
g_latlongProj_str <- "+proj=longlat +datum=WGS84"
# Function to remove temporary objects
## Convention: name starting with 'c_'
rmMyTemp_fn <- function(pattern="^c_.*$") {
rm(list=apropos(pattern), pos=globalenv())
# CAREFUL: accesses global environment. Know what you are doing
}
# Function to parse string -> POSIX
parserDate_fn <- function(str, tz) {
if (!("package:lubridate" %in% search())) require(lubridate)
## PRE: string containing information about date and time (well-formatted)
## tz is a string for time zone -- here, restricted to US time zones.
## POST: UTC converted, POSIX vector
time <- as.POSIXct(str, tz=tz)
as_datetime(time, tz="UTC")
}
# Image saving function (png format, fixed resolution)
# (For ggplot use ggsave instead)
savePlot_fn <- function(filename, plotfn, ...) {
## PRE: plotfn can be plot. method or external plot functions
## ... passed onto plotfn as arguments
resultPlot <- plotfn(...)
png(filename, width=1080, height=720)
print(resultPlot)
dev.off()
}
# Function to display pairwise ggplots
# that do not necessarily share the same variables
# (May be generalized to include multiple, distinct ggplots)
pairGG_fn <- function(g1, g2, ...) {
## ... passed to ggmatrix fn
plotList <- list(g1, g2)
resultPlotMat <- ggmatrix(plotList, nrow=1, ncol=2, ...)
# Parameters: label / legend / aes, etc.
resultPlotMat
}
#---
# Function that creates a binary weights matrix for time series (see Griffith, 2013)
binAdjTime_fn <- function(n, lags=NULL) {
# only parameter is n, the dimension (number of time points)
adjMat <- matrix(0, n, n)
if (is.null(lags)) {
for (i in 1:n) {
if (i==1) adjMat[i,c(i,i+1)] <- c(1,-1)
else if (i==n) adjMat[i,c(i-1,i)] <- c(-1,1)
else adjMat[i,c(i-1,i,i+1)] <- c(-1,2,-1)
}
return(adjMat)
}
# if lags specified, not Griffith style.
for (i in 1:n) {
for (l in lags) {
if (i+l<=n) adjMat[i,(i+l)] <- 1
if (i-l>0) adjMat[i,(i-l)] <- 1
}
}
return(adjMat)
}
# Function that performs a Moran basis operation given covariates and adjacency matrix
# (see Griffith, 2013; Hughes and Haran, 2013 -- can be accommodated to either setting)
moranEigen_fn <- function(X=NULL, A, k, attractive=T) {
# PRE: X is n x p covariates (default is NULL -- no orthogonality restriction).
# A is the adjacency matrix that the user specifies.
# POST: Returns a list of k eigenvalues and eigenvectors of the Moran basis matrix.
if (require(Matrix) && require(RSpectra)) {
n <- nrow(A)
if (is.null(X)) X <- rep(1,n) # if NULL, no covariates -- all 1's
projection <- X %*% solve(t(X) %*% X) %*% t(X) # Projection matrix onto col. space of X
I <- diag(1,n,n) # identity matrix
Mx <- t(I-projection) %*% as(A, "dgCMatrix") %*% (I-projection) # Moran expansion on the adj. matrix.
result <- eigs_sym(k=k, as(Mx, "dgeMatrix")) # Returns a list.
if (attractive) return(result$vectors[,result$values > 0])
return(result)
}
}
#---
# Header for CSV files in dataset
g_header_str <- c("STATION", "STATION_NAME", "ELEVATION", "LATITUDE", "LONGITUDE", "DATE",
"REPORTTPYE", "HOURLYSKYCONDITIONS", "HOURLYVISIBILITY", "HOURLYPRSENTWEATHERTYPE",
"HOURLYDRYBULBTEMPF", "HOURLYDRYBULBTEMPC", "HOURLYWETBULBTEMPF", "HOURLYWETBULBTEMPC",
"HOURLYDewPointTempF", "HOURLYDewPointTempC", "HOURLYRelativeHumidity",
"HOURLYWindSpeed", "HOURLYWindDirection", "HOURLYWindGustSpeed", "HOURLYStationPressure",
"HOURLYPressureTendency", "HOURLYPressureChange", "HOURLYSeaLevelPressure",
"HOURLYPrecip", "HOURLYAltimeterSetting", "DAILYMaximumDryBulbTemp", "DAILYMinimumDryBulbTemp",
"DAILYAverageDryBulbTemp", "DAILYDeptFromNormalAverageTemp", "DAILYAverageRelativeHumidity",
"DAILYAverageDewPointTemp", "DAILYAverageWetBulbTemp", "DAILYHeatingDegreeDays",
"DAILYCoolingDegreeDays", "DAILYSunrise", "DAILYSunset", "DAILYWeather", "DAILYPrecip",
"DAILYSnowfall", "DAILYSnowDepth", "DAILYAverageStationPressure", "DAILYAverageSeaLevelPressure",
"DAILYAverageWindSpeed", "DAILYPeakWindSpeed", "PeakWindDirection", "DAILYSustainedWindSpeed",
"DAILYSustainedWindDirection", "MonthlyMaximumTemp", "MonthlyMinimumTemp",
"MonthlyMeanTemp", "MonthlyAverageRH", "MonthlyDewpointTemp", "MonthlyWetBulbTemp",
"MonthlyAvgHeatingDegreeDays", "MonthlyAvgCoolingDegreeDays", "MonthlyStationPressure",
"MonthlySeaLevelPressure", "MonthlyAverageWindSpeed", "MonthlyTotalSnowfall", "MonthlyDeptFromNormalMaximumTemp",
"MonthlyDeptFromNormalMinimumTemp", "MonthlyDeptFromNormalAverageTemp", "MonthlyDeptFromNormalPrecip",
"MonthlyTotalLiquidPrecip", "MonthlyGreatestPrecip", "MonthlyGreatestPrecipDate", "MonthlyGreatestSnowfall",
"MonthlyGreatestSnowfallDate", "MonthlyGreatestSnowDepth", "MonthlyGreatestSnowDepthDate", "MonthlyDaysWithGT90Temp",
"MonthlyDaysWithLT32Temp", "MonthlyDaysWithGT32Temp", "MonthlyDaysWithLT0Temp", "MonthlyDaysWithGT001Precip", "MonthlyDaysWithGT010Precip",
"MonthlyDaysWithGT1Snow", "MonthlyMaxSeaLevelPressureValue", "MonthlyMaxSeaLevelPressureDate", "MonthlyMaxSeaLevelPressureTime",
"MonthlyMinSeaLevelPressureValue", "MonthlyMinSeaLevelPressureDate", "MonthlyMinSeaLevelPressureTime", "MonthlyTotalHeatingDegreeDays",
"MonthlyTotalCoolingDegreeDays", "MonthlyDeptFromNormalHeatingDD", "MonthlyDeptFromNormalCoolingDD", "MonthlyTotalSeasonToDateHeatingDD",
"MonthlyTotalSeasonToDateCoolingDD")
# Reading CSV files with options preset
myRead_csv <- function(file) read.csv(file, header=T, stringsAsFactors=F)
# Reading CSV without header (for merging use)
readNoHeader_csv <- function(file) {
read.csv(file, header=F, stringsAsFactors=F, skip=1)
}
# Function to merge all CSV files in the path to one data frame
mergeFiles_csv <- function(path) {
fileNames <- list.files(path, "*.csv", full.names=T)
allFiles <- lapply(fileNames, readNoHeader_csv)
result <- do.call(rbind.data.frame, allFiles)
names(result) <- g_header_str
return(result)
}
rm(g_header_str, myRead_csv, readNoHeader_csv)
|
\name{predict.mixGGM}
\alias{predict.mixGGM}
\title{Cluster prediction by Mixture of Gaussian Graphical Models}
\description{Cluster prediction for multivariate observations based on Mixture of Gaussian Graphical Models estimated by \code{\link{mixGGM}}.}
\usage{
\method{predict}{mixGGM}(object, newdata, \dots)
}
\arguments{
\item{object}{An object of class \code{'mixGGM'} resulting from a call to \code{\link{mixGGM}}.}
\item{newdata}{A data frame or matrix giving the data. If missing the clustering data obtained from the call to \code{\link{mixGGM}} are classified.}
\item{\dots}{Further arguments passed to or from other methods.}
}
% \details{}
\value{
Returns a list of with the following components:
\item{classification}{a factor of predicted cluster labels for \code{newdata}.}
\item{z}{a matrix whose \emph{[i,k]}th entry is the probability that
observation \emph{i} in \code{newdata} belongs to the \emph{k}th cluster.}
}
% \note{}
\seealso{\code{\link{mixGGM}}.}
% \examples{}
|
/man/predict.mixGGM.Rd
|
no_license
|
lkampoli/mixggm
|
R
| false | false | 1,026 |
rd
|
\name{predict.mixGGM}
\alias{predict.mixGGM}
\title{Cluster prediction by Mixture of Gaussian Graphical Models}
\description{Cluster prediction for multivariate observations based on Mixture of Gaussian Graphical Models estimated by \code{\link{mixGGM}}.}
\usage{
\method{predict}{mixGGM}(object, newdata, \dots)
}
\arguments{
\item{object}{An object of class \code{'mixGGM'} resulting from a call to \code{\link{mixGGM}}.}
\item{newdata}{A data frame or matrix giving the data. If missing the clustering data obtained from the call to \code{\link{mixGGM}} are classified.}
\item{\dots}{Further arguments passed to or from other methods.}
}
% \details{}
\value{
Returns a list of with the following components:
\item{classification}{a factor of predicted cluster labels for \code{newdata}.}
\item{z}{a matrix whose \emph{[i,k]}th entry is the probability that
observation \emph{i} in \code{newdata} belongs to the \emph{k}th cluster.}
}
% \note{}
\seealso{\code{\link{mixGGM}}.}
% \examples{}
|
library("dplyr")
library("tidyverse")
library("lubridate")
rm(list=ls())
setwd(here::here("output", "measures"))
df1 <- readRDS('ab_type_pre.rds')
df2 <- readRDS('ab_type_2019.rds')
df3 <- readRDS('ab_type_2020.rds')
df4 <- readRDS('ab_type_2021.rds')
df5 <- readRDS('ab_type_2022.rds')
df2 <- bind_rows(df2)
df3 <- bind_rows(df3)
df4 <- bind_rows(df4)
df <- rbind(df1,df2,df3,df4,df5)
rm(df1,df2,df3,df4,df5)
broadtype <- c("Amoxicillin")
df <- df %>% select(patient_id,age,Date,type) %>%
mutate(age_cat= case_when(age>=0&age<=4 ~ "0-4",
age>=5&age<=14 ~ "5-14",
age>=15&age<=24 ~ "15-24",
age>=25&age<=34 ~ "25-34",
age>=35&age<=44 ~ "35-44",
age>=45&age<=54 ~ "45-54",
age>=55&age<=64 ~ "55-64",
age>=65&age<=74 ~ "65-74",
age>=75 ~ "75+"))
df$age_cat <- as.factor(df$age_cat)
df.broad <- df %>% filter(type %in% broadtype )
df.broad_total <- df.broad %>% group_by(Date,age_cat) %>% summarise(
broad_number = n()
)
first_mon=format(min(df.broad_total$Date),"%m-%Y")
last_mon= format(max(df.broad_total$Date),"%m-%Y")
plot.broad_number<- ggplot(df.broad_total, aes(x=Date, y=broad_number ,group=age_cat,color=age_cat))+
annotate(geom = "rect", xmin = as.Date("2021-01-01"),xmax = as.Date("2021-04-01"),ymin = -Inf, ymax = Inf,fill="grey80", alpha=0.5)+
annotate(geom = "rect", xmin = as.Date("2020-11-01"),xmax = as.Date("2020-12-01"),ymin = -Inf, ymax = Inf,fill="grey80", alpha=0.5)+
annotate(geom = "rect", xmin = as.Date("2020-03-01"),xmax = as.Date("2020-06-01"),ymin = -Inf, ymax = Inf,fill="grey80", alpha=0.5)+
geom_line(aes(linetype=age_cat))+
geom_point(aes(shape=age_cat))+
theme(legend.position = "right",legend.title =element_blank())+
labs(
fill = "Age",
title = "The total number of amoxicillin prescriptions by age",
subtitle = paste(first_mon,"-",last_mon),
y = "",
x=""
)+
theme(axis.text.x=element_text(angle=60,hjust=1))+
scale_shape_manual(values = c(rep(1:9))) +
scale_color_manual(values = c("coral2","deeppink3","darkred","darkviolet","brown3","goldenrod2","blue3","green3","forestgreen"))+
scale_x_date(date_labels = "%m-%Y", date_breaks = "1 month")
plot.broad_number
ggsave(
plot= plot.broad_number,
filename="amoxicillin_prescriptions_by_age.jpeg", path=here::here("output"),
)
rm(plot.broad_number,df.broad)
df.all <- df %>% group_by(Date,age_cat) %>% summarise(
ab_number = n()
)
df.prop <- merge(df.broad_total,df.all,by=c("Date","age_cat"))
df.prop$prop <- df.prop$broad_number/df.prop$ab_number
plot.broad_prop<- ggplot(df.prop, aes(x=Date, y=prop ,group=age_cat,color=age_cat))+
annotate(geom = "rect", xmin = as.Date("2021-01-01"),xmax = as.Date("2021-04-01"),ymin = -Inf, ymax = Inf,fill="grey80", alpha=0.5)+
annotate(geom = "rect", xmin = as.Date("2020-11-01"),xmax = as.Date("2020-12-01"),ymin = -Inf, ymax = Inf,fill="grey80", alpha=0.5)+
annotate(geom = "rect", xmin = as.Date("2020-03-01"),xmax = as.Date("2020-06-01"),ymin = -Inf, ymax = Inf,fill="grey80", alpha=0.5)+
geom_line(aes(linetype=age_cat))+
geom_point(aes(shape=age_cat))+
theme(legend.position = "right",legend.title =element_blank())+
labs(
fill = "Age",
title = "Proportion of amoxicillin prescribed by age",
subtitle = paste(first_mon,"-",last_mon),
y = "",
x=""
)+
scale_y_continuous(labels = scales::percent,breaks=seq(0, 1, by = 0.005))+
theme(axis.text.x=element_text(angle=60,hjust=1))+
scale_shape_manual(values = c(rep(1:9))) +
scale_color_manual(values = c("coral2","deeppink3","darkred","darkviolet","brown3","goldenrod2","blue3","green3","forestgreen"))+
scale_x_date(date_labels = "%m-%Y", date_breaks = "1 month")
plot.broad_prop
ggsave(
plot= plot.broad_prop,
filename="amoxicillin_proportion_by_age.jpeg", path=here::here("output"),
)
|
/analysis/plot/amoxicillin_percentage_by_age.R
|
permissive
|
opensafely/amr-uom-brit
|
R
| false | false | 4,160 |
r
|
library("dplyr")
library("tidyverse")
library("lubridate")
rm(list=ls())
setwd(here::here("output", "measures"))
df1 <- readRDS('ab_type_pre.rds')
df2 <- readRDS('ab_type_2019.rds')
df3 <- readRDS('ab_type_2020.rds')
df4 <- readRDS('ab_type_2021.rds')
df5 <- readRDS('ab_type_2022.rds')
df2 <- bind_rows(df2)
df3 <- bind_rows(df3)
df4 <- bind_rows(df4)
df <- rbind(df1,df2,df3,df4,df5)
rm(df1,df2,df3,df4,df5)
broadtype <- c("Amoxicillin")
df <- df %>% select(patient_id,age,Date,type) %>%
mutate(age_cat= case_when(age>=0&age<=4 ~ "0-4",
age>=5&age<=14 ~ "5-14",
age>=15&age<=24 ~ "15-24",
age>=25&age<=34 ~ "25-34",
age>=35&age<=44 ~ "35-44",
age>=45&age<=54 ~ "45-54",
age>=55&age<=64 ~ "55-64",
age>=65&age<=74 ~ "65-74",
age>=75 ~ "75+"))
df$age_cat <- as.factor(df$age_cat)
df.broad <- df %>% filter(type %in% broadtype )
df.broad_total <- df.broad %>% group_by(Date,age_cat) %>% summarise(
broad_number = n()
)
first_mon=format(min(df.broad_total$Date),"%m-%Y")
last_mon= format(max(df.broad_total$Date),"%m-%Y")
plot.broad_number<- ggplot(df.broad_total, aes(x=Date, y=broad_number ,group=age_cat,color=age_cat))+
annotate(geom = "rect", xmin = as.Date("2021-01-01"),xmax = as.Date("2021-04-01"),ymin = -Inf, ymax = Inf,fill="grey80", alpha=0.5)+
annotate(geom = "rect", xmin = as.Date("2020-11-01"),xmax = as.Date("2020-12-01"),ymin = -Inf, ymax = Inf,fill="grey80", alpha=0.5)+
annotate(geom = "rect", xmin = as.Date("2020-03-01"),xmax = as.Date("2020-06-01"),ymin = -Inf, ymax = Inf,fill="grey80", alpha=0.5)+
geom_line(aes(linetype=age_cat))+
geom_point(aes(shape=age_cat))+
theme(legend.position = "right",legend.title =element_blank())+
labs(
fill = "Age",
title = "The total number of amoxicillin prescriptions by age",
subtitle = paste(first_mon,"-",last_mon),
y = "",
x=""
)+
theme(axis.text.x=element_text(angle=60,hjust=1))+
scale_shape_manual(values = c(rep(1:9))) +
scale_color_manual(values = c("coral2","deeppink3","darkred","darkviolet","brown3","goldenrod2","blue3","green3","forestgreen"))+
scale_x_date(date_labels = "%m-%Y", date_breaks = "1 month")
plot.broad_number
ggsave(
plot= plot.broad_number,
filename="amoxicillin_prescriptions_by_age.jpeg", path=here::here("output"),
)
rm(plot.broad_number,df.broad)
df.all <- df %>% group_by(Date,age_cat) %>% summarise(
ab_number = n()
)
df.prop <- merge(df.broad_total,df.all,by=c("Date","age_cat"))
df.prop$prop <- df.prop$broad_number/df.prop$ab_number
plot.broad_prop<- ggplot(df.prop, aes(x=Date, y=prop ,group=age_cat,color=age_cat))+
annotate(geom = "rect", xmin = as.Date("2021-01-01"),xmax = as.Date("2021-04-01"),ymin = -Inf, ymax = Inf,fill="grey80", alpha=0.5)+
annotate(geom = "rect", xmin = as.Date("2020-11-01"),xmax = as.Date("2020-12-01"),ymin = -Inf, ymax = Inf,fill="grey80", alpha=0.5)+
annotate(geom = "rect", xmin = as.Date("2020-03-01"),xmax = as.Date("2020-06-01"),ymin = -Inf, ymax = Inf,fill="grey80", alpha=0.5)+
geom_line(aes(linetype=age_cat))+
geom_point(aes(shape=age_cat))+
theme(legend.position = "right",legend.title =element_blank())+
labs(
fill = "Age",
title = "Proportion of amoxicillin prescribed by age",
subtitle = paste(first_mon,"-",last_mon),
y = "",
x=""
)+
scale_y_continuous(labels = scales::percent,breaks=seq(0, 1, by = 0.005))+
theme(axis.text.x=element_text(angle=60,hjust=1))+
scale_shape_manual(values = c(rep(1:9))) +
scale_color_manual(values = c("coral2","deeppink3","darkred","darkviolet","brown3","goldenrod2","blue3","green3","forestgreen"))+
scale_x_date(date_labels = "%m-%Y", date_breaks = "1 month")
plot.broad_prop
ggsave(
plot= plot.broad_prop,
filename="amoxicillin_proportion_by_age.jpeg", path=here::here("output"),
)
|
library(yorkr)
### Name: teamBowlersWicketRunsOppnAllMatches
### Title: Team bowlers wicket runs against an opposition in all matches
### Aliases: teamBowlersWicketRunsOppnAllMatches
### ** Examples
## Not run:
##D # Get all matches between India and Australia
##D matches <- getAllMatchesBetweenTeams("Australia","India",dir="../data")
##D
##D teamBowlersWicketRunsOppnAllMatches(matches,"India","Australia")
##D m <-teamBowlerWicketsRunsOppnAllMatches(matches,"Australia","India",plot=FALSE)
## End(Not run)
|
/data/genthat_extracted_code/yorkr/examples/teamBowlersWicketRunsOppnAllMatches.Rd.R
|
no_license
|
surayaaramli/typeRrh
|
R
| false | false | 520 |
r
|
library(yorkr)
### Name: teamBowlersWicketRunsOppnAllMatches
### Title: Team bowlers wicket runs against an opposition in all matches
### Aliases: teamBowlersWicketRunsOppnAllMatches
### ** Examples
## Not run:
##D # Get all matches between India and Australia
##D matches <- getAllMatchesBetweenTeams("Australia","India",dir="../data")
##D
##D teamBowlersWicketRunsOppnAllMatches(matches,"India","Australia")
##D m <-teamBowlerWicketsRunsOppnAllMatches(matches,"Australia","India",plot=FALSE)
## End(Not run)
|
JACCARD.F <- function(partHard, partFuzzy, t_norm = c("minimum","product"))
{
if (missing(partHard))
stop("The hard partitions partHard must be given")
if (missing(partFuzzy))
stop("The fuzzy partitions partFuzzy must be given")
if (is.null(partHard))
stop("The hard partitions partHard is empty")
if (is.null(partFuzzy))
stop("The fuzzy partitions partFuzzy is empty")
partHard = as.matrix(partHard)
partFuzzy = as.matrix(partFuzzy)
if(any(dim(partHard) != dim(partFuzzy)))
stop("partHard and partFuzzy must be matrix of the same dimension")
t_norm <- match.arg(t_norm, choices = eval(formals(JACCARD.F)$t_norm))
out = partition_comp(HardClust = partHard,Fuzzy = partFuzzy, t_norm = t_norm)
return(out$Jaccard.F)
}
|
/R/JACCARD.F.R
|
no_license
|
bratnick/fclust
|
R
| false | false | 763 |
r
|
JACCARD.F <- function(partHard, partFuzzy, t_norm = c("minimum","product"))
{
if (missing(partHard))
stop("The hard partitions partHard must be given")
if (missing(partFuzzy))
stop("The fuzzy partitions partFuzzy must be given")
if (is.null(partHard))
stop("The hard partitions partHard is empty")
if (is.null(partFuzzy))
stop("The fuzzy partitions partFuzzy is empty")
partHard = as.matrix(partHard)
partFuzzy = as.matrix(partFuzzy)
if(any(dim(partHard) != dim(partFuzzy)))
stop("partHard and partFuzzy must be matrix of the same dimension")
t_norm <- match.arg(t_norm, choices = eval(formals(JACCARD.F)$t_norm))
out = partition_comp(HardClust = partHard,Fuzzy = partFuzzy, t_norm = t_norm)
return(out$Jaccard.F)
}
|
library(xts)
library(lubridate)
library(raster)
library(ncdf4)
pct09=read.csv("WT_data/pct09.cla",sep="",header=F)
san09=read.csv("WT_data/san09_500HGT.cla",sep="",header=F)
WTS=data.frame(WT_pct09=as.factor(pct09$V5),
WT_san09=as.factor(san09$V5[1:13545])
)
rownames(WTS)=ISOdate(pct09$V1,pct09$V2,pct09$V3)
saveRDS(WTS,"data/WTS_df.rds")
WTS_xts=as.xts(WTS)
saveRDS(WTS_xts,"data/WTS_xts.rds")
times_WTS=index(WTS_xts)
saveRDS(times_WTS,"data/times_WTS.rds")
months_WTS=month(times_WTS)
saveRDS(months_WTS,"data/months_WTS.rds")
list_month_f=list()
list_month_f[[1]]=table(months_WTS,WTS$WT_pct09)
list_month_f[[2]]=table(months_WTS,WTS$WT_san09)
write.csv(as.data.frame.array(list_month_f[[1]]),file="WT_data/f_WT_pct09.csv")
write.csv(as.data.frame.array(list_month_f[[2]]),file="WT_data/f_WT_san09.csv")
saveRDS(list_month_f,"data/list_month_f_WTS.rds")
#########################################################################àà
# reading lists
WTS=readRDS("data/WTS_df.rds")
WTS_xts=readRDS("data/WTS_xts.rds")
months_WTS=readRDS("data/months_WTS.rds")
times_WTS=readRDS("data/times_WTS.rds")
###########################################################################################
# list climatological 1980-2010
temp=data.frame(mon=months_WTS[732:11688],wt=WTS$WT_pct09[732:11688])
list_WT_WT_pct09=split(temp,temp[c('mon','wt')])
list_WT_pct09=lapply(list_WT_WT_pct09,function(x) rownames(x))
names(list_WT_pct09)<-gsub("\\.","_",paste0("ind_wt_",names(list_WT_pct09)))
saveRDS(list_WT_pct09,"data/list_WT_pct09.rds")
temp=data.frame(mon=months_WTS[732:11688],wt=WTS$WT_san09[732:11688])
list_WT_WT_san09=split(temp,temp[c('mon','wt')])
list_WT_san09=lapply(list_WT_WT_san09,function(x) rownames(x))
names(list_WT_san09)<-gsub("\\.","_",paste0("ind_wt_",names(list_WT_san09)))
saveRDS(list_WT_san09,"data/list_WT_san09.rds")
###########################################################################################
# list recent full 1979-2016
temp=data.frame(mon=months_WTS,wt=WTS$WT_pct09)
list_WT_WT_pct09=split(temp,temp[c('mon','wt')])
list_WT_pct09=lapply(list_WT_WT_pct09,function(x) rownames(x))
names(list_WT_pct09)<-gsub("\\.","_",paste0("ind_wt_",names(list_WT_pct09)))
saveRDS(list_WT_pct09,"data/list_WT_pct09_full.rds")
temp=data.frame(mon=months_WTS,wt=WTS$WT_san09)
list_WT_WT_san09=split(temp,temp[c('mon','wt')])
list_WT_san09=lapply(list_WT_WT_san09,function(x) rownames(x))
names(list_WT_san09)<-gsub("\\.","_",paste0("ind_wt_",names(list_WT_san09)))
saveRDS(list_WT_san09,"data/list_WT_san09_full.rds")
###########################################################################################
# Questo è il passaggio che crea degli stack WT per ogni mese
##############################################################################################à
list_WT_pct09=readRDS("data/list_WT_pct09.rds")
list_WT_san09=readRDS("data/list_WT_san09.rds")
list_WTS=list(list_WT_pct09,list_WT_san09)
names(list_WTS)=c("WT_pct09","WT_san09")
dir.create("all_wt")
############################################################################################################
rr_daily=brick( "stack_eobs/rr_0.25deg_reg_1981-2010_stack.nc",lvar=1)
j=1
for (i in seq_along(list_WTS[[j]])) {
days=as.numeric(unlist(list_WTS[[j]][i]))
if ( length(days) >0) {
rr_temp_clim=subset(rr_daily,as.numeric(unlist(list_WTS[[j]][i])))
writeRaster(rr_temp_clim,paste0("all_wt/all_rr_",names(list_WTS)[j],"_",names(list_WTS[[j]])[[i]]), "CDF", overwrite=TRUE,varname="rr",varunit="mm",longname="thickness_of_rainfall_amount",xname="longitude",yname="latitude")
}
}
rm(rr_daily)
############################################################################################################
pp_daily=brick( "stack_eobs/pp_0.25deg_reg_1981-2010_stack.nc",lvar=1)
for (j in 1:2) {
for (i in seq_along(list_WTS[[j]])) {
days=as.numeric(unlist(list_WTS[[j]][i]))
if ( length(days) >0) {
pp_temp_clim=subset(pp_daily,as.numeric(unlist(list_WTS[[j]][i])))
writeRaster(pp_temp_clim,paste0("all_wt/all_pp_",names(list_WTS)[j],"_",names(list_WTS[[j]])[[i]]), "CDF", overwrite=TRUE,varname="pp",varunit="hPa",longname="air_pressure_at_sea_level",xname="longitude",yname="latitude")
}
}
}
rm(pp_daily)
############################################################################################################
tx_daily=brick( "stack_eobs/tx_0.25deg_reg_1981-2010_stack.nc",lvar=1)
j=2
for (i in seq_along(list_WTS[[j]])) {
days=as.numeric(unlist(list_WTS[[j]][i]))
if ( length(days) >0) {
tx_temp_clim=subset(tx_daily,as.numeric(unlist(list_WTS[[j]][i])))
writeRaster(tx_temp_clim,paste0("all_wt/all_tx_",names(list_WTS)[j],"_",names(list_WTS[[j]])[[i]]), "CDF", overwrite=TRUE,varname="tx",varunit="Celsius",longname="maximum temperature",xname="longitude",yname="latitude")
}
}
rm(tx_daily)
############################################################################################################
tn_daily=brick( "stack_eobs/tn_0.25deg_reg_1981-2010_stack.nc",lvar=1)
j=2
for (i in seq_along(list_WTS[[j]])) {
days=as.numeric(unlist(list_WTS[[j]][i]))
if ( length(days) >0) {
tn_temp_clim=subset(tn_daily,as.numeric(unlist(list_WTS[[j]][i])))
writeRaster(tn_temp_clim,paste0("all_wt/all_tn_",names(list_WTS)[j],"_",names(list_WTS[[j]])[[i]]), "CDF", overwrite=TRUE,varname="tn",varunit="Celsius",longname="minumum temperature",xname="longitude",yname="latitude")
}
}
rm(tn_daily)
############################################################################################################
tg_daily=brick( "stack_eobs/tg_0.25deg_reg_1981-2010_stack.nc",lvar=1)
j=2
for (i in seq_along(list_WTS[[j]])) {
days=as.numeric(unlist(list_WTS[[j]][i]))
if ( length(days) >0) {
tg_temp_clim=subset(tg_daily,as.numeric(unlist(list_WTS[[j]][i])))
writeRaster(tg_temp_clim,paste0("all_wt/all_tg_",names(list_WTS)[j],"_",names(list_WTS[[j]])[[i]]), "CDF", overwrite=TRUE,varname="tg",varunit="Celsius",longname="mean temperature",xname="longitude",yname="latitude")
}
}
rm(tg_daily)
############################################################################################################
gp1m_daily=brick( "stack_eobs/gpm1_0.25deg_reg_1981-2010_stack.nc",lvar=1)
j=1
for (i in seq_along(list_WTS[[j]])) {
days=as.numeric(unlist(list_WTS[[j]][i]))
if ( length(days) >0) {
gp1m_temp_clim=subset(gp1m_daily,as.numeric(unlist(list_WTS[[j]][i])))
writeRaster(gp1m_temp_clim,paste0("all_wt/all_gpm1_",names(list_WTS)[j],"_",names(list_WTS[[j]])[[i]]), "CDF", overwrite=TRUE,varname="gpm1",varunit="days",longname="rainy days over 1 mm",xname="longitude",yname="latitude")
}
}
rm(gp1m_daily)
############################################################################################################
|
/WT_init_proc.r
|
no_license
|
CLIMAIBIMETCNR/seasonal_forecast
|
R
| false | false | 7,029 |
r
|
library(xts)
library(lubridate)
library(raster)
library(ncdf4)
pct09=read.csv("WT_data/pct09.cla",sep="",header=F)
san09=read.csv("WT_data/san09_500HGT.cla",sep="",header=F)
WTS=data.frame(WT_pct09=as.factor(pct09$V5),
WT_san09=as.factor(san09$V5[1:13545])
)
rownames(WTS)=ISOdate(pct09$V1,pct09$V2,pct09$V3)
saveRDS(WTS,"data/WTS_df.rds")
WTS_xts=as.xts(WTS)
saveRDS(WTS_xts,"data/WTS_xts.rds")
times_WTS=index(WTS_xts)
saveRDS(times_WTS,"data/times_WTS.rds")
months_WTS=month(times_WTS)
saveRDS(months_WTS,"data/months_WTS.rds")
list_month_f=list()
list_month_f[[1]]=table(months_WTS,WTS$WT_pct09)
list_month_f[[2]]=table(months_WTS,WTS$WT_san09)
write.csv(as.data.frame.array(list_month_f[[1]]),file="WT_data/f_WT_pct09.csv")
write.csv(as.data.frame.array(list_month_f[[2]]),file="WT_data/f_WT_san09.csv")
saveRDS(list_month_f,"data/list_month_f_WTS.rds")
#########################################################################àà
# reading lists
WTS=readRDS("data/WTS_df.rds")
WTS_xts=readRDS("data/WTS_xts.rds")
months_WTS=readRDS("data/months_WTS.rds")
times_WTS=readRDS("data/times_WTS.rds")
###########################################################################################
# list climatological 1980-2010
temp=data.frame(mon=months_WTS[732:11688],wt=WTS$WT_pct09[732:11688])
list_WT_WT_pct09=split(temp,temp[c('mon','wt')])
list_WT_pct09=lapply(list_WT_WT_pct09,function(x) rownames(x))
names(list_WT_pct09)<-gsub("\\.","_",paste0("ind_wt_",names(list_WT_pct09)))
saveRDS(list_WT_pct09,"data/list_WT_pct09.rds")
temp=data.frame(mon=months_WTS[732:11688],wt=WTS$WT_san09[732:11688])
list_WT_WT_san09=split(temp,temp[c('mon','wt')])
list_WT_san09=lapply(list_WT_WT_san09,function(x) rownames(x))
names(list_WT_san09)<-gsub("\\.","_",paste0("ind_wt_",names(list_WT_san09)))
saveRDS(list_WT_san09,"data/list_WT_san09.rds")
###########################################################################################
# list recent full 1979-2016
temp=data.frame(mon=months_WTS,wt=WTS$WT_pct09)
list_WT_WT_pct09=split(temp,temp[c('mon','wt')])
list_WT_pct09=lapply(list_WT_WT_pct09,function(x) rownames(x))
names(list_WT_pct09)<-gsub("\\.","_",paste0("ind_wt_",names(list_WT_pct09)))
saveRDS(list_WT_pct09,"data/list_WT_pct09_full.rds")
temp=data.frame(mon=months_WTS,wt=WTS$WT_san09)
list_WT_WT_san09=split(temp,temp[c('mon','wt')])
list_WT_san09=lapply(list_WT_WT_san09,function(x) rownames(x))
names(list_WT_san09)<-gsub("\\.","_",paste0("ind_wt_",names(list_WT_san09)))
saveRDS(list_WT_san09,"data/list_WT_san09_full.rds")
###########################################################################################
# Questo è il passaggio che crea degli stack WT per ogni mese
##############################################################################################à
list_WT_pct09=readRDS("data/list_WT_pct09.rds")
list_WT_san09=readRDS("data/list_WT_san09.rds")
list_WTS=list(list_WT_pct09,list_WT_san09)
names(list_WTS)=c("WT_pct09","WT_san09")
dir.create("all_wt")
############################################################################################################
rr_daily=brick( "stack_eobs/rr_0.25deg_reg_1981-2010_stack.nc",lvar=1)
j=1
for (i in seq_along(list_WTS[[j]])) {
days=as.numeric(unlist(list_WTS[[j]][i]))
if ( length(days) >0) {
rr_temp_clim=subset(rr_daily,as.numeric(unlist(list_WTS[[j]][i])))
writeRaster(rr_temp_clim,paste0("all_wt/all_rr_",names(list_WTS)[j],"_",names(list_WTS[[j]])[[i]]), "CDF", overwrite=TRUE,varname="rr",varunit="mm",longname="thickness_of_rainfall_amount",xname="longitude",yname="latitude")
}
}
rm(rr_daily)
############################################################################################################
pp_daily=brick( "stack_eobs/pp_0.25deg_reg_1981-2010_stack.nc",lvar=1)
for (j in 1:2) {
for (i in seq_along(list_WTS[[j]])) {
days=as.numeric(unlist(list_WTS[[j]][i]))
if ( length(days) >0) {
pp_temp_clim=subset(pp_daily,as.numeric(unlist(list_WTS[[j]][i])))
writeRaster(pp_temp_clim,paste0("all_wt/all_pp_",names(list_WTS)[j],"_",names(list_WTS[[j]])[[i]]), "CDF", overwrite=TRUE,varname="pp",varunit="hPa",longname="air_pressure_at_sea_level",xname="longitude",yname="latitude")
}
}
}
rm(pp_daily)
############################################################################################################
tx_daily=brick( "stack_eobs/tx_0.25deg_reg_1981-2010_stack.nc",lvar=1)
j=2
for (i in seq_along(list_WTS[[j]])) {
days=as.numeric(unlist(list_WTS[[j]][i]))
if ( length(days) >0) {
tx_temp_clim=subset(tx_daily,as.numeric(unlist(list_WTS[[j]][i])))
writeRaster(tx_temp_clim,paste0("all_wt/all_tx_",names(list_WTS)[j],"_",names(list_WTS[[j]])[[i]]), "CDF", overwrite=TRUE,varname="tx",varunit="Celsius",longname="maximum temperature",xname="longitude",yname="latitude")
}
}
rm(tx_daily)
############################################################################################################
tn_daily=brick( "stack_eobs/tn_0.25deg_reg_1981-2010_stack.nc",lvar=1)
j=2
for (i in seq_along(list_WTS[[j]])) {
days=as.numeric(unlist(list_WTS[[j]][i]))
if ( length(days) >0) {
tn_temp_clim=subset(tn_daily,as.numeric(unlist(list_WTS[[j]][i])))
writeRaster(tn_temp_clim,paste0("all_wt/all_tn_",names(list_WTS)[j],"_",names(list_WTS[[j]])[[i]]), "CDF", overwrite=TRUE,varname="tn",varunit="Celsius",longname="minumum temperature",xname="longitude",yname="latitude")
}
}
rm(tn_daily)
############################################################################################################
tg_daily=brick( "stack_eobs/tg_0.25deg_reg_1981-2010_stack.nc",lvar=1)
j=2
for (i in seq_along(list_WTS[[j]])) {
days=as.numeric(unlist(list_WTS[[j]][i]))
if ( length(days) >0) {
tg_temp_clim=subset(tg_daily,as.numeric(unlist(list_WTS[[j]][i])))
writeRaster(tg_temp_clim,paste0("all_wt/all_tg_",names(list_WTS)[j],"_",names(list_WTS[[j]])[[i]]), "CDF", overwrite=TRUE,varname="tg",varunit="Celsius",longname="mean temperature",xname="longitude",yname="latitude")
}
}
rm(tg_daily)
############################################################################################################
gp1m_daily=brick( "stack_eobs/gpm1_0.25deg_reg_1981-2010_stack.nc",lvar=1)
j=1
for (i in seq_along(list_WTS[[j]])) {
days=as.numeric(unlist(list_WTS[[j]][i]))
if ( length(days) >0) {
gp1m_temp_clim=subset(gp1m_daily,as.numeric(unlist(list_WTS[[j]][i])))
writeRaster(gp1m_temp_clim,paste0("all_wt/all_gpm1_",names(list_WTS)[j],"_",names(list_WTS[[j]])[[i]]), "CDF", overwrite=TRUE,varname="gpm1",varunit="days",longname="rainy days over 1 mm",xname="longitude",yname="latitude")
}
}
rm(gp1m_daily)
############################################################################################################
|
test_that("Hemis can be shifted apart using rglactions for non-overlapping rendering.", {
testthat::skip_on_cran(); # CRAN maintainers asked me to reduce test time on CRAN by disabling unit tests.
skip_if(tests_running_on_cran_under_macos(), message = "Skipping on CRAN under MacOS, required test data cannot be downloaded.");
fsbrain::download_optional_data();
subjects_dir = fsbrain::get_optional_data_filepath("subjects_dir");
skip_if_not(dir.exists(subjects_dir), message="Test data missing.");
subject_id = "subject1";
vis.subject.morph.native(subjects_dir, subject_id, 'thickness', rglactions = list('shift_hemis_apart'=TRUE));
expect_equal(1L , 1L);
})
test_that("The limit function can be created.", {
lf = limit_fun(2, 3);
data = c(1.0,2.5,2.9, 3.5);
data_lim = lf(data);
expect_equal(length(data), length(data_lim));
})
test_that("The limit_na function can be created.", {
lf = limit_fun_na(2, 3);
data = c(1.0,2.5,2.9, 3.5);
data_lim = lf(data);
expect_equal(length(data), length(data_lim));
})
test_that("The demo rglactions list for screenshot can be created", {
rgla = rglactions();
testthat::expect_true(is.list(rgla));
})
|
/tests/testthat/test-rglactions.R
|
permissive
|
adigherman/fsbrain
|
R
| false | false | 1,220 |
r
|
test_that("Hemis can be shifted apart using rglactions for non-overlapping rendering.", {
testthat::skip_on_cran(); # CRAN maintainers asked me to reduce test time on CRAN by disabling unit tests.
skip_if(tests_running_on_cran_under_macos(), message = "Skipping on CRAN under MacOS, required test data cannot be downloaded.");
fsbrain::download_optional_data();
subjects_dir = fsbrain::get_optional_data_filepath("subjects_dir");
skip_if_not(dir.exists(subjects_dir), message="Test data missing.");
subject_id = "subject1";
vis.subject.morph.native(subjects_dir, subject_id, 'thickness', rglactions = list('shift_hemis_apart'=TRUE));
expect_equal(1L , 1L);
})
test_that("The limit function can be created.", {
lf = limit_fun(2, 3);
data = c(1.0,2.5,2.9, 3.5);
data_lim = lf(data);
expect_equal(length(data), length(data_lim));
})
test_that("The limit_na function can be created.", {
lf = limit_fun_na(2, 3);
data = c(1.0,2.5,2.9, 3.5);
data_lim = lf(data);
expect_equal(length(data), length(data_lim));
})
test_that("The demo rglactions list for screenshot can be created", {
rgla = rglactions();
testthat::expect_true(is.list(rgla));
})
|
# Generated by using Rcpp::compileAttributes() -> do not edit by hand
# Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393
#' Sample from the Dirichlet distribution
#'
#' @param n number ofsample
#' @param a vector of weights
#'
#' @export
rdirichlet <- function(n, a) {
.Call(`_dist_rdirichlet`, n, a)
}
#' Sample from the discrete distribution
#'
#' @param n number of samples
#' @param p vector of class probabilities, must sum to 1
#' @param as_indicator false: returns class number, true: returns binary vector
#'
#' @export
rdiscrete <- function(n, p, as_indicator = FALSE) {
.Call(`_dist_rdiscrete`, n, p, as_indicator)
}
#' Sample from the GEM distribution
#'
#' @param n number of samples
#' @param k vector size
#' @param b shape
#'
#' @export
rgem <- function(n, k, b) {
.Call(`_dist_rgem`, n, k, b)
}
#' Density function of the Laplace distribution
#'
#' @param x vector
#' @param m location
#' @param b scale
#'
#' @export
dlaplace <- function(x, m, b) {
.Call(`_dist_dlaplace`, x, m, b)
}
#' Distribution function of the Laplace distribution
#'
#' @param x quantile
#' @param m location
#' @param b scale
#'
#' @export
plaplace <- function(x, m, b) {
.Call(`_dist_plaplace`, x, m, b)
}
#' Sample from the Laplace distribution
#'
#' @param n number of samples
#' @param m location
#' @param b scale
#'
#' @export
rlaplace <- function(n, m, b) {
.Call(`_dist_rlaplace`, n, m, b)
}
|
/R/RcppExports.R
|
no_license
|
mkomod/dist
|
R
| false | false | 1,428 |
r
|
# Generated by using Rcpp::compileAttributes() -> do not edit by hand
# Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393
#' Sample from the Dirichlet distribution
#'
#' @param n number ofsample
#' @param a vector of weights
#'
#' @export
rdirichlet <- function(n, a) {
.Call(`_dist_rdirichlet`, n, a)
}
#' Sample from the discrete distribution
#'
#' @param n number of samples
#' @param p vector of class probabilities, must sum to 1
#' @param as_indicator false: returns class number, true: returns binary vector
#'
#' @export
rdiscrete <- function(n, p, as_indicator = FALSE) {
.Call(`_dist_rdiscrete`, n, p, as_indicator)
}
#' Sample from the GEM distribution
#'
#' @param n number of samples
#' @param k vector size
#' @param b shape
#'
#' @export
rgem <- function(n, k, b) {
.Call(`_dist_rgem`, n, k, b)
}
#' Density function of the Laplace distribution
#'
#' @param x vector
#' @param m location
#' @param b scale
#'
#' @export
dlaplace <- function(x, m, b) {
.Call(`_dist_dlaplace`, x, m, b)
}
#' Distribution function of the Laplace distribution
#'
#' @param x quantile
#' @param m location
#' @param b scale
#'
#' @export
plaplace <- function(x, m, b) {
.Call(`_dist_plaplace`, x, m, b)
}
#' Sample from the Laplace distribution
#'
#' @param n number of samples
#' @param m location
#' @param b scale
#'
#' @export
rlaplace <- function(n, m, b) {
.Call(`_dist_rlaplace`, n, m, b)
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/drugSetEnrichment.R
\name{matchStatsWithDrugSetsID}
\alias{matchStatsWithDrugSetsID}
\title{Match identifiers between data and drug sets}
\usage{
matchStatsWithDrugSetsID(
sets,
stats,
col = "values",
keyColSets = NULL,
keyColStats = NULL
)
}
\arguments{
\item{sets}{Named list of characters: named sets containing compound
identifiers (obtain drug sets by running \code{prepareDrugSets()})}
\item{stats}{Named numeric vector or either a \code{similarPerturbations} or
a \code{targetingDrugs} object (obtained after running
\code{\link{rankSimilarPerturbations}} or
\code{\link{predictTargetingDrugs}}, respectively)}
\item{col}{Character: name of the column to use for statistics (only required
if class of \code{stats} is either \code{similarPerturbations} or
\code{targetingDrugs})}
\item{keyColSets}{Character: column from \code{sets} to compare with column
\code{keyColStats} from \code{stats}; automatically selected if \code{NULL}}
\item{keyColStats}{Character: column from \code{stats} to compare with column
\code{keyColSets} from \code{sets}; automatically selected if \code{NULL}}
}
\value{
Statistic values from input data and corresponding identifiers as
names (if no match is found, the original identifier from argument
\code{stats} is used)
}
\description{
Match identifiers between data and drug sets
}
\keyword{internal}
|
/man/matchStatsWithDrugSetsID.Rd
|
permissive
|
nuno-agostinho/cTRAP
|
R
| false | true | 1,435 |
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/drugSetEnrichment.R
\name{matchStatsWithDrugSetsID}
\alias{matchStatsWithDrugSetsID}
\title{Match identifiers between data and drug sets}
\usage{
matchStatsWithDrugSetsID(
sets,
stats,
col = "values",
keyColSets = NULL,
keyColStats = NULL
)
}
\arguments{
\item{sets}{Named list of characters: named sets containing compound
identifiers (obtain drug sets by running \code{prepareDrugSets()})}
\item{stats}{Named numeric vector or either a \code{similarPerturbations} or
a \code{targetingDrugs} object (obtained after running
\code{\link{rankSimilarPerturbations}} or
\code{\link{predictTargetingDrugs}}, respectively)}
\item{col}{Character: name of the column to use for statistics (only required
if class of \code{stats} is either \code{similarPerturbations} or
\code{targetingDrugs})}
\item{keyColSets}{Character: column from \code{sets} to compare with column
\code{keyColStats} from \code{stats}; automatically selected if \code{NULL}}
\item{keyColStats}{Character: column from \code{stats} to compare with column
\code{keyColSets} from \code{sets}; automatically selected if \code{NULL}}
}
\value{
Statistic values from input data and corresponding identifiers as
names (if no match is found, the original identifier from argument
\code{stats} is used)
}
\description{
Match identifiers between data and drug sets
}
\keyword{internal}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/qvcalc.PlackettLuce.R
\name{qvcalc.PlackettLuce}
\alias{qvcalc.PlackettLuce}
\title{Quasi Variances for Model Coefficients}
\usage{
\method{qvcalc}{PlackettLuce}(object, ref = 1, ...)
}
\arguments{
\item{object}{a \code{"PlackettLuce"} object as returned by
\code{PlackettLuce}.}
\item{ref}{an integer or character string specifying the reference item (for
which log worth will be set to zero). If \code{NULL} the sum of the log worth
parameters is set to zero.}
\item{...}{additional arguments, currently ignored..}
}
\value{
A list of class \code{"qv"}, with components
\item{covmat}{The full variance-covariance matrix for the item
parameters.}
\item{qvframe}{A data frame with variables `estimate`, `SE`, `quasiSE` and
`quasiVar`, the last two being a quasi standard error and quasi-variance
for each parameter.}
\item{dispersion}{\code{NULL} (dispersion is fixed to 1).}
\item{relerrs}{Relative errors for approximating the standard errors of all
simple contrasts.}
\item{factorname}{\code{NULL} (not required for this method).}
\item{coef.indices}{\code{NULL} (not required for this method).}
\item{modelcall}{The call to \code{PlackettLuce} to fit the model from which
the item parameters were estimated.}
}
\description{
A method for \code{\link{qvcalc}} to compute a set of quasi variances (and
corresponding quasi standard errors) for estimated item parameters from a
Plackett-Luce model.
}
\details{
For details of the method see Firth (2000), Firth (2003) or Firth and de
Menezes (2004). Quasi variances generalize and improve the accuracy of
\dQuote{floating absolute risk} (Easton et al., 1991). This device for
economical model summary was first suggested by Ridout (1989).
Ordinarily the quasi variances are positive and so their square roots
(the quasi standard errors) exist and can be used in plots, etc.
}
\examples{
# Six partial rankings of four objects, 1 is top rank, e.g
# first ranking: item 1, item 2
# second ranking: item 2, item 3, item 4, item 1
# third ranking: items 2, 3, 4 tie for first place, item 1 second
R <- matrix(c(1, 2, 0, 0,
4, 1, 2, 3,
2, 1, 1, 1,
1, 2, 3, 0,
2, 1, 1, 0,
1, 0, 3, 2), nrow = 6, byrow = TRUE)
colnames(R) <- c("apple", "banana", "orange", "pear")
mod <- PlackettLuce(R)
qv <- qvcalc(mod)
qv
plot(qv)
}
\references{
Easton, D. F, Peto, J. and Babiker, A. G. A. G. (1991) Floating absolute
risk: an alternative to relative risk in survival and case-control analysis
avoiding an arbitrary reference group. *Statistics in Medicine* **10**,
1025--1035.
Firth, D. (2000) Quasi-variances in Xlisp-Stat and on the web.
*Journal of Statistical Software* **5.4**, 1--13.
At http://www.jstatsoft.org
Firth, D. (2003) Overcoming the reference category problem in the
presentation of statistical models. *Sociological Methodology*
**33**, 1--18.
Firth, D. and de Menezes, R. X. (2004) Quasi-variances.
*Biometrika* **91**, 65--80.
Menezes, R. X. de (1999) More useful standard errors for group and factor
effects in generalized linear models. *D.Phil. Thesis*,
Department of Statistics, University of Oxford.
Ridout, M.S. (1989). Summarizing the results of fitting generalized
linear models to data from designed experiments. In: *Statistical
Modelling: Proceedings of GLIM89 and the 4th International
Workshop on Statistical Modelling held in Trento, Italy, July 17--21,
1989* (A. Decarli et al., eds.), pp 262--269. New York: Springer.
}
\seealso{
\code{\link{worstErrors}}, \code{\link{plot.qv}}.
}
|
/man/qvcalc.PlackettLuce.Rd
|
no_license
|
anhnguyendepocen/PlackettLuce
|
R
| false | true | 3,623 |
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/qvcalc.PlackettLuce.R
\name{qvcalc.PlackettLuce}
\alias{qvcalc.PlackettLuce}
\title{Quasi Variances for Model Coefficients}
\usage{
\method{qvcalc}{PlackettLuce}(object, ref = 1, ...)
}
\arguments{
\item{object}{a \code{"PlackettLuce"} object as returned by
\code{PlackettLuce}.}
\item{ref}{an integer or character string specifying the reference item (for
which log worth will be set to zero). If \code{NULL} the sum of the log worth
parameters is set to zero.}
\item{...}{additional arguments, currently ignored..}
}
\value{
A list of class \code{"qv"}, with components
\item{covmat}{The full variance-covariance matrix for the item
parameters.}
\item{qvframe}{A data frame with variables `estimate`, `SE`, `quasiSE` and
`quasiVar`, the last two being a quasi standard error and quasi-variance
for each parameter.}
\item{dispersion}{\code{NULL} (dispersion is fixed to 1).}
\item{relerrs}{Relative errors for approximating the standard errors of all
simple contrasts.}
\item{factorname}{\code{NULL} (not required for this method).}
\item{coef.indices}{\code{NULL} (not required for this method).}
\item{modelcall}{The call to \code{PlackettLuce} to fit the model from which
the item parameters were estimated.}
}
\description{
A method for \code{\link{qvcalc}} to compute a set of quasi variances (and
corresponding quasi standard errors) for estimated item parameters from a
Plackett-Luce model.
}
\details{
For details of the method see Firth (2000), Firth (2003) or Firth and de
Menezes (2004). Quasi variances generalize and improve the accuracy of
\dQuote{floating absolute risk} (Easton et al., 1991). This device for
economical model summary was first suggested by Ridout (1989).
Ordinarily the quasi variances are positive and so their square roots
(the quasi standard errors) exist and can be used in plots, etc.
}
\examples{
# Six partial rankings of four objects, 1 is top rank, e.g
# first ranking: item 1, item 2
# second ranking: item 2, item 3, item 4, item 1
# third ranking: items 2, 3, 4 tie for first place, item 1 second
R <- matrix(c(1, 2, 0, 0,
4, 1, 2, 3,
2, 1, 1, 1,
1, 2, 3, 0,
2, 1, 1, 0,
1, 0, 3, 2), nrow = 6, byrow = TRUE)
colnames(R) <- c("apple", "banana", "orange", "pear")
mod <- PlackettLuce(R)
qv <- qvcalc(mod)
qv
plot(qv)
}
\references{
Easton, D. F, Peto, J. and Babiker, A. G. A. G. (1991) Floating absolute
risk: an alternative to relative risk in survival and case-control analysis
avoiding an arbitrary reference group. *Statistics in Medicine* **10**,
1025--1035.
Firth, D. (2000) Quasi-variances in Xlisp-Stat and on the web.
*Journal of Statistical Software* **5.4**, 1--13.
At http://www.jstatsoft.org
Firth, D. (2003) Overcoming the reference category problem in the
presentation of statistical models. *Sociological Methodology*
**33**, 1--18.
Firth, D. and de Menezes, R. X. (2004) Quasi-variances.
*Biometrika* **91**, 65--80.
Menezes, R. X. de (1999) More useful standard errors for group and factor
effects in generalized linear models. *D.Phil. Thesis*,
Department of Statistics, University of Oxford.
Ridout, M.S. (1989). Summarizing the results of fitting generalized
linear models to data from designed experiments. In: *Statistical
Modelling: Proceedings of GLIM89 and the 4th International
Workshop on Statistical Modelling held in Trento, Italy, July 17--21,
1989* (A. Decarli et al., eds.), pp 262--269. New York: Springer.
}
\seealso{
\code{\link{worstErrors}}, \code{\link{plot.qv}}.
}
|
# incluir imagenes en ggplots:
# https://drmowinckels.io/blog/adding-external-images-to-plots/
# ggimage
library(tidyverse)
library(ggplot2)
library(jpeg)
library(grid)
library(ggdark)
library(showtext)
theme_set(dark_theme_grey())
metallica <- readRDS("metallica.rds")
# does not work!
# mutate(track_name = fct_inorder(factor(track_name)))
metallica$track_name <- fct_inorder(factor(metallica$track_name))
metallica$album_name <- fct_inorder(factor(metallica$album_name))
# Dancebility
metallica %>%
ggplot(aes(track_name, danceability)) +
geom_col() +
facet_wrap(album_name~., scales="free", ncol = 3) +
coord_flip() +
labs(title = "Danceability")
# Los temas con riffs repetitivos tienen alto nivel de danceability:
# Devil's Dance, The thing that should not be, Sad but True, etc.
# Dancebility
metallica %>%
ggplot(aes(track_name, danceability, fill=album_name)) +
geom_col() +
facet_wrap(album_name~., scales="free", ncol = 3) +
coord_flip() +
labs(title = "Danceability") +
guides(fill = FALSE)
# En acousticness destacan las baladas: Mama Said, Nothing Else Matters,
# etc.
metallica %>%
ggplot(aes(track_name, acousticness, fill=album_name)) +
geom_col() +
facet_wrap(album_name~., scales="free", ncol = 3) +
coord_flip() +
labs(title = "Acousticness") +
guides(fill=FALSE)
# Los temas instrumentales también se ven en esta medida
metallica %>%
ggplot(aes(track_name, instrumentalness, fill=album_name)) +
geom_col() +
facet_wrap(album_name~., scales="free", ncol = 3) +
coord_flip() +
labs(title = "Instrumentalness") +
guides(fill=FALSE)
# Evolution of tempo
tempo <- metallica %>%
ggplot(aes(track_name, tempo, color = album_name, group = 1)) +
scale_x_discrete(breaks = NULL) +
geom_point() +
geom_smooth(se=FALSE) +
geom_smooth(aes(group=album_name), se = FALSE, method = "lm", formula = y~1) +
guides(color=FALSE) +
labs(title = "Song tempo over time", x="Albums", y="Tempo (BPM)")
# Evolution of energy
energy <- metallica %>%
ggplot(aes(track_name, energy, color = album_name, group = 1)) +
scale_x_discrete(breaks = NULL) +
geom_point() +
geom_smooth(se=FALSE) +
geom_smooth(aes(group=album_name), se = FALSE, method = "lm", formula = y~1) +
guides(color=FALSE) +
labs(title = "Song energy over time", x="Albums", y="Energy (BPM)")
fast_songs <- c("Holier Than Thou",
"My Apocalypse",
"The Four Horsemen")
highligts <- metallica %>%
filter(track_name %in% fast_songs)
# Gráfico de base.
tempo <- metallica %>%
ggplot(aes(album_name, tempo, group = 1)) +
scale_x_discrete(breaks = NULL, expand=c(0.1, 0)) +
scale_y_continuous(limits = c(60, 220)) +
geom_point() +
geom_text_repel(data = highligts,
aes(label=track_name),
nudge_y = 10,
nudge_x = .2,
color="white", size = 3) +
geom_smooth(se=FALSE) +
guides(color=FALSE) +
labs(title="Metallica",
subtitle = "U-shaped evolution of song tempo",
caption = "data: Spotify",
x="Album", y="Tempo (bpm)")
# Agregar las tapas de los discos como imágenes.
covers <- list.files('covers', full.names = TRUE) %>%
purrr::map(readJPEG) %>%
purrr::map(rasterGrob, interpolate=TRUE)
y_coord_cover <- 60
y_offset <- 10.5
font_add_google("Metal Mania", "metal")
showtext_auto()
output <- tempo +
annotation_custom(grob=covers[[1]], xmin=.5, xmax=1.5, ymin=y_coord_cover, ymax=y_coord_cover+y_offset) +
annotation_custom(grob=covers[[2]], xmin=1.5, xmax=2.5, ymin=y_coord_cover, ymax=y_coord_cover+y_offset) +
annotation_custom(grob=covers[[3]], xmin=2.5, xmax=3.5, ymin=y_coord_cover, ymax=y_coord_cover+y_offset) +
annotation_custom(grob=covers[[4]], xmin=3.5, xmax=4.5, ymin=y_coord_cover, ymax=y_coord_cover+y_offset) +
annotation_custom(grob=covers[[5]], xmin=4.5, xmax=5.5, ymin=y_coord_cover, ymax=y_coord_cover+y_offset) +
annotation_custom(grob=covers[[6]], xmin=5.5, xmax=6.5, ymin=y_coord_cover, ymax=y_coord_cover+y_offset) +
annotation_custom(grob=covers[[7]], xmin=6.5, xmax=7.5, ymin=y_coord_cover, ymax=y_coord_cover+y_offset) +
annotation_custom(grob=covers[[8]], xmin=7.5, xmax=8.5, ymin=y_coord_cover, ymax=y_coord_cover+y_offset) +
annotation_custom(grob=covers[[9]], xmin=8.5, xmax=9.5, ymin=y_coord_cover, ymax=y_coord_cover+y_offset) +
annotation_custom(grob=covers[[10]], xmin=9.5, xmax=10.5, ymin=y_coord_cover, ymax=y_coord_cover+y_offset) +
annotation_custom(grob=covers[[11]], xmin=10.5, xmax=11.5, ymin=y_coord_cover, ymax=y_coord_cover+y_offset) +
theme(
text = element_text(family="metal"),
plot.title = element_text(hjust = .5),
plot.subtitle = element_text(hjust=.5)
) +
ggsave("tempo_2.png")
# https://www.kaylinpavlik.com/song-distance/
|
/visualize.R
|
no_license
|
rlabuonora/metallica_viz
|
R
| false | false | 4,862 |
r
|
# incluir imagenes en ggplots:
# https://drmowinckels.io/blog/adding-external-images-to-plots/
# ggimage
library(tidyverse)
library(ggplot2)
library(jpeg)
library(grid)
library(ggdark)
library(showtext)
theme_set(dark_theme_grey())
metallica <- readRDS("metallica.rds")
# does not work!
# mutate(track_name = fct_inorder(factor(track_name)))
metallica$track_name <- fct_inorder(factor(metallica$track_name))
metallica$album_name <- fct_inorder(factor(metallica$album_name))
# Dancebility
metallica %>%
ggplot(aes(track_name, danceability)) +
geom_col() +
facet_wrap(album_name~., scales="free", ncol = 3) +
coord_flip() +
labs(title = "Danceability")
# Los temas con riffs repetitivos tienen alto nivel de danceability:
# Devil's Dance, The thing that should not be, Sad but True, etc.
# Dancebility
metallica %>%
ggplot(aes(track_name, danceability, fill=album_name)) +
geom_col() +
facet_wrap(album_name~., scales="free", ncol = 3) +
coord_flip() +
labs(title = "Danceability") +
guides(fill = FALSE)
# En acousticness destacan las baladas: Mama Said, Nothing Else Matters,
# etc.
metallica %>%
ggplot(aes(track_name, acousticness, fill=album_name)) +
geom_col() +
facet_wrap(album_name~., scales="free", ncol = 3) +
coord_flip() +
labs(title = "Acousticness") +
guides(fill=FALSE)
# Los temas instrumentales también se ven en esta medida
metallica %>%
ggplot(aes(track_name, instrumentalness, fill=album_name)) +
geom_col() +
facet_wrap(album_name~., scales="free", ncol = 3) +
coord_flip() +
labs(title = "Instrumentalness") +
guides(fill=FALSE)
# Evolution of tempo
tempo <- metallica %>%
ggplot(aes(track_name, tempo, color = album_name, group = 1)) +
scale_x_discrete(breaks = NULL) +
geom_point() +
geom_smooth(se=FALSE) +
geom_smooth(aes(group=album_name), se = FALSE, method = "lm", formula = y~1) +
guides(color=FALSE) +
labs(title = "Song tempo over time", x="Albums", y="Tempo (BPM)")
# Evolution of energy
energy <- metallica %>%
ggplot(aes(track_name, energy, color = album_name, group = 1)) +
scale_x_discrete(breaks = NULL) +
geom_point() +
geom_smooth(se=FALSE) +
geom_smooth(aes(group=album_name), se = FALSE, method = "lm", formula = y~1) +
guides(color=FALSE) +
labs(title = "Song energy over time", x="Albums", y="Energy (BPM)")
fast_songs <- c("Holier Than Thou",
"My Apocalypse",
"The Four Horsemen")
highligts <- metallica %>%
filter(track_name %in% fast_songs)
# Gráfico de base.
tempo <- metallica %>%
ggplot(aes(album_name, tempo, group = 1)) +
scale_x_discrete(breaks = NULL, expand=c(0.1, 0)) +
scale_y_continuous(limits = c(60, 220)) +
geom_point() +
geom_text_repel(data = highligts,
aes(label=track_name),
nudge_y = 10,
nudge_x = .2,
color="white", size = 3) +
geom_smooth(se=FALSE) +
guides(color=FALSE) +
labs(title="Metallica",
subtitle = "U-shaped evolution of song tempo",
caption = "data: Spotify",
x="Album", y="Tempo (bpm)")
# Agregar las tapas de los discos como imágenes.
covers <- list.files('covers', full.names = TRUE) %>%
purrr::map(readJPEG) %>%
purrr::map(rasterGrob, interpolate=TRUE)
y_coord_cover <- 60
y_offset <- 10.5
font_add_google("Metal Mania", "metal")
showtext_auto()
output <- tempo +
annotation_custom(grob=covers[[1]], xmin=.5, xmax=1.5, ymin=y_coord_cover, ymax=y_coord_cover+y_offset) +
annotation_custom(grob=covers[[2]], xmin=1.5, xmax=2.5, ymin=y_coord_cover, ymax=y_coord_cover+y_offset) +
annotation_custom(grob=covers[[3]], xmin=2.5, xmax=3.5, ymin=y_coord_cover, ymax=y_coord_cover+y_offset) +
annotation_custom(grob=covers[[4]], xmin=3.5, xmax=4.5, ymin=y_coord_cover, ymax=y_coord_cover+y_offset) +
annotation_custom(grob=covers[[5]], xmin=4.5, xmax=5.5, ymin=y_coord_cover, ymax=y_coord_cover+y_offset) +
annotation_custom(grob=covers[[6]], xmin=5.5, xmax=6.5, ymin=y_coord_cover, ymax=y_coord_cover+y_offset) +
annotation_custom(grob=covers[[7]], xmin=6.5, xmax=7.5, ymin=y_coord_cover, ymax=y_coord_cover+y_offset) +
annotation_custom(grob=covers[[8]], xmin=7.5, xmax=8.5, ymin=y_coord_cover, ymax=y_coord_cover+y_offset) +
annotation_custom(grob=covers[[9]], xmin=8.5, xmax=9.5, ymin=y_coord_cover, ymax=y_coord_cover+y_offset) +
annotation_custom(grob=covers[[10]], xmin=9.5, xmax=10.5, ymin=y_coord_cover, ymax=y_coord_cover+y_offset) +
annotation_custom(grob=covers[[11]], xmin=10.5, xmax=11.5, ymin=y_coord_cover, ymax=y_coord_cover+y_offset) +
theme(
text = element_text(family="metal"),
plot.title = element_text(hjust = .5),
plot.subtitle = element_text(hjust=.5)
) +
ggsave("tempo_2.png")
# https://www.kaylinpavlik.com/song-distance/
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/ogbox.R
\name{roxygenTabular}
\alias{roxygenTabular}
\title{Roxygen table maker}
\usage{
roxygenTabular(df, col.names = TRUE, ...)
}
\arguments{
\item{df}{data.frame}
\item{col.names}{logica. If colnames should be included}
\item{...}{variables for format function}
}
\description{
Roxygen table maker
}
|
/man/roxygenTabular.Rd
|
permissive
|
oganm/ogbox
|
R
| false | true | 384 |
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/ogbox.R
\name{roxygenTabular}
\alias{roxygenTabular}
\title{Roxygen table maker}
\usage{
roxygenTabular(df, col.names = TRUE, ...)
}
\arguments{
\item{df}{data.frame}
\item{col.names}{logica. If colnames should be included}
\item{...}{variables for format function}
}
\description{
Roxygen table maker
}
|
#' The base Choropleth object.
#' @importFrom R6 R6Class
#' @importFrom scales comma
#' @importFrom ggplot2 scale_color_continuous coord_quickmap
#' @export
Choropleth = R6Class("Choropleth",
public = list(
# the key objects for this class
user.df = NULL, # input from user
map.df = NULL, # geometry of the map
choropleth.df = NULL, # result of binding user data with our map data
title = "", # title for map
legend = "", # title for legend
warn = TRUE, # warn user on clipped or missing values
ggplot_scale = NULL, # override default scale.
# warning, you need to set "drop=FALSE" for insets to render correctly
projection = coord_quickmap(),
ggplot_polygon = geom_polygon(aes(fill = value), color = "dark grey", size = 0.2),
# a choropleth map is defined by these two variables
# a data.frame of a map
# a data.frame that expresses values for regions of each map
initialize = function(map.df, user.df)
{
stopifnot(is.data.frame(map.df))
stopifnot("region" %in% colnames(map.df))
self$map.df = map.df
# all input, regardless of map, is just a bunch of (region, value) pairs
stopifnot(is.data.frame(user.df))
stopifnot(c("region", "value") %in% colnames(user.df))
self$user.df = user.df
self$user.df = self$user.df[, c("region", "value")]
stopifnot(anyDuplicated(self$user.df$region) == 0)
# things like insets won't color properly if they are characters, and not factors
if (is.character(self$user.df$value))
{
self$user.df$value = as.factor(self$user.df$value)
}
# initialize the map to the max zoom - i.e. all regions
self$set_zoom(NULL)
# if the user's data contains values which are not on the map,
# then emit a warning if appropriate
if (self$warn)
{
all_regions = unique(self$map.df$region)
user_regions = unique(self$user.df$region)
invalid_regions = setdiff(user_regions, all_regions)
if (length(invalid_regions) > 0)
{
invalid_regions = paste(invalid_regions, collapse = ", ")
warning(paste0("Your data.frame contains the following regions which are not mappable: ", invalid_regions))
}
}
},
render = function()
{
self$prepare_map()
ggplot(self$choropleth.df, aes(long, lat, group = group)) +
self$ggplot_polygon +
self$get_scale() +
self$theme_clean() +
ggtitle(self$title) +
self$projection
},
# support e.g. users just viewing states on the west coast
clip = function() {
stopifnot(!is.null(private$zoom))
self$user.df = self$user.df[self$user.df$region %in% private$zoom, ]
self$map.df = self$map.df[self$map.df$region %in% private$zoom, ]
},
# for us, discretizing values means
# 1. assigning each value to one of num_colors colors
# 2. formatting the intervals e.g. with commas
#' @importFrom Hmisc cut2
discretize = function()
{
if (is.numeric(self$user.df$value) && private$num_colors > 1) {
# if cut2 uses scientific notation, our attempt to put in commas will fail
scipen_orig = getOption("scipen")
options(scipen=999)
self$user.df$value = cut2(self$user.df$value, g = private$num_colors)
options(scipen=scipen_orig)
levels(self$user.df$value) = sapply(levels(self$user.df$value), self$format_levels)
}
},
bind = function() {
self$choropleth.df = left_join(self$map.df, self$user.df, by="region")
missing_regions = unique(self$choropleth.df[is.na(self$choropleth.df$value), ]$region)
if (self$warn && length(missing_regions) > 0)
{
missing_regions = paste(missing_regions, collapse = ", ");
warning_string = paste("The following regions were missing and are being set to NA:", missing_regions);
warning(warning_string);
}
self$choropleth.df = self$choropleth.df[order(self$choropleth.df$order), ];
},
prepare_map = function()
{
self$clip() # clip the input - e.g. remove value for Washington DC on a 50 state map
self$discretize() # discretize the input. normally people don't want a continuous scale
self$bind() # bind the input values to the map values
},
#' @importFrom scales comma
get_scale = function()
{
if (!is.null(self$ggplot_scale))
{
self$ggplot_scale
} else if (private$num_colors == 1) {
min_value = min(self$choropleth.df$value, na.rm = TRUE)
max_value = max(self$choropleth.df$value, na.rm = TRUE)
stopifnot(!is.na(min_value) && !is.na(max_value))
# by default, scale_fill_continuous uses a light value for high values and a dark value for low values
# however, this is the opposite of how choropleths are normally colored (see wikipedia)
# these low and high values are from the 7 color brewer blue scale (see colorbrewer.org)
scale_fill_continuous(self$legend, low="#eff3ff", high="#084594", labels=comma, na.value="black", limits=c(min_value, max_value))
} else {
scale_fill_brewer(self$legend, drop=FALSE, labels=comma, na.value="black")
}
},
#' Removes axes, margins and sets the background to white.
#' This code, with minor modifications, comes from section 13.19
# "Making a Map with a Clean Background" of "R Graphics Cookbook" by Winston Chang.
# Reused with permission.
theme_clean = function()
{
theme(
axis.title = element_blank(),
axis.text = element_blank(),
panel.background = element_blank(),
panel.grid = element_blank(),
axis.ticks.length = unit(0, "cm"),
axis.ticks.margin = unit(0, "cm"),
panel.margin = unit(0, "lines"),
plot.margin = unit(c(0, 0, 0, 0), "lines"),
complete = TRUE
)
},
# like theme clean, but also remove the legend
theme_inset = function()
{
theme(
legend.position = "none",
axis.title = element_blank(),
axis.text = element_blank(),
panel.background = element_blank(),
panel.grid = element_blank(),
axis.ticks.length = unit(0, "cm"),
axis.ticks.margin = unit(0, "cm"),
panel.margin = unit(0, "lines"),
plot.margin = unit(c(0, 0, 0, 0), "lines"),
complete = TRUE
)
},
#' Make the output of cut2 a bit easier to read
#'
#' Adds commas to numbers, removes unnecessary whitespace and allows an arbitrary separator.
#'
#' @param x A factor with levels created via Hmisc::cut2.
#' @param nsep A separator which you wish to use. Defaults to " to ".
#'
#' @export
#' @examples
#' data(df_pop_state)
#'
#' x = Hmisc::cut2(df_pop_state$value, g=3)
#' levels(x)
#' # [1] "[ 562803, 2851183)" "[2851183, 6353226)" "[6353226,37325068]"
#' levels(x) = sapply(levels(x), format_levels)
#' levels(x)
#' # [1] "[562,803 to 2,851,183)" "[2,851,183 to 6,353,226)" "[6,353,226 to 37,325,068]"
#'
#' @seealso \url{http://stackoverflow.com/questions/22416612/how-can-i-get-cut2-to-use-commas/}, which this implementation is based on.
#' @importFrom stringr str_extract_all
format_levels = function(x, nsep=" to ")
{
n = str_extract_all(x, "[-+]?[0-9]*\\.?[0-9]+")[[1]] # extract numbers
v = format(as.numeric(n), big.mark=",", trim=TRUE) # change format
x = as.character(x)
# preserve starting [ or ( if appropriate
prefix = ""
if (substring(x, 1, 1) %in% c("[", "("))
{
prefix = substring(x, 1, 1)
}
# preserve ending ] or ) if appropriate
suffix = ""
if (substring(x, nchar(x), nchar(x)) %in% c("]", ")"))
{
suffix = substring(x, nchar(x), nchar(x))
}
# recombine
paste0(prefix, paste(v,collapse=nsep), suffix)
},
set_zoom = function(zoom)
{
if (is.null(zoom))
{
# initialize the map to the max zoom - i.e. all regions
private$zoom = unique(self$map.df$region)
} else {
stopifnot(all(zoom %in% unique(self$map.df$region)))
private$zoom = zoom
}
},
get_zoom = function() { private$zoom },
set_num_colors = function(num_colors)
{
# if R's ?is.integer actually tested if a value was an integer, we could replace the
# first 2 tests with is.integer(num_colors)
stopifnot(is.numeric(num_colors)
&& num_colors%%1 == 0
&& num_colors > 0
&& num_colors < 10)
private$num_colors = num_colors
}
),
private = list(
zoom = NULL, # a vector of regions to zoom in on. if NULL, show all
num_colors = 7, # number of colors to use on the map. if 1 then use a continuous scale
has_invalid_regions = FALSE
)
)
|
/R/choropleth.R
|
no_license
|
cardiomoon/choroplethr
|
R
| false | false | 9,370 |
r
|
#' The base Choropleth object.
#' @importFrom R6 R6Class
#' @importFrom scales comma
#' @importFrom ggplot2 scale_color_continuous coord_quickmap
#' @export
Choropleth = R6Class("Choropleth",
public = list(
# the key objects for this class
user.df = NULL, # input from user
map.df = NULL, # geometry of the map
choropleth.df = NULL, # result of binding user data with our map data
title = "", # title for map
legend = "", # title for legend
warn = TRUE, # warn user on clipped or missing values
ggplot_scale = NULL, # override default scale.
# warning, you need to set "drop=FALSE" for insets to render correctly
projection = coord_quickmap(),
ggplot_polygon = geom_polygon(aes(fill = value), color = "dark grey", size = 0.2),
# a choropleth map is defined by these two variables
# a data.frame of a map
# a data.frame that expresses values for regions of each map
initialize = function(map.df, user.df)
{
stopifnot(is.data.frame(map.df))
stopifnot("region" %in% colnames(map.df))
self$map.df = map.df
# all input, regardless of map, is just a bunch of (region, value) pairs
stopifnot(is.data.frame(user.df))
stopifnot(c("region", "value") %in% colnames(user.df))
self$user.df = user.df
self$user.df = self$user.df[, c("region", "value")]
stopifnot(anyDuplicated(self$user.df$region) == 0)
# things like insets won't color properly if they are characters, and not factors
if (is.character(self$user.df$value))
{
self$user.df$value = as.factor(self$user.df$value)
}
# initialize the map to the max zoom - i.e. all regions
self$set_zoom(NULL)
# if the user's data contains values which are not on the map,
# then emit a warning if appropriate
if (self$warn)
{
all_regions = unique(self$map.df$region)
user_regions = unique(self$user.df$region)
invalid_regions = setdiff(user_regions, all_regions)
if (length(invalid_regions) > 0)
{
invalid_regions = paste(invalid_regions, collapse = ", ")
warning(paste0("Your data.frame contains the following regions which are not mappable: ", invalid_regions))
}
}
},
render = function()
{
self$prepare_map()
ggplot(self$choropleth.df, aes(long, lat, group = group)) +
self$ggplot_polygon +
self$get_scale() +
self$theme_clean() +
ggtitle(self$title) +
self$projection
},
# support e.g. users just viewing states on the west coast
clip = function() {
stopifnot(!is.null(private$zoom))
self$user.df = self$user.df[self$user.df$region %in% private$zoom, ]
self$map.df = self$map.df[self$map.df$region %in% private$zoom, ]
},
# for us, discretizing values means
# 1. assigning each value to one of num_colors colors
# 2. formatting the intervals e.g. with commas
#' @importFrom Hmisc cut2
discretize = function()
{
if (is.numeric(self$user.df$value) && private$num_colors > 1) {
# if cut2 uses scientific notation, our attempt to put in commas will fail
scipen_orig = getOption("scipen")
options(scipen=999)
self$user.df$value = cut2(self$user.df$value, g = private$num_colors)
options(scipen=scipen_orig)
levels(self$user.df$value) = sapply(levels(self$user.df$value), self$format_levels)
}
},
bind = function() {
self$choropleth.df = left_join(self$map.df, self$user.df, by="region")
missing_regions = unique(self$choropleth.df[is.na(self$choropleth.df$value), ]$region)
if (self$warn && length(missing_regions) > 0)
{
missing_regions = paste(missing_regions, collapse = ", ");
warning_string = paste("The following regions were missing and are being set to NA:", missing_regions);
warning(warning_string);
}
self$choropleth.df = self$choropleth.df[order(self$choropleth.df$order), ];
},
prepare_map = function()
{
self$clip() # clip the input - e.g. remove value for Washington DC on a 50 state map
self$discretize() # discretize the input. normally people don't want a continuous scale
self$bind() # bind the input values to the map values
},
#' @importFrom scales comma
get_scale = function()
{
if (!is.null(self$ggplot_scale))
{
self$ggplot_scale
} else if (private$num_colors == 1) {
min_value = min(self$choropleth.df$value, na.rm = TRUE)
max_value = max(self$choropleth.df$value, na.rm = TRUE)
stopifnot(!is.na(min_value) && !is.na(max_value))
# by default, scale_fill_continuous uses a light value for high values and a dark value for low values
# however, this is the opposite of how choropleths are normally colored (see wikipedia)
# these low and high values are from the 7 color brewer blue scale (see colorbrewer.org)
scale_fill_continuous(self$legend, low="#eff3ff", high="#084594", labels=comma, na.value="black", limits=c(min_value, max_value))
} else {
scale_fill_brewer(self$legend, drop=FALSE, labels=comma, na.value="black")
}
},
#' Removes axes, margins and sets the background to white.
#' This code, with minor modifications, comes from section 13.19
# "Making a Map with a Clean Background" of "R Graphics Cookbook" by Winston Chang.
# Reused with permission.
theme_clean = function()
{
theme(
axis.title = element_blank(),
axis.text = element_blank(),
panel.background = element_blank(),
panel.grid = element_blank(),
axis.ticks.length = unit(0, "cm"),
axis.ticks.margin = unit(0, "cm"),
panel.margin = unit(0, "lines"),
plot.margin = unit(c(0, 0, 0, 0), "lines"),
complete = TRUE
)
},
# like theme clean, but also remove the legend
theme_inset = function()
{
theme(
legend.position = "none",
axis.title = element_blank(),
axis.text = element_blank(),
panel.background = element_blank(),
panel.grid = element_blank(),
axis.ticks.length = unit(0, "cm"),
axis.ticks.margin = unit(0, "cm"),
panel.margin = unit(0, "lines"),
plot.margin = unit(c(0, 0, 0, 0), "lines"),
complete = TRUE
)
},
#' Make the output of cut2 a bit easier to read
#'
#' Adds commas to numbers, removes unnecessary whitespace and allows an arbitrary separator.
#'
#' @param x A factor with levels created via Hmisc::cut2.
#' @param nsep A separator which you wish to use. Defaults to " to ".
#'
#' @export
#' @examples
#' data(df_pop_state)
#'
#' x = Hmisc::cut2(df_pop_state$value, g=3)
#' levels(x)
#' # [1] "[ 562803, 2851183)" "[2851183, 6353226)" "[6353226,37325068]"
#' levels(x) = sapply(levels(x), format_levels)
#' levels(x)
#' # [1] "[562,803 to 2,851,183)" "[2,851,183 to 6,353,226)" "[6,353,226 to 37,325,068]"
#'
#' @seealso \url{http://stackoverflow.com/questions/22416612/how-can-i-get-cut2-to-use-commas/}, which this implementation is based on.
#' @importFrom stringr str_extract_all
format_levels = function(x, nsep=" to ")
{
n = str_extract_all(x, "[-+]?[0-9]*\\.?[0-9]+")[[1]] # extract numbers
v = format(as.numeric(n), big.mark=",", trim=TRUE) # change format
x = as.character(x)
# preserve starting [ or ( if appropriate
prefix = ""
if (substring(x, 1, 1) %in% c("[", "("))
{
prefix = substring(x, 1, 1)
}
# preserve ending ] or ) if appropriate
suffix = ""
if (substring(x, nchar(x), nchar(x)) %in% c("]", ")"))
{
suffix = substring(x, nchar(x), nchar(x))
}
# recombine
paste0(prefix, paste(v,collapse=nsep), suffix)
},
set_zoom = function(zoom)
{
if (is.null(zoom))
{
# initialize the map to the max zoom - i.e. all regions
private$zoom = unique(self$map.df$region)
} else {
stopifnot(all(zoom %in% unique(self$map.df$region)))
private$zoom = zoom
}
},
get_zoom = function() { private$zoom },
set_num_colors = function(num_colors)
{
# if R's ?is.integer actually tested if a value was an integer, we could replace the
# first 2 tests with is.integer(num_colors)
stopifnot(is.numeric(num_colors)
&& num_colors%%1 == 0
&& num_colors > 0
&& num_colors < 10)
private$num_colors = num_colors
}
),
private = list(
zoom = NULL, # a vector of regions to zoom in on. if NULL, show all
num_colors = 7, # number of colors to use on the map. if 1 then use a continuous scale
has_invalid_regions = FALSE
)
)
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/discrim_flexible.R
\name{discrim_flexible}
\alias{discrim_flexible}
\title{Flexible discriminant analysis}
\usage{
discrim_flexible(
mode = "classification",
num_terms = NULL,
prod_degree = NULL,
prune_method = NULL,
engine = "earth"
)
}
\arguments{
\item{mode}{A single character string for the prediction outcome mode.
Possible values for this model are "unknown", "regression", or
"classification".}
\item{num_terms}{The number of features that will be retained in the
final model, including the intercept.}
\item{prod_degree}{The highest possible interaction degree.}
\item{prune_method}{The pruning method.}
\item{engine}{A single character string specifying what computational engine
to use for fitting.}
}
\description{
\code{discrim_flexible()} defines a model that fits a discriminant analysis model
that can use nonlinear features created using multivariate adaptive
regression splines (MARS). This function can fit classification models.
\Sexpr[stage=render,results=rd]{parsnip:::make_engine_list("discrim_flexible")}
More information on how \pkg{parsnip} is used for modeling is at
\url{https://www.tidymodels.org/}.
}
\details{
This function only defines what \emph{type} of model is being fit. Once an engine
is specified, the \emph{method} to fit the model is also defined. See
\code{\link[=set_engine]{set_engine()}} for more on setting the engine, including how to set engine
arguments.
The model is not trained or fit until the \code{\link[=fit.model_spec]{fit()}} function is used
with the data.
Each of the arguments in this function other than \code{mode} and \code{engine} are
captured as \link[rlang:topic-quosure]{quosures}. To pass values
programmatically, use the \link[rlang:injection-operator]{injection operator} like so:
\if{html}{\out{<div class="sourceCode r">}}\preformatted{value <- 1
discrim_flexible(argument = !!value)
}\if{html}{\out{</div>}}
}
\references{
\url{https://www.tidymodels.org}, \href{https://www.tmwr.org/}{\emph{Tidy Modeling with R}}, \href{https://www.tidymodels.org/find/parsnip/}{searchable table of parsnip models}
}
\seealso{
\Sexpr[stage=render,results=rd]{parsnip:::make_seealso_list("discrim_flexible")}
}
|
/man/discrim_flexible.Rd
|
permissive
|
tidymodels/parsnip
|
R
| false | true | 2,265 |
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/discrim_flexible.R
\name{discrim_flexible}
\alias{discrim_flexible}
\title{Flexible discriminant analysis}
\usage{
discrim_flexible(
mode = "classification",
num_terms = NULL,
prod_degree = NULL,
prune_method = NULL,
engine = "earth"
)
}
\arguments{
\item{mode}{A single character string for the prediction outcome mode.
Possible values for this model are "unknown", "regression", or
"classification".}
\item{num_terms}{The number of features that will be retained in the
final model, including the intercept.}
\item{prod_degree}{The highest possible interaction degree.}
\item{prune_method}{The pruning method.}
\item{engine}{A single character string specifying what computational engine
to use for fitting.}
}
\description{
\code{discrim_flexible()} defines a model that fits a discriminant analysis model
that can use nonlinear features created using multivariate adaptive
regression splines (MARS). This function can fit classification models.
\Sexpr[stage=render,results=rd]{parsnip:::make_engine_list("discrim_flexible")}
More information on how \pkg{parsnip} is used for modeling is at
\url{https://www.tidymodels.org/}.
}
\details{
This function only defines what \emph{type} of model is being fit. Once an engine
is specified, the \emph{method} to fit the model is also defined. See
\code{\link[=set_engine]{set_engine()}} for more on setting the engine, including how to set engine
arguments.
The model is not trained or fit until the \code{\link[=fit.model_spec]{fit()}} function is used
with the data.
Each of the arguments in this function other than \code{mode} and \code{engine} are
captured as \link[rlang:topic-quosure]{quosures}. To pass values
programmatically, use the \link[rlang:injection-operator]{injection operator} like so:
\if{html}{\out{<div class="sourceCode r">}}\preformatted{value <- 1
discrim_flexible(argument = !!value)
}\if{html}{\out{</div>}}
}
\references{
\url{https://www.tidymodels.org}, \href{https://www.tmwr.org/}{\emph{Tidy Modeling with R}}, \href{https://www.tidymodels.org/find/parsnip/}{searchable table of parsnip models}
}
\seealso{
\Sexpr[stage=render,results=rd]{parsnip:::make_seealso_list("discrim_flexible")}
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/plot_fns.R
\name{plot.corRes}
\alias{plot.corRes}
\title{Plot corRes Object}
\usage{
\method{plot}{corRes}(
corRes_obj,
omicsData = NULL,
order_by = NULL,
colorbar_lim = c(NA, NA),
x_text = TRUE,
y_text = TRUE,
interactive = FALSE,
x_lab = NULL,
y_lab = NULL,
x_lab_size = 11,
y_lab_size = 11,
x_lab_angle = 90,
title_lab = NULL,
title_lab_size = 14,
legend_lab = NULL,
legend_position = "right",
color_low = NULL,
color_high = NULL,
bw_theme = TRUE,
use_VizSampNames = FALSE
)
}
\arguments{
\item{corRes_obj}{An object of class "corRes" created via \code{cor_result}}
\item{omicsData}{an object of the class 'pepData', 'isobaricpepData',
'proData', 'lipidData', 'metabData', 'nmrData' or 'seqData' created via
\code{\link{as.pepData}}, \code{\link{as.isobaricpepData}},
\code{\link{as.proData}}, \code{\link{as.lipidData}},
\code{\link{as.metabData}}, \code{\link{as.nmrData}}, or
\code{\link{as.seqData}}, respectively.}
\item{order_by}{A character string specifying a column in f_data by which to
order the samples.}
\item{colorbar_lim}{A pair of numeric values specifying the minimum and
maximum values to use in the heat map color bar. Defaults to 'c(NA, NA)',
in which case ggplot2 automatically sets the minimum and maximum values
based on the correlation values in the data.}
\item{x_text}{logical value. Indicates whether the x-axis will be labeled
with the sample names. The default is TRUE.}
\item{y_text}{logical value. Indicates whether the y-axis will be labeled
with the sample names. The default is TRUE.}
\item{interactive}{logical value. If TRUE produces an interactive plot.}
\item{x_lab}{character string specifying the x-axis label}
\item{y_lab}{character string specifying the y-axis label}
\item{x_lab_size}{integer value indicating the font size for the x-axis.
The default is 11.}
\item{y_lab_size}{integer value indicating the font size for the y-axis.
The default is 11.}
\item{x_lab_angle}{integer value indicating the angle of x-axis labels.
The default is 90.}
\item{title_lab}{character string specifying the plot title}
\item{title_lab_size}{integer value indicating the font size of the plot
title. The default is 14.}
\item{legend_lab}{character string specifying the legend title.}
\item{legend_position}{character string specifying the position of the
legend. Can be one of "right", "left", "top", "bottom", or "none". The
default is "none".}
\item{color_low}{character string specifying the color of the gradient for
low values}
\item{color_high}{character string specifying the color of the gradient for
high values}
\item{bw_theme}{logical value. If TRUE uses the ggplot2 black and white theme.}
\item{use_VizSampNames}{logical value. Indicates whether to use custom sample
names. The default is FALSE.}
}
\value{
ggplot2 plot object if interactive is FALSE, or plotly plot object if
interactive is TRUE
}
\description{
For plotting an S3 object of type 'corRes'
}
\examples{
library(pmartRdata)
mymetab <- edata_transform(omicsData = metab_object, data_scale = "log2")
mymetab <- group_designation(omicsData = mymetab, main_effects = "Phenotype")
my_correlation <- cor_result(omicsData = mymetab)
plot(my_correlation, omicsData = mymetab, order_by = "Phenotype")
\dontrun{
myseq_correlation <- cor_result(omicsData = rnaseq_object)
plot(myseq_correlation)
}
}
|
/man/plot-corRes.Rd
|
permissive
|
clabornd/pmartR
|
R
| false | true | 3,441 |
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/plot_fns.R
\name{plot.corRes}
\alias{plot.corRes}
\title{Plot corRes Object}
\usage{
\method{plot}{corRes}(
corRes_obj,
omicsData = NULL,
order_by = NULL,
colorbar_lim = c(NA, NA),
x_text = TRUE,
y_text = TRUE,
interactive = FALSE,
x_lab = NULL,
y_lab = NULL,
x_lab_size = 11,
y_lab_size = 11,
x_lab_angle = 90,
title_lab = NULL,
title_lab_size = 14,
legend_lab = NULL,
legend_position = "right",
color_low = NULL,
color_high = NULL,
bw_theme = TRUE,
use_VizSampNames = FALSE
)
}
\arguments{
\item{corRes_obj}{An object of class "corRes" created via \code{cor_result}}
\item{omicsData}{an object of the class 'pepData', 'isobaricpepData',
'proData', 'lipidData', 'metabData', 'nmrData' or 'seqData' created via
\code{\link{as.pepData}}, \code{\link{as.isobaricpepData}},
\code{\link{as.proData}}, \code{\link{as.lipidData}},
\code{\link{as.metabData}}, \code{\link{as.nmrData}}, or
\code{\link{as.seqData}}, respectively.}
\item{order_by}{A character string specifying a column in f_data by which to
order the samples.}
\item{colorbar_lim}{A pair of numeric values specifying the minimum and
maximum values to use in the heat map color bar. Defaults to 'c(NA, NA)',
in which case ggplot2 automatically sets the minimum and maximum values
based on the correlation values in the data.}
\item{x_text}{logical value. Indicates whether the x-axis will be labeled
with the sample names. The default is TRUE.}
\item{y_text}{logical value. Indicates whether the y-axis will be labeled
with the sample names. The default is TRUE.}
\item{interactive}{logical value. If TRUE produces an interactive plot.}
\item{x_lab}{character string specifying the x-axis label}
\item{y_lab}{character string specifying the y-axis label}
\item{x_lab_size}{integer value indicating the font size for the x-axis.
The default is 11.}
\item{y_lab_size}{integer value indicating the font size for the y-axis.
The default is 11.}
\item{x_lab_angle}{integer value indicating the angle of x-axis labels.
The default is 90.}
\item{title_lab}{character string specifying the plot title}
\item{title_lab_size}{integer value indicating the font size of the plot
title. The default is 14.}
\item{legend_lab}{character string specifying the legend title.}
\item{legend_position}{character string specifying the position of the
legend. Can be one of "right", "left", "top", "bottom", or "none". The
default is "none".}
\item{color_low}{character string specifying the color of the gradient for
low values}
\item{color_high}{character string specifying the color of the gradient for
high values}
\item{bw_theme}{logical value. If TRUE uses the ggplot2 black and white theme.}
\item{use_VizSampNames}{logical value. Indicates whether to use custom sample
names. The default is FALSE.}
}
\value{
ggplot2 plot object if interactive is FALSE, or plotly plot object if
interactive is TRUE
}
\description{
For plotting an S3 object of type 'corRes'
}
\examples{
library(pmartRdata)
mymetab <- edata_transform(omicsData = metab_object, data_scale = "log2")
mymetab <- group_designation(omicsData = mymetab, main_effects = "Phenotype")
my_correlation <- cor_result(omicsData = mymetab)
plot(my_correlation, omicsData = mymetab, order_by = "Phenotype")
\dontrun{
myseq_correlation <- cor_result(omicsData = rnaseq_object)
plot(myseq_correlation)
}
}
|
(function(e,t){function u(e){var t=o[e]={},n,r;e=e.split(/\s+/);for(n=0,r=e.length;n<r;n++){t[e[n]]=true}return t}function c(e,n,r){if(r===t&&e.nodeType===1){var i="data-"+n.replace(l,"-$1").toLowerCase();r=e.getAttribute(i);if(typeof r==="string"){try{r=r==="true"?true:r==="false"?false:r==="null"?null:s.isNumeric(r)?+r:f.test(r)?s.parseJSON(r):r}catch(o){}s.data(e,n,r)}else{r=t}}return r}function h(e){for(var t in e){if(t==="data"&&s.isEmptyObject(e[t])){continue}if(t!=="toJSON"){return false}}return true}function p(e,t,n){var r=t+"defer",i=t+"queue",o=t+"mark",u=s._data(e,r);if(u&&(n==="queue"||!s._data(e,i))&&(n==="mark"||!s._data(e,o))){setTimeout(function(){if(!s._data(e,i)&&!s._data(e,o)){s.removeData(e,r,true);u.fire()}},0)}}function H(){return false}function B(){return true}function W(e){return!e||!e.parentNode||e.parentNode.nodeType===11}function X(e,t,n){t=t||0;if(s.isFunction(t)){return s.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n})}else if(t.nodeType){return s.grep(e,function(e,r){return e===t===n})}else if(typeof t==="string"){var r=s.grep(e,function(e){return e.nodeType===1});if(q.test(t)){return s.filter(t,r,!n)}else{t=s.filter(t,r)}}return s.grep(e,function(e,r){return s.inArray(e,t)>=0===n})}function V(e){var t=$.split("|"),n=e.createDocumentFragment();if(n.createElement){while(t.length){n.createElement(t.pop())}}return n}function at(e,t){return s.nodeName(e,"table")?e.getElementsByTagName("tbody")[0]||e.appendChild(e.ownerDocument.createElement("tbody")):e}function ft(e,t){if(t.nodeType!==1||!s.hasData(e)){return}var n,r,i,o=s._data(e),u=s._data(t,o),a=o.events;if(a){delete u.handle;u.events={};for(n in a){for(r=0,i=a[n].length;r<i;r++){s.event.add(t,n,a[n][r])}}}if(u.data){u.data=s.extend({},u.data)}}function lt(e,t){var n;if(t.nodeType!==1){return}if(t.clearAttributes){t.clearAttributes()}if(t.mergeAttributes){t.mergeAttributes(e)}n=t.nodeName.toLowerCase();if(n==="object"){t.outerHTML=e.outerHTML}else if(n==="input"&&(e.type==="checkbox"||e.type==="radio")){if(e.checked){t.defaultChecked=t.checked=e.checked}if(t.value!==e.value){t.value=e.value}}else if(n==="option"){t.selected=e.defaultSelected}else if(n==="input"||n==="textarea"){t.defaultValue=e.defaultValue}else if(n==="script"&&t.text!==e.text){t.text=e.text}t.removeAttribute(s.expando);t.removeAttribute("_submit_attached");t.removeAttribute("_change_attached")}function ct(e){if(typeof e.getElementsByTagName!=="undefined"){return e.getElementsByTagName("*")}else if(typeof e.querySelectorAll!=="undefined"){return e.querySelectorAll("*")}else{return[]}}function ht(e){if(e.type==="checkbox"||e.type==="radio"){e.defaultChecked=e.checked}}function pt(e){var t=(e.nodeName||"").toLowerCase();if(t==="input"){ht(e)}else if(t!=="script"&&typeof e.getElementsByTagName!=="undefined"){s.grep(e.getElementsByTagName("input"),ht)}}function dt(e){var t=n.createElement("div");ut.appendChild(t);t.innerHTML=e.outerHTML;return t.firstChild}function kt(e,t,n){var r=t==="width"?e.offsetWidth:e.offsetHeight,i=t==="width"?1:0,o=4;if(r>0){if(n!=="border"){for(;i<o;i+=2){if(!n){r-=parseFloat(s.css(e,"padding"+xt[i]))||0}if(n==="margin"){r+=parseFloat(s.css(e,n+xt[i]))||0}else{r-=parseFloat(s.css(e,"border"+xt[i]+"Width"))||0}}}return r+"px"}r=Tt(e,t);if(r<0||r==null){r=e.style[t]}if(bt.test(r)){return r}r=parseFloat(r)||0;if(n){for(;i<o;i+=2){r+=parseFloat(s.css(e,"padding"+xt[i]))||0;if(n!=="padding"){r+=parseFloat(s.css(e,"border"+xt[i]+"Width"))||0}if(n==="margin"){r+=parseFloat(s.css(e,n+xt[i]))||0}}}return r+"px"}function Qt(e){return function(t,n){if(typeof t!=="string"){n=t;t="*"}if(s.isFunction(n)){var r=t.toLowerCase().split(qt),i=0,o=r.length,u,a,f;for(;i<o;i++){u=r[i];f=/^\+/.test(u);if(f){u=u.substr(1)||"*"}a=e[u]=e[u]||[];a[f?"unshift":"push"](n)}}}}function Gt(e,n,r,i,s,o){s=s||n.dataTypes[0];o=o||{};o[s]=true;var u=e[s],a=0,f=u?u.length:0,l=e===Wt,c;for(;a<f&&(l||!c);a++){c=u[a](n,r,i);if(typeof c==="string"){if(!l||o[c]){c=t}else{n.dataTypes.unshift(c);c=Gt(e,n,r,i,c,o)}}}if((l||!c)&&!o["*"]){c=Gt(e,n,r,i,"*",o)}return c}function Yt(e,n){var r,i,o=s.ajaxSettings.flatOptions||{};for(r in n){if(n[r]!==t){(o[r]?e:i||(i={}))[r]=n[r]}}if(i){s.extend(true,e,i)}}function Zt(e,t,n,r){if(s.isArray(t)){s.each(t,function(t,i){if(n||At.test(e)){r(e,i)}else{Zt(e+"["+(typeof i==="object"?t:"")+"]",i,n,r)}})}else if(!n&&s.type(t)==="object"){for(var i in t){Zt(e+"["+i+"]",t[i],n,r)}}else{r(e,t)}}function en(e,n,r){var i=e.contents,s=e.dataTypes,o=e.responseFields,u,a,f,l;for(a in o){if(a in r){n[o[a]]=r[a]}}while(s[0]==="*"){s.shift();if(u===t){u=e.mimeType||n.getResponseHeader("content-type")}}if(u){for(a in i){if(i[a]&&i[a].test(u)){s.unshift(a);break}}}if(s[0]in r){f=s[0]}else{for(a in r){if(!s[0]||e.converters[a+" "+s[0]]){f=a;break}if(!l){l=a}}f=f||l}if(f){if(f!==s[0]){s.unshift(f)}return r[f]}}function tn(e,n){if(e.dataFilter){n=e.dataFilter(n,e.dataType)}var r=e.dataTypes,i={},o,u,a=r.length,f,l=r[0],c,h,p,d,v;for(o=1;o<a;o++){if(o===1){for(u in e.converters){if(typeof u==="string"){i[u.toLowerCase()]=e.converters[u]}}}c=l;l=r[o];if(l==="*"){l=c}else if(c!=="*"&&c!==l){h=c+" "+l;p=i[h]||i["* "+l];if(!p){v=t;for(d in i){f=d.split(" ");if(f[0]===c||f[0]==="*"){v=i[f[1]+" "+l];if(v){d=i[d];if(d===true){p=v}else if(v===true){p=d}break}}}}if(!(p||v)){s.error("No conversion from "+h.replace(" "," to "))}if(p!==true){n=p?p(n):v(d(n))}}}return n}function an(){try{return new e.XMLHttpRequest}catch(t){}}function fn(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}function yn(){setTimeout(bn,0);return gn=s.now()}function bn(){gn=t}function wn(e,t){var n={};s.each(mn.concat.apply([],mn.slice(0,t)),function(){n[this]=e});return n}function En(e){if(!ln[e]){var t=n.body,r=s("<"+e+">").appendTo(t),i=r.css("display");r.remove();if(i==="none"||i===""){if(!cn){cn=n.createElement("iframe");cn.frameBorder=cn.width=cn.height=0}t.appendChild(cn);if(!hn||!cn.createElement){hn=(cn.contentWindow||cn.contentDocument).document;hn.write((s.support.boxModel?"<!doctype html>":"")+"<html><body>");hn.close()}r=hn.createElement(e);hn.body.appendChild(r);i=s.css(r,"display");t.removeChild(cn)}ln[e]=i}return ln[e]}function Nn(e){return s.isWindow(e)?e:e.nodeType===9?e.defaultView||e.parentWindow:false}var n=e.document,r=e.navigator,i=e.location;var s=function(){function H(){if(i.isReady){return}try{n.documentElement.doScroll("left")}catch(e){setTimeout(H,1);return}i.ready()}var i=function(e,t){return new i.fn.init(e,t,u)},s=e.jQuery,o=e.$,u,a=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,f=/\S/,l=/^\s+/,c=/\s+$/,h=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,p=/^[\],:{}\s]*$/,d=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,v=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,m=/(?:^|:|,)(?:\s*\[)+/g,g=/(webkit)[ \/]([\w.]+)/,y=/(opera)(?:.*version)?[ \/]([\w.]+)/,b=/(msie) ([\w.]+)/,w=/(mozilla)(?:.*? rv:([\w.]+))?/,E=/-([a-z]|[0-9])/ig,S=/^-ms-/,x=function(e,t){return(t+"").toUpperCase()},T=r.userAgent,N,C,k,L=Object.prototype.toString,A=Object.prototype.hasOwnProperty,O=Array.prototype.push,M=Array.prototype.slice,_=String.prototype.trim,D=Array.prototype.indexOf,P={};i.fn=i.prototype={constructor:i,init:function(e,r,s){var o,u,f,l;if(!e){return this}if(e.nodeType){this.context=this[0]=e;this.length=1;return this}if(e==="body"&&!r&&n.body){this.context=n;this[0]=n.body;this.selector=e;this.length=1;return this}if(typeof e==="string"){if(e.charAt(0)==="<"&&e.charAt(e.length-1)===">"&&e.length>=3){o=[null,e,null]}else{o=a.exec(e)}if(o&&(o[1]||!r)){if(o[1]){r=r instanceof i?r[0]:r;l=r?r.ownerDocument||r:n;f=h.exec(e);if(f){if(i.isPlainObject(r)){e=[n.createElement(f[1])];i.fn.attr.call(e,r,true)}else{e=[l.createElement(f[1])]}}else{f=i.buildFragment([o[1]],[l]);e=(f.cacheable?i.clone(f.fragment):f.fragment).childNodes}return i.merge(this,e)}else{u=n.getElementById(o[2]);if(u&&u.parentNode){if(u.id!==o[2]){return s.find(e)}this.length=1;this[0]=u}this.context=n;this.selector=e;return this}}else if(!r||r.jquery){return(r||s).find(e)}else{return this.constructor(r).find(e)}}else if(i.isFunction(e)){return s.ready(e)}if(e.selector!==t){this.selector=e.selector;this.context=e.context}return i.makeArray(e,this)},selector:"",jquery:"1.7.2",length:0,size:function(){return this.length},toArray:function(){return M.call(this,0)},get:function(e){return e==null?this.toArray():e<0?this[this.length+e]:this[e]},pushStack:function(e,t,n){var r=this.constructor();if(i.isArray(e)){O.apply(r,e)}else{i.merge(r,e)}r.prevObject=this;r.context=this.context;if(t==="find"){r.selector=this.selector+(this.selector?" ":"")+n}else if(t){r.selector=this.selector+"."+t+"("+n+")"}return r},each:function(e,t){return i.each(this,e,t)},ready:function(e){i.bindReady();C.add(e);return this},eq:function(e){e=+e;return 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(M.apply(this,arguments),"slice",M.call(arguments).join(","))},map:function(e){return this.pushStack(i.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:O,sort:[].sort,splice:[].splice};i.fn.init.prototype=i.fn;i.extend=i.fn.extend=function(){var e,n,r,s,o,u,a=arguments[0]||{},f=1,l=arguments.length,c=false;if(typeof a==="boolean"){c=a;a=arguments[1]||{};f=2}if(typeof a!=="object"&&!i.isFunction(a)){a={}}if(l===f){a=this;--f}for(;f<l;f++){if((e=arguments[f])!=null){for(n in e){r=a[n];s=e[n];if(a===s){continue}if(c&&s&&(i.isPlainObject(s)||(o=i.isArray(s)))){if(o){o=false;u=r&&i.isArray(r)?r:[]}else{u=r&&i.isPlainObject(r)?r:{}}a[n]=i.extend(c,u,s)}else if(s!==t){a[n]=s}}}}return a};i.extend({noConflict:function(t){if(e.$===i){e.$=o}if(t&&e.jQuery===i){e.jQuery=s}return i},isReady:false,readyWait:1,holdReady:function(e){if(e){i.readyWait++}else{i.ready(true)}},ready:function(e){if(e===true&&!--i.readyWait||e!==true&&!i.isReady){if(!n.body){return setTimeout(i.ready,1)}i.isReady=true;if(e!==true&&--i.readyWait>0){return}C.fireWith(n,[i]);if(i.fn.trigger){i(n).trigger("ready").off("ready")}}},bindReady:function(){if(C){return}C=i.Callbacks("once memory");if(n.readyState==="complete"){return setTimeout(i.ready,1)}if(n.addEventListener){n.addEventListener("DOMContentLoaded",k,false);e.addEventListener("load",i.ready,false)}else if(n.attachEvent){n.attachEvent("onreadystatechange",k);e.attachEvent("onload",i.ready);var t=false;try{t=e.frameElement==null}catch(r){}if(n.documentElement.doScroll&&t){H()}}},isFunction:function(e){return i.type(e)==="function"},isArray:Array.isArray||function(e){return i.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):P[L.call(e)]||"object"},isPlainObject:function(e){if(!e||i.type(e)!=="object"||e.nodeType||i.isWindow(e)){return false}try{if(e.constructor&&!A.call(e,"constructor")&&!A.call(e.constructor.prototype,"isPrototypeOf")){return false}}catch(n){return false}var r;for(r in e){}return r===t||A.call(e,r)},isEmptyObject:function(e){for(var t in e){return false}return true},error:function(e){throw new Error(e)},parseJSON:function(t){if(typeof t!=="string"||!t){return null}t=i.trim(t);if(e.JSON&&e.JSON.parse){return e.JSON.parse(t)}if(p.test(t.replace(d,"@").replace(v,"]").replace(m,""))){return(new Function("return "+t))()}i.error("Invalid JSON: "+t)},parseXML:function(n){if(typeof n!=="string"||!n){return null}var r,s;try{if(e.DOMParser){s=new DOMParser;r=s.parseFromString(n,"text/xml")}else{r=new ActiveXObject("Microsoft.XMLDOM");r.async="false";r.loadXML(n)}}catch(o){r=t}if(!r||!r.documentElement||r.getElementsByTagName("parsererror").length){i.error("Invalid XML: "+n)}return r},noop:function(){},globalEval:function(t){if(t&&f.test(t)){(e.execScript||function(t){e["eval"].call(e,t)})(t)}},camelCase:function(e){return e.replace(S,"ms-").replace(E,x)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toUpperCase()===t.toUpperCase()},each:function(e,n,r){var s,o=0,u=e.length,a=u===t||i.isFunction(e);if(r){if(a){for(s in e){if(n.apply(e[s],r)===false){break}}}else{for(;o<u;){if(n.apply(e[o++],r)===false){break}}}}else{if(a){for(s in e){if(n.call(e[s],s,e[s])===false){break}}}else{for(;o<u;){if(n.call(e[o],o,e[o++])===false){break}}}}return e},trim:_?function(e){return e==null?"":_.call(e)}:function(e){return e==null?"":e.toString().replace(l,"").replace(c,"")},makeArray:function(e,t){var n=t||[];if(e!=null){var r=i.type(e);if(e.length==null||r==="string"||r==="function"||r==="regexp"||i.isWindow(e)){O.call(n,e)}else{i.merge(n,e)}}return n},inArray:function(e,t,n){var r;if(t){if(D){return D.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=e.length,i=0;if(typeof n.length==="number"){for(var s=n.length;i<s;i++){e[r++]=n[i]}}else{while(n[i]!==t){e[r++]=n[i++]}}e.length=r;return e},grep:function(e,t,n){var r=[],i;n=!!n;for(var s=0,o=e.length;s<o;s++){i=!!t(e[s],s);if(n!==i){r.push(e[s])}}return r},map:function(e,n,r){var s,o,u=[],a=0,f=e.length,l=e instanceof i||f!==t&&typeof f==="number"&&(f>0&&e[0]&&e[f-1]||f===0||i.isArray(e));if(l){for(;a<f;a++){s=n(e[a],a,r);if(s!=null){u[u.length]=s}}}else{for(o in e){s=n(e[o],o,r);if(s!=null){u[u.length]=s}}}return u.concat.apply([],u)},guid:1,proxy:function(e,n){if(typeof n==="string"){var r=e[n];n=e;e=r}if(!i.isFunction(e)){return t}var s=M.call(arguments,2),o=function(){return e.apply(n,s.concat(M.call(arguments)))};o.guid=e.guid=e.guid||o.guid||i.guid++;return o},access:function(e,n,r,s,o,u,a){var f,l=r==null,c=0,h=e.length;if(r&&typeof r==="object"){for(c in r){i.access(e,n,c,r[c],1,u,s)}o=1}else if(s!==t){f=a===t&&i.isFunction(s);if(l){if(f){f=n;n=function(e,t,n){return f.call(i(e),n)}}else{n.call(e,s);n=null}}if(n){for(;c<h;c++){n(e[c],r,f?s.call(e[c],c,n(e[c],r)):s,a)}}o=1}return o?e:l?n.call(e):h?n(e[0],r):u},now:function(){return(new Date).getTime()},uaMatch:function(e){e=e.toLowerCase();var t=g.exec(e)||y.exec(e)||b.exec(e)||e.indexOf("compatible")<0&&w.exec(e)||[];return{browser:t[1]||"",version:t[2]||"0"}},sub:function(){function e(t,n){return new e.fn.init(t,n)}i.extend(true,e,this);e.superclass=this;e.fn=e.prototype=this();e.fn.constructor=e;e.sub=this.sub;e.fn.init=function(r,s){if(s&&s instanceof i&&!(s instanceof e)){s=e(s)}return i.fn.init.call(this,r,s,t)};e.fn.init.prototype=e.fn;var t=e(n);return e},browser:{}});i.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(e,t){P["[object "+t+"]"]=t.toLowerCase()});N=i.uaMatch(T);if(N.browser){i.browser[N.browser]=true;i.browser.version=N.version}if(i.browser.webkit){i.browser.safari=true}if(f.test(" ")){l=/^[\s\xA0]+/;c=/[\s\xA0]+$/}u=i(n);if(n.addEventListener){k=function(){n.removeEventListener("DOMContentLoaded",k,false);i.ready()}}else if(n.attachEvent){k=function(){if(n.readyState==="complete"){n.detachEvent("onreadystatechange",k);i.ready()}}}return i}();var o={};s.Callbacks=function(e){e=e?o[e]||u(e):{};var n=[],r=[],i,a,f,l,c,h,p=function(t){var r,i,o,u,a;for(r=0,i=t.length;r<i;r++){o=t[r];u=s.type(o);if(u==="array"){p(o)}else if(u==="function"){if(!e.unique||!v.has(o)){n.push(o)}}}},d=function(t,s){s=s||[];i=!e.memory||[t,s];a=true;f=true;h=l||0;l=0;c=n.length;for(;n&&h<c;h++){if(n[h].apply(t,s)===false&&e.stopOnFalse){i=true;break}}f=false;if(n){if(!e.once){if(r&&r.length){i=r.shift();v.fireWith(i[0],i[1])}}else if(i===true){v.disable()}else{n=[]}}},v={add:function(){if(n){var e=n.length;p(arguments);if(f){c=n.length}else if(i&&i!==true){l=e;d(i[0],i[1])}}return this},remove:function(){if(n){var t=arguments,r=0,i=t.length;for(;r<i;r++){for(var s=0;s<n.length;s++){if(t[r]===n[s]){if(f){if(s<=c){c--;if(s<=h){h--}}}n.splice(s--,1);if(e.unique){break}}}}}return this},has:function(e){if(n){var t=0,r=n.length;for(;t<r;t++){if(e===n[t]){return true}}}return false},empty:function(){n=[];return this},disable:function(){n=r=i=t;return this},disabled:function(){return!n},lock:function(){r=t;if(!i||i===true){v.disable()}return this},locked:function(){return!r},fireWith:function(t,n){if(r){if(f){if(!e.once){r.push([t,n])}}else if(!(e.once&&i)){d(t,n)}}return this},fire:function(){v.fireWith(this,arguments);return this},fired:function(){return!!a}};return v};var a=[].slice;s.extend({Deferred:function(e){var t=s.Callbacks("once memory"),n=s.Callbacks("once memory"),r=s.Callbacks("memory"),i="pending",o={resolve:t,reject:n,notify:r},u={done:t.add,fail:n.add,progress:r.add,state:function(){return i},isResolved:t.fired,isRejected:n.fired,then:function(e,t,n){a.done(e).fail(t).progress(n);return this},always:function(){a.done.apply(a,arguments).fail.apply(a,arguments);return this},pipe:function(e,t,n){return s.Deferred(function(r){s.each({done:[e,"resolve"],fail:[t,"reject"],progress:[n,"notify"]},function(e,t){var n=t[0],i=t[1],o;if(s.isFunction(n)){a[e](function(){o=n.apply(this,arguments);if(o&&s.isFunction(o.promise)){o.promise().then(r.resolve,r.reject,r.notify)}else{r[i+"With"](this===a?r:this,[o])}})}else{a[e](r[i])}})}).promise()},promise:function(e){if(e==null){e=u}else{for(var t in u){e[t]=u[t]}}return e}},a=u.promise({}),f;for(f in o){a[f]=o[f].fire;a[f+"With"]=o[f].fireWith}a.done(function(){i="resolved"},n.disable,r.lock).fail(function(){i="rejected"},t.disable,r.lock);if(e){e.call(a,a)}return a},when:function(e){function c(e){return function(n){t[e]=arguments.length>1?a.call(arguments,0):n;if(!--o){f.resolveWith(f,t)}}}function h(e){return function(t){i[e]=arguments.length>1?a.call(arguments,0):t;f.notifyWith(l,i)}}var t=a.call(arguments,0),n=0,r=t.length,i=new Array(r),o=r,u=r,f=r<=1&&e&&s.isFunction(e.promise)?e:s.Deferred(),l=f.promise();if(r>1){for(;n<r;n++){if(t[n]&&t[n].promise&&s.isFunction(t[n].promise)){t[n].promise().then(c(n),f.reject,h(n))}else{--o}}if(!o){f.resolveWith(f,t)}}else if(f!==e){f.resolveWith(f,r?[e]:[])}return l}});s.support=function(){var t,r,i,o,u,a,f,l,c,h,p,d,v=n.createElement("div"),m=n.documentElement;v.setAttribute("className","t");v.innerHTML=" <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>";r=v.getElementsByTagName("*");i=v.getElementsByTagName("a")[0];if(!r||!r.length||!i){return{}}o=n.createElement("select");u=o.appendChild(n.createElement("option"));a=v.getElementsByTagName("input")[0];t={leadingWhitespace:v.firstChild.nodeType===3,tbody:!v.getElementsByTagName("tbody").length,htmlSerialize:!!v.getElementsByTagName("link").length,style:/top/.test(i.getAttribute("style")),hrefNormalized:i.getAttribute("href")==="/a",opacity:/^0.55/.test(i.style.opacity),cssFloat:!!i.style.cssFloat,checkOn:a.value==="on",optSelected:u.selected,getSetAttribute:v.className!=="t",enctype:!!n.createElement("form").enctype,html5Clone:n.createElement("nav").cloneNode(true).outerHTML!=="<:nav></:nav>",submitBubbles:true,changeBubbles:true,focusinBubbles:false,deleteExpando:true,noCloneEvent:true,inlineBlockNeedsLayout:false,shrinkWrapBlocks:false,reliableMarginRight:true,pixelMargin:true};s.boxModel=t.boxModel=n.compatMode==="CSS1Compat";a.checked=true;t.noCloneChecked=a.cloneNode(true).checked;o.disabled=true;t.optDisabled=!u.disabled;try{delete v.test}catch(g){t.deleteExpando=false}if(!v.addEventListener&&v.attachEvent&&v.fireEvent){v.attachEvent("onclick",function(){t.noCloneEvent=false});v.cloneNode(true).fireEvent("onclick")}a=n.createElement("input");a.value="t";a.setAttribute("type","radio");t.radioValue=a.value==="t";a.setAttribute("checked","checked");a.setAttribute("name","t");v.appendChild(a);f=n.createDocumentFragment();f.appendChild(v.lastChild);t.checkClone=f.cloneNode(true).cloneNode(true).lastChild.checked;t.appendChecked=a.checked;f.removeChild(a);f.appendChild(v);if(v.attachEvent){for(p in{submit:1,change:1,focusin:1}){h="on"+p;d=h in v;if(!d){v.setAttribute(h,"return;");d=typeof v[h]==="function"}t[p+"Bubbles"]=d}}f.removeChild(v);f=o=u=v=a=null;s(function(){var r,i,o,u,a,f,c,h,p,m,g,y,b,w=n.getElementsByTagName("body")[0];if(!w){return}h=1;b="padding:0;margin:0;border:";g="position:absolute;top:0;left:0;width:1px;height:1px;";y=b+"0;visibility:hidden;";p="style='"+g+b+"5px solid #000;";m="<div "+p+"display:block;'><div style='"+b+"0;display:block;overflow:hidden;'></div></div>"+"<table "+p+"' cellpadding='0' cellspacing='0'>"+"<tr><td></td></tr></table>";r=n.createElement("div");r.style.cssText=y+"width:0;height:0;position:static;top:0;margin-top:"+h+"px";w.insertBefore(r,w.firstChild);v=n.createElement("div");r.appendChild(v);v.innerHTML="<table><tr><td style='"+b+"0;display:none'></td><td>t</td></tr></table>";l=v.getElementsByTagName("td");d=l[0].offsetHeight===0;l[0].style.display="";l[1].style.display="none";t.reliableHiddenOffsets=d&&l[0].offsetHeight===0;if(e.getComputedStyle){v.innerHTML="";c=n.createElement("div");c.style.width="0";c.style.marginRight="0";v.style.width="2px";v.appendChild(c);t.reliableMarginRight=(parseInt((e.getComputedStyle(c,null)||{marginRight:0}).marginRight,10)||0)===0}if(typeof v.style.zoom!=="undefined"){v.innerHTML="";v.style.width=v.style.padding="1px";v.style.border=0;v.style.overflow="hidden";v.style.display="inline";v.style.zoom=1;t.inlineBlockNeedsLayout=v.offsetWidth===3;v.style.display="block";v.style.overflow="visible";v.innerHTML="<div style='width:5px;'></div>";t.shrinkWrapBlocks=v.offsetWidth!==3}v.style.cssText=g+y;v.innerHTML=m;i=v.firstChild;o=i.firstChild;a=i.nextSibling.firstChild.firstChild;f={doesNotAddBorder:o.offsetTop!==5,doesAddBorderForTableAndCells:a.offsetTop===5};o.style.position="fixed";o.style.top="20px";f.fixedPosition=o.offsetTop===20||o.offsetTop===15;o.style.position=o.style.top="";i.style.overflow="hidden";i.style.position="relative";f.subtractsBorderForOverflowNotVisible=o.offsetTop===-5;f.doesNotIncludeMarginInBodyOffset=w.offsetTop!==h;if(e.getComputedStyle){v.style.marginTop="1%";t.pixelMargin=(e.getComputedStyle(v,null)||{marginTop:0}).marginTop!=="1%"}if(typeof r.style.zoom!=="undefined"){r.style.zoom=1}w.removeChild(r);c=v=r=null;s.extend(t,f)});return t}();var f=/^(?:\{.*\}|\[.*\])$/,l=/([A-Z])/g;s.extend({cache:{},uuid:0,expando:"jQuery"+(s.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:true,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:true},hasData:function(e){e=e.nodeType?s.cache[e[s.expando]]:e[s.expando];return!!e&&!h(e)},data:function(e,n,r,i){if(!s.acceptData(e)){return}var o,u,a,f=s.expando,l=typeof n==="string",c=e.nodeType,h=c?s.cache:e,p=c?e[f]:e[f]&&f,d=n==="events";if((!p||!h[p]||!d&&!i&&!h[p].data)&&l&&r===t){return}if(!p){if(c){e[f]=p=++s.uuid}else{p=f}}if(!h[p]){h[p]={};if(!c){h[p].toJSON=s.noop}}if(typeof n==="object"||typeof n==="function"){if(i){h[p]=s.extend(h[p],n)}else{h[p].data=s.extend(h[p].data,n)}}o=u=h[p];if(!i){if(!u.data){u.data={}}u=u.data}if(r!==t){u[s.camelCase(n)]=r}if(d&&!u[n]){return o.events}if(l){a=u[n];if(a==null){a=u[s.camelCase(n)]}}else{a=u}return a},removeData:function(e,t,n){if(!s.acceptData(e)){return}var r,i,o,u=s.expando,a=e.nodeType,f=a?s.cache:e,l=a?e[u]:u;if(!f[l]){return}if(t){r=n?f[l]:f[l].data;if(r){if(!s.isArray(t)){if(t in r){t=[t]}else{t=s.camelCase(t);if(t in r){t=[t]}else{t=t.split(" ")}}}for(i=0,o=t.length;i<o;i++){delete r[t[i]]}if(!(n?h:s.isEmptyObject)(r)){return}}}if(!n){delete f[l].data;if(!h(f[l])){return}}if(s.support.deleteExpando||!f.setInterval){delete f[l]}else{f[l]=null}if(a){if(s.support.deleteExpando){delete e[u]}else if(e.removeAttribute){e.removeAttribute(u)}else{e[u]=null}}},_data:function(e,t,n){return s.data(e,t,n,true)},acceptData:function(e){if(e.nodeName){var t=s.noData[e.nodeName.toLowerCase()];if(t){return!(t===true||e.getAttribute("classid")!==t)}}return true}});s.fn.extend({data:function(e,n){var r,i,o,u,a,f=this[0],l=0,h=null;if(e===t){if(this.length){h=s.data(f);if(f.nodeType===1&&!s._data(f,"parsedAttrs")){o=f.attributes;for(a=o.length;l<a;l++){u=o[l].name;if(u.indexOf("data-")===0){u=s.camelCase(u.substring(5));c(f,u,h[u])}}s._data(f,"parsedAttrs",true)}}return h}if(typeof e==="object"){return this.each(function(){s.data(this,e)})}r=e.split(".",2);r[1]=r[1]?"."+r[1]:"";i=r[1]+"!";return s.access(this,function(n){if(n===t){h=this.triggerHandler("getData"+i,[r[0]]);if(h===t&&f){h=s.data(f,e);h=c(f,e,h)}return h===t&&r[1]?this.data(r[0]):h}r[1]=n;this.each(function(){var t=s(this);t.triggerHandler("setData"+i,r);s.data(this,e,n);t.triggerHandler("changeData"+i,r)})},null,n,arguments.length>1,null,false)},removeData:function(e){return this.each(function(){s.removeData(this,e)})}});s.extend({_mark:function(e,t){if(e){t=(t||"fx")+"mark";s._data(e,t,(s._data(e,t)||0)+1)}},_unmark:function(e,t,n){if(e!==true){n=t;t=e;e=false}if(t){n=n||"fx";var r=n+"mark",i=e?0:(s._data(t,r)||1)-1;if(i){s._data(t,r,i)}else{s.removeData(t,r,true);p(t,n,"mark")}}},queue:function(e,t,n){var r;if(e){t=(t||"fx")+"queue";r=s._data(e,t);if(n){if(!r||s.isArray(n)){r=s._data(e,t,s.makeArray(n))}else{r.push(n)}}return r||[]}},dequeue:function(e,t){t=t||"fx";var n=s.queue(e,t),r=n.shift(),i={};if(r==="inprogress"){r=n.shift()}if(r){if(t==="fx"){n.unshift("inprogress")}s._data(e,t+".run",i);r.call(e,function(){s.dequeue(e,t)},i)}if(!n.length){s.removeData(e,t+"queue "+t+".run",true);p(e,t,"queue")}}});s.fn.extend({queue:function(e,n){var r=2;if(typeof e!=="string"){n=e;e="fx";r--}if(arguments.length<r){return s.queue(this[0],e)}return n===t?this:this.each(function(){var t=s.queue(this,e,n);if(e==="fx"&&t[0]!=="inprogress"){s.dequeue(this,e)}})},dequeue:function(e){return this.each(function(){s.dequeue(this,e)})},delay:function(e,t){e=s.fx?s.fx.speeds[e]||e:e;t=t||"fx";return 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){function h(){if(!--u){r.resolveWith(i,[i])}}if(typeof e!=="string"){n=e;e=t}e=e||"fx";var r=s.Deferred(),i=this,o=i.length,u=1,a=e+"defer",f=e+"queue",l=e+"mark",c;while(o--){if(c=s.data(i[o],a,t,true)||(s.data(i[o],f,t,true)||s.data(i[o],l,t,true))&&s.data(i[o],a,s.Callbacks("once memory"),true)){u++;c.add(h)}}h();return r.promise(n)}});var d=/[\n\t\r]/g,v=/\s+/,m=/\r/g,g=/^(?:button|input)$/i,y=/^(?:button|input|object|select|textarea)$/i,b=/^a(?:rea)?$/i,w=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,E=s.support.getSetAttribute,S,x,T;s.fn.extend({attr:function(e,t){return s.access(this,s.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){s.removeAttr(this,e)})},prop:function(e,t){return s.access(this,s.prop,e,t,arguments.length>1)},removeProp:function(e){e=s.propFix[e]||e;return this.each(function(){try{this[e]=t;delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,o,u,a;if(s.isFunction(e)){return this.each(function(t){s(this).addClass(e.call(this,t,this.className))})}if(e&&typeof e==="string"){t=e.split(v);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{o=" "+i.className+" ";for(u=0,a=t.length;u<a;u++){if(!~o.indexOf(" "+t[u]+" ")){o+=t[u]+" "}}i.className=s.trim(o)}}}}return this},removeClass:function(e){var n,r,i,o,u,a,f;if(s.isFunction(e)){return this.each(function(t){s(this).removeClass(e.call(this,t,this.className))})}if(e&&typeof e==="string"||e===t){n=(e||"").split(v);for(r=0,i=this.length;r<i;r++){o=this[r];if(o.nodeType===1&&o.className){if(e){u=(" "+o.className+" ").replace(d," ");for(a=0,f=n.length;a<f;a++){u=u.replace(" "+n[a]+" "," ")}o.className=s.trim(u)}else{o.className=""}}}}return this},toggleClass:function(e,t){var n=typeof e,r=typeof t==="boolean";if(s.isFunction(e)){return this.each(function(n){s(this).toggleClass(e.call(this,n,this.className,t),t)})}return this.each(function(){if(n==="string"){var i,o=0,u=s(this),a=t,f=e.split(v);while(i=f[o++]){a=r?a:!u.hasClass(i);u[a?"addClass":"removeClass"](i)}}else if(n==="undefined"||n==="boolean"){if(this.className){s._data(this,"__className__",this.className)}this.className=this.className||e===false?"":s._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(d," ").indexOf(t)>-1){return true}}return false},val:function(e){var n,r,i,o=this[0];if(!arguments.length){if(o){n=s.valHooks[o.type]||s.valHooks[o.nodeName.toLowerCase()];if(n&&"get"in n&&(r=n.get(o,"value"))!==t){return r}r=o.value;return typeof r==="string"?r.replace(m,""):r==null?"":r}return}i=s.isFunction(e);return this.each(function(r){var o=s(this),u;if(this.nodeType!==1){return}if(i){u=e.call(this,r,o.val())}else{u=e}if(u==null){u=""}else if(typeof u==="number"){u+=""}else if(s.isArray(u)){u=s.map(u,function(e){return e==null?"":e+""})}n=s.valHooks[this.type]||s.valHooks[this.nodeName.toLowerCase()];if(!n||!("set"in n)||n.set(this,u,"value")===t){this.value=u}})}});s.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,o=e.selectedIndex,u=[],a=e.options,f=e.type==="select-one";if(o<0){return null}n=f?o:0;r=f?o+1:a.length;for(;n<r;n++){i=a[n];if(i.selected&&(s.support.optDisabled?!i.disabled:i.getAttribute("disabled")===null)&&(!i.parentNode.disabled||!s.nodeName(i.parentNode,"optgroup"))){t=s(i).val();if(f){return t}u.push(t)}}if(f&&!u.length&&a.length){return s(a[o]).val()}return u},set:function(e,t){var n=s.makeArray(t);s(e).find("option").each(function(){this.selected=s.inArray(s(this).val(),n)>=0});if(!n.length){e.selectedIndex=-1}return n}}},attrFn:{val:true,css:true,html:true,text:true,data:true,width:true,height:true,offset:true},attr:function(e,n,r,i){var o,u,a,f=e.nodeType;if(!e||f===3||f===8||f===2){return}if(i&&n in s.attrFn){return s(e)[n](r)}if(typeof e.getAttribute==="undefined"){return s.prop(e,n,r)}a=f!==1||!s.isXMLDoc(e);if(a){n=n.toLowerCase();u=s.attrHooks[n]||(w.test(n)?x:S)}if(r!==t){if(r===null){s.removeAttr(e,n);return}else if(u&&"set"in u&&a&&(o=u.set(e,r,n))!==t){return o}else{e.setAttribute(n,""+r);return r}}else if(u&&"get"in u&&a&&(o=u.get(e,n))!==null){return o}else{o=e.getAttribute(n);return o===null?t:o}},removeAttr:function(e,t){var n,r,i,o,u,a=0;if(t&&e.nodeType===1){r=t.toLowerCase().split(v);o=r.length;for(;a<o;a++){i=r[a];if(i){n=s.propFix[i]||i;u=w.test(i);if(!u){s.attr(e,i,"")}e.removeAttribute(E?i:n);if(u&&n in e){e[n]=false}}}}},attrHooks:{type:{set:function(e,t){if(g.test(e.nodeName)&&e.parentNode){s.error("type property can't be changed")}else if(!s.support.radioValue&&t==="radio"&&s.nodeName(e,"input")){var n=e.value;e.setAttribute("type",t);if(n){e.value=n}return t}}},value:{get:function(e,t){if(S&&s.nodeName(e,"button")){return S.get(e,t)}return t in e?e.value:null},set:function(e,t,n){if(S&&s.nodeName(e,"button")){return S.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,o,u,a=e.nodeType;if(!e||a===3||a===8||a===2){return}u=a!==1||!s.isXMLDoc(e);if(u){n=s.propFix[n]||n;o=s.propHooks[n]}if(r!==t){if(o&&"set"in o&&(i=o.set(e,r,n))!==t){return i}else{return e[n]=r}}else{if(o&&"get"in o&&(i=o.get(e,n))!==null){return i}else{return e[n]}}},propHooks:{tabIndex:{get:function(e){var n=e.getAttributeNode("tabindex");return n&&n.specified?parseInt(n.value,10):y.test(e.nodeName)||b.test(e.nodeName)&&e.href?0:t}}}});s.attrHooks.tabindex=s.propHooks.tabIndex;x={get:function(e,n){var r,i=s.prop(e,n);return i===true||typeof i!=="boolean"&&(r=e.getAttributeNode(n))&&r.nodeValue!==false?n.toLowerCase():t},set:function(e,t,n){var r;if(t===false){s.removeAttr(e,n)}else{r=s.propFix[n]||n;if(r in e){e[r]=true}e.setAttribute(n,n.toLowerCase())}return n}};if(!E){T={name:true,id:true,coords:true};S=s.valHooks.button={get:function(e,n){var r;r=e.getAttributeNode(n);return r&&(T[n]?r.nodeValue!=="":r.specified)?r.nodeValue:t},set:function(e,t,r){var i=e.getAttributeNode(r);if(!i){i=n.createAttribute(r);e.setAttributeNode(i)}return i.nodeValue=t+""}};s.attrHooks.tabindex.set=S.set;s.each(["width","height"],function(e,t){s.attrHooks[t]=s.extend(s.attrHooks[t],{set:function(e,n){if(n===""){e.setAttribute(t,"auto");return n}}})});s.attrHooks.contenteditable={get:S.get,set:function(e,t,n){if(t===""){t="false"}S.set(e,t,n)}}}if(!s.support.hrefNormalized){s.each(["href","src","width","height"],function(e,n){s.attrHooks[n]=s.extend(s.attrHooks[n],{get:function(e){var r=e.getAttribute(n,2);return r===null?t:r}})})}if(!s.support.style){s.attrHooks.style={get:function(e){return e.style.cssText.toLowerCase()||t},set:function(e,t){return e.style.cssText=""+t}}}if(!s.support.optSelected){s.propHooks.selected=s.extend(s.propHooks.selected,{get:function(e){var t=e.parentNode;if(t){t.selectedIndex;if(t.parentNode){t.parentNode.selectedIndex}}return null}})}if(!s.support.enctype){s.propFix.enctype="encoding"}if(!s.support.checkOn){s.each(["radio","checkbox"],function(){s.valHooks[this]={get:function(e){return e.getAttribute("value")===null?"on":e.value}}})}s.each(["radio","checkbox"],function(){s.valHooks[this]=s.extend(s.valHooks[this],{set:function(e,t){if(s.isArray(t)){return e.checked=s.inArray(s(e).val(),t)>=0}}})});var N=/^(?:textarea|input|select)$/i,C=/^([^\.]*)?(?:\.(.+))?$/,k=/(?:^|\s)hover(\.\S+)?\b/,L=/^key/,A=/^(?:mouse|contextmenu)|click/,O=/^(?:focusinfocus|focusoutblur)$/,M=/^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,_=function(e){var t=M.exec(e);if(t){t[1]=(t[1]||"").toLowerCase();t[3]=t[3]&&new RegExp("(?:^|\\s)"+t[3]+"(?:\\s|$)")}return t},D=function(e,t){var n=e.attributes||{};return(!t[1]||e.nodeName.toLowerCase()===t[1])&&(!t[2]||(n.id||{}).value===t[2])&&(!t[3]||t[3].test((n["class"]||{}).value))},P=function(e){return s.event.special.hover?e:e.replace(k,"mouseenter$1 mouseleave$1")};s.event={add:function(e,n,r,i,o){var u,a,f,l,c,h,p,d,v,m,g,y;if(e.nodeType===3||e.nodeType===8||!n||!r||!(u=s._data(e))){return}if(r.handler){v=r;r=v.handler;o=v.selector}if(!r.guid){r.guid=s.guid++}f=u.events;if(!f){u.events=f={}}a=u.handle;if(!a){u.handle=a=function(e){return typeof s!=="undefined"&&(!e||s.event.triggered!==e.type)?s.event.dispatch.apply(a.elem,arguments):t};a.elem=e}n=s.trim(P(n)).split(" ");for(l=0;l<n.length;l++){c=C.exec(n[l])||[];h=c[1];p=(c[2]||"").split(".").sort();y=s.event.special[h]||{};h=(o?y.delegateType:y.bindType)||h;y=s.event.special[h]||{};d=s.extend({type:h,origType:c[1],data:i,handler:r,guid:r.guid,selector:o,quick:o&&_(o),namespace:p.join(".")},v);g=f[h];if(!g){g=f[h]=[];g.delegateCount=0;if(!y.setup||y.setup.call(e,i,p,a)===false){if(e.addEventListener){e.addEventListener(h,a,false)}else if(e.attachEvent){e.attachEvent("on"+h,a)}}}if(y.add){y.add.call(e,d);if(!d.handler.guid){d.handler.guid=r.guid}}if(o){g.splice(g.delegateCount++,0,d)}else{g.push(d)}s.event.global[h]=true}e=null},global:{},remove:function(e,t,n,r,i){var o=s.hasData(e)&&s._data(e),u,a,f,l,c,h,p,d,v,m,g,y;if(!o||!(d=o.events)){return}t=s.trim(P(t||"")).split(" ");for(u=0;u<t.length;u++){a=C.exec(t[u])||[];f=l=a[1];c=a[2];if(!f){for(f in d){s.event.remove(e,f+t[u],n,r,true)}continue}v=s.event.special[f]||{};f=(r?v.delegateType:v.bindType)||f;g=d[f]||[];h=g.length;c=c?new RegExp("(^|\\.)"+c.split(".").sort().join("\\.(?:.*\\.)?")+"(\\.|$)"):null;for(p=0;p<g.length;p++){y=g[p];if((i||l===y.origType)&&(!n||n.guid===y.guid)&&(!c||c.test(y.namespace))&&(!r||r===y.selector||r==="**"&&y.selector)){g.splice(p--,1);if(y.selector){g.delegateCount--}if(v.remove){v.remove.call(e,y)}}}if(g.length===0&&h!==g.length){if(!v.teardown||v.teardown.call(e,c)===false){s.removeEvent(e,f,o.handle)}delete d[f]}}if(s.isEmptyObject(d)){m=o.handle;if(m){m.elem=null}s.removeData(e,["events","handle"],true)}},customEvent:{getData:true,setData:true,changeData:true},trigger:function(n,r,i,o){if(i&&(i.nodeType===3||i.nodeType===8)){return}var u=n.type||n,a=[],f,l,c,h,p,d,v,m,g,y;if(O.test(u+s.event.triggered)){return}if(u.indexOf("!")>=0){u=u.slice(0,-1);l=true}if(u.indexOf(".")>=0){a=u.split(".");u=a.shift();a.sort()}if((!i||s.event.customEvent[u])&&!s.event.global[u]){return}n=typeof n==="object"?n[s.expando]?n:new s.Event(u,n):new s.Event(u);n.type=u;n.isTrigger=true;n.exclusive=l;n.namespace=a.join(".");n.namespace_re=n.namespace?new RegExp("(^|\\.)"+a.join("\\.(?:.*\\.)?")+"(\\.|$)"):null;d=u.indexOf(":")<0?"on"+u:"";if(!i){f=s.cache;for(c in f){if(f[c].events&&f[c].events[u]){s.event.trigger(n,r,f[c].handle.elem,true)}}return}n.result=t;if(!n.target){n.target=i}r=r!=null?s.makeArray(r):[];r.unshift(n);v=s.event.special[u]||{};if(v.trigger&&v.trigger.apply(i,r)===false){return}g=[[i,v.bindType||u]];if(!o&&!v.noBubble&&!s.isWindow(i)){y=v.delegateType||u;h=O.test(y+u)?i:i.parentNode;p=null;for(;h;h=h.parentNode){g.push([h,y]);p=h}if(p&&p===i.ownerDocument){g.push([p.defaultView||p.parentWindow||e,y])}}for(c=0;c<g.length&&!n.isPropagationStopped();c++){h=g[c][0];n.type=g[c][1];m=(s._data(h,"events")||{})[n.type]&&s._data(h,"handle");if(m){m.apply(h,r)}m=d&&h[d];if(m&&s.acceptData(h)&&m.apply(h,r)===false){n.preventDefault()}}n.type=u;if(!o&&!n.isDefaultPrevented()){if((!v._default||v._default.apply(i.ownerDocument,r)===false)&&!(u==="click"&&s.nodeName(i,"a"))&&s.acceptData(i)){if(d&&i[u]&&(u!=="focus"&&u!=="blur"||n.target.offsetWidth!==0)&&!s.isWindow(i)){p=i[d];if(p){i[d]=null}s.event.triggered=u;i[u]();s.event.triggered=t;if(p){i[d]=p}}}}return n.result},dispatch:function(n){n=s.event.fix(n||e.event);var r=(s._data(this,"events")||{})[n.type]||[],i=r.delegateCount,o=[].slice.call(arguments,0),u=!n.exclusive&&!n.namespace,a=s.event.special[n.type]||{},f=[],l,c,h,p,d,v,m,g,y,b,w;o[0]=n;n.delegateTarget=this;if(a.preDispatch&&a.preDispatch.call(this,n)===false){return}if(i&&!(n.button&&n.type==="click")){p=s(this);p.context=this.ownerDocument||this;for(h=n.target;h!=this;h=h.parentNode||this){if(h.disabled!==true){v={};g=[];p[0]=h;for(l=0;l<i;l++){y=r[l];b=y.selector;if(v[b]===t){v[b]=y.quick?D(h,y.quick):p.is(b)}if(v[b]){g.push(y)}}if(g.length){f.push({elem:h,matches:g})}}}}if(r.length>i){f.push({elem:this,matches:r.slice(i)})}for(l=0;l<f.length&&!n.isPropagationStopped();l++){m=f[l];n.currentTarget=m.elem;for(c=0;c<m.matches.length&&!n.isImmediatePropagationStopped();c++){y=m.matches[c];if(u||!n.namespace&&!y.namespace||n.namespace_re&&n.namespace_re.test(y.namespace)){n.data=y.data;n.handleObj=y;d=((s.event.special[y.origType]||{}).handle||y.handler).apply(m.elem,o);if(d!==t){n.result=d;if(d===false){n.preventDefault();n.stopPropagation()}}}}}if(a.postDispatch){a.postDispatch.call(this,n)}return 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){if(e.which==null){e.which=t.charCode!=null?t.charCode:t.keyCode}return e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,r){var i,s,o,u=r.button,a=r.fromElement;if(e.pageX==null&&r.clientX!=null){i=e.target.ownerDocument||n;s=i.documentElement;o=i.body;e.pageX=r.clientX+(s&&s.scrollLeft||o&&o.scrollLeft||0)-(s&&s.clientLeft||o&&o.clientLeft||0);e.pageY=r.clientY+(s&&s.scrollTop||o&&o.scrollTop||0)-(s&&s.clientTop||o&&o.clientTop||0)}if(!e.relatedTarget&&a){e.relatedTarget=a===e.target?r.toElement:a}if(!e.which&&u!==t){e.which=u&1?1:u&2?3:u&4?2:0}return e}},fix:function(e){if(e[s.expando]){return e}var r,i,o=e,u=s.event.fixHooks[e.type]||{},a=u.props?this.props.concat(u.props):this.props;e=s.Event(o);for(r=a.length;r;){i=a[--r];e[i]=o[i]}if(!e.target){e.target=o.srcElement||n}if(e.target.nodeType===3){e.target=e.target.parentNode}if(e.metaKey===t){e.metaKey=e.ctrlKey}return u.filter?u.filter(e,o):e},special:{ready:{setup:s.bindReady},load:{noBubble:true},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(e,t,n){if(s.isWindow(this)){this.onbeforeunload=n}},teardown:function(e,t){if(this.onbeforeunload===t){this.onbeforeunload=null}}}},simulate:function(e,t,n,r){var i=s.extend(new s.Event,n,{type:e,isSimulated:true,originalEvent:{}});if(r){s.event.trigger(i,null,t)}else{s.event.dispatch.call(t,i)}if(i.isDefaultPrevented()){n.preventDefault()}}};s.event.handle=s.event.dispatch;s.removeEvent=n.removeEventListener?function(e,t,n){if(e.removeEventListener){e.removeEventListener(t,n,false)}}:function(e,t,n){if(e.detachEvent){e.detachEvent("on"+t,n)}};s.Event=function(e,t){if(!(this instanceof s.Event)){return new s.Event(e,t)}if(e&&e.type){this.originalEvent=e;this.type=e.type;this.isDefaultPrevented=e.defaultPrevented||e.returnValue===false||e.getPreventDefault&&e.defaultPrevented?B:H}else{this.type=e}if(t){s.extend(this,t)}this.timeStamp=e&&e.timeStamp||s.now();this[s.expando]=true};s.Event.prototype={preventDefault:function(){this.isDefaultPrevented=B;var e=this.originalEvent;if(!e){return}if(e.preventDefault){e.preventDefault()}else{e.returnValue=false}},stopPropagation:function(){this.isPropagationStopped=B;var e=this.originalEvent;if(!e){return}if(e.stopPropagation){e.stopPropagation()}e.cancelBubble=true},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=B;this.stopPropagation()},isDefaultPrevented:H,isPropagationStopped:H,isImmediatePropagationStopped:H};s.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){s.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n=this,r=e.relatedTarget,i=e.handleObj,o=i.selector,u;if(!r||r!==n&&!s.contains(n,r)){e.type=i.origType;u=i.handler.apply(this,arguments);e.type=t}return u}}});if(!s.support.submitBubbles){s.event.special.submit={setup:function(){if(s.nodeName(this,"form")){return false}s.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=s.nodeName(n,"input")||s.nodeName(n,"button")?n.form:t;if(r&&!r._submit_attached){s.event.add(r,"submit._submit",function(e){e._submit_bubble=true});r._submit_attached=true}})},postDispatch:function(e){if(e._submit_bubble){delete e._submit_bubble;if(this.parentNode&&!e.isTrigger){s.event.simulate("submit",this.parentNode,e,true)}}},teardown:function(){if(s.nodeName(this,"form")){return false}s.event.remove(this,"._submit")}}}if(!s.support.changeBubbles){s.event.special.change={setup:function(){if(N.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio"){s.event.add(this,"propertychange._change",function(e){if(e.originalEvent.propertyName==="checked"){this._just_changed=true}});s.event.add(this,"click._change",function(e){if(this._just_changed&&!e.isTrigger){this._just_changed=false;s.event.simulate("change",this,e,true)}})}return false}s.event.add(this,"beforeactivate._change",function(e){var t=e.target;if(N.test(t.nodeName)&&!t._change_attached){s.event.add(t,"change._change",function(e){if(this.parentNode&&!e.isSimulated&&!e.isTrigger){s.event.simulate("change",this.parentNode,e,true)}});t._change_attached=true}})},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(){s.event.remove(this,"._change");return N.test(this.nodeName)}}}if(!s.support.focusinBubbles){s.each({focus:"focusin",blur:"focusout"},function(e,t){var r=0,i=function(e){s.event.simulate(t,e.target,s.event.fix(e),true)};s.event.special[t]={setup:function(){if(r++===0){n.addEventListener(e,i,true)}},teardown:function(){if(--r===0){n.removeEventListener(e,i,true)}}}})}s.fn.extend({on:function(e,n,r,i,o){var u,a;if(typeof e==="object"){if(typeof n!=="string"){r=r||n;n=t}for(a in e){this.on(a,n,r,e[a],o)}return this}if(r==null&&i==null){i=n;r=n=t}else if(i==null){if(typeof n==="string"){i=r;r=t}else{i=r;r=n;n=t}}if(i===false){i=H}else if(!i){return this}if(o===1){u=i;i=function(e){s().off(e);return u.apply(this,arguments)};i.guid=u.guid||(u.guid=s.guid++)}return this.each(function(){s.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){if(e&&e.preventDefault&&e.handleObj){var i=e.handleObj;s(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler);return this}if(typeof e==="object"){for(var o in e){this.off(o,n,e[o])}return this}if(n===false||typeof n==="function"){r=n;n=t}if(r===false){r=H}return this.each(function(){s.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){s(this.context).on(e,this.selector,t,n);return this},die:function(e,t){s(this.context).off(e,this.selector||"**",t);return 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(){s.event.trigger(e,t,this)})},triggerHandler:function(e,t){if(this[0]){return s.event.trigger(e,t,this[0],true)}},toggle:function(e){var t=arguments,n=e.guid||s.guid++,r=0,i=function(n){var i=(s._data(this,"lastToggle"+e.guid)||0)%r;s._data(this,"lastToggle"+e.guid,i+1);n.preventDefault();return t[i].apply(this,arguments)||false};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)}});s.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){s.fn[t]=function(e,n){if(n==null){n=e;e=null}return arguments.length>0?this.on(t,null,e,n):this.trigger(t)};if(s.attrFn){s.attrFn[t]=true}if(L.test(t)){s.event.fixHooks[t]=s.event.keyHooks}if(A.test(t)){s.event.fixHooks[t]=s.event.mouseHooks}});(function(){function S(e,t,n,i,s,o){for(var u=0,a=i.length;u<a;u++){var f=i[u];if(f){var l=false;f=f[e];while(f){if(f[r]===n){l=i[f.sizset];break}if(f.nodeType===1&&!o){f[r]=n;f.sizset=u}if(f.nodeName.toLowerCase()===t){l=f;break}f=f[e]}i[u]=l}}}function x(e,t,n,i,s,o){for(var u=0,a=i.length;u<a;u++){var f=i[u];if(f){var l=false;f=f[e];while(f){if(f[r]===n){l=i[f.sizset];break}if(f.nodeType===1){if(!o){f[r]=n;f.sizset=u}if(typeof t!=="string"){if(f===t){l=true;break}}else if(h.filter(t,[f]).length>0){l=f;break}}f=f[e]}i[u]=l}}}var e=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,r="sizcache"+(Math.random()+"").replace(".",""),i=0,o=Object.prototype.toString,u=false,a=true,f=/\\/g,l=/\r\n/g,c=/\W/;[0,0].sort(function(){a=false;return 0});var h=function(t,r,i,s){i=i||[];r=r||n;var u=r;if(r.nodeType!==1&&r.nodeType!==9){return[]}if(!t||typeof t!=="string"){return i}var a,f,l,c,p,m,g,b,w=true,E=h.isXML(r),S=[],x=t;do{e.exec("");a=e.exec(x);if(a){x=a[3];S.push(a[1]);if(a[2]){c=a[3];break}}}while(a);if(S.length>1&&v.exec(t)){if(S.length===2&&d.relative[S[0]]){f=T(S[0]+S[1],r,s)}else{f=d.relative[S[0]]?[r]:h(S.shift(),r);while(S.length){t=S.shift();if(d.relative[t]){t+=S.shift()}f=T(t,f,s)}}}else{if(!s&&S.length>1&&r.nodeType===9&&!E&&d.match.ID.test(S[0])&&!d.match.ID.test(S[S.length-1])){p=h.find(S.shift(),r,E);r=p.expr?h.filter(p.expr,p.set)[0]:p.set[0]}if(r){p=s?{expr:S.pop(),set:y(s)}:h.find(S.pop(),S.length===1&&(S[0]==="~"||S[0]==="+")&&r.parentNode?r.parentNode:r,E);f=p.expr?h.filter(p.expr,p.set):p.set;if(S.length>0){l=y(f)}else{w=false}while(S.length){m=S.pop();g=m;if(!d.relative[m]){m=""}else{g=S.pop()}if(g==null){g=r}d.relative[m](l,g,E)}}else{l=S=[]}}if(!l){l=f}if(!l){h.error(m||t)}if(o.call(l)==="[object Array]"){if(!w){i.push.apply(i,l)}else if(r&&r.nodeType===1){for(b=0;l[b]!=null;b++){if(l[b]&&(l[b]===true||l[b].nodeType===1&&h.contains(r,l[b]))){i.push(f[b])}}}else{for(b=0;l[b]!=null;b++){if(l[b]&&l[b].nodeType===1){i.push(f[b])}}}}else{y(l,i)}if(c){h(c,u,i,s);h.uniqueSort(i)}return i};h.uniqueSort=function(e){if(w){u=a;e.sort(w);if(u){for(var t=1;t<e.length;t++){if(e[t]===e[t-1]){e.splice(t--,1)}}}}return e};h.matches=function(e,t){return h(e,null,null,t)};h.matchesSelector=function(e,t){return h(t,null,null,[e]).length>0};h.find=function(e,t,n){var r,i,s,o,u,a;if(!e){return[]}for(i=0,s=d.order.length;i<s;i++){u=d.order[i];if(o=d.leftMatch[u].exec(e)){a=o[1];o.splice(1,1);if(a.substr(a.length-1)!=="\\"){o[1]=(o[1]||"").replace(f,"");r=d.find[u](o,t,n);if(r!=null){e=e.replace(d.match[u],"");break}}}}if(!r){r=typeof t.getElementsByTagName!=="undefined"?t.getElementsByTagName("*"):[]}return{set:r,expr:e}};h.filter=function(e,n,r,i){var s,o,u,a,f,l,c,p,v,m=e,g=[],y=n,b=n&&n[0]&&h.isXML(n[0]);while(e&&n.length){for(u in d.filter){if((s=d.leftMatch[u].exec(e))!=null&&s[2]){l=d.filter[u];c=s[1];o=false;s.splice(1,1);if(c.substr(c.length-1)==="\\"){continue}if(y===g){g=[]}if(d.preFilter[u]){s=d.preFilter[u](s,y,r,g,i,b);if(!s){o=a=true}else if(s===true){continue}}if(s){for(p=0;(f=y[p])!=null;p++){if(f){a=l(f,s,p,y);v=i^a;if(r&&a!=null){if(v){o=true}else{y[p]=false}}else if(v){g.push(f);o=true}}}}if(a!==t){if(!r){y=g}e=e.replace(d.match[u],"");if(!o){return[]}break}}}if(e===m){if(o==null){h.error(e)}else{break}}m=e}return y};h.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)};var p=h.getText=function(e){var t,n,r=e.nodeType,i="";if(r){if(r===1||r===9||r===11){if(typeof e.textContent==="string"){return e.textContent}else if(typeof e.innerText==="string"){return e.innerText.replace(l,"")}else{for(e=e.firstChild;e;e=e.nextSibling){i+=p(e)}}}else if(r===3||r===4){return e.nodeValue}}else{for(t=0;n=e[t];t++){if(n.nodeType!==8){i+=p(n)}}}return i};var d=h.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(e){return e.getAttribute("href")},type:function(e){return e.getAttribute("type")}},relative:{"+":function(e,t){var n=typeof t==="string",r=n&&!c.test(t),i=n&&!r;if(r){t=t.toLowerCase()}for(var s=0,o=e.length,u;s<o;s++){if(u=e[s]){while((u=u.previousSibling)&&u.nodeType!==1){}e[s]=i||u&&u.nodeName.toLowerCase()===t?u||false:u===t}}if(i){h.filter(t,e,true)}},">":function(e,t){var n,r=typeof t==="string",i=0,s=e.length;if(r&&!c.test(t)){t=t.toLowerCase();for(;i<s;i++){n=e[i];if(n){var o=n.parentNode;e[i]=o.nodeName.toLowerCase()===t?o:false}}}else{for(;i<s;i++){n=e[i];if(n){e[i]=r?n.parentNode:n.parentNode===t}}if(r){h.filter(t,e,true)}}},"":function(e,t,n){var r,s=i++,o=x;if(typeof t==="string"&&!c.test(t)){t=t.toLowerCase();r=t;o=S}o("parentNode",t,s,e,r,n)},"~":function(e,t,n){var r,s=i++,o=x;if(typeof t==="string"&&!c.test(t)){t=t.toLowerCase();r=t;o=S}o("previousSibling",t,s,e,r,n)}},find:{ID:function(e,t,n){if(typeof t.getElementById!=="undefined"&&!n){var r=t.getElementById(e[1]);return r&&r.parentNode?[r]:[]}},NAME:function(e,t){if(typeof t.getElementsByName!=="undefined"){var n=[],r=t.getElementsByName(e[1]);for(var i=0,s=r.length;i<s;i++){if(r[i].getAttribute("name")===e[1]){n.push(r[i])}}return n.length===0?null:n}},TAG:function(e,t){if(typeof t.getElementsByTagName!=="undefined"){return t.getElementsByTagName(e[1])}}},preFilter:{CLASS:function(e,t,n,r,i,s){e=" "+e[1].replace(f,"")+" ";if(s){return e}for(var o=0,u;(u=t[o])!=null;o++){if(u){if(i^(u.className&&(" "+u.className+" ").replace(/[\t\n\r]/g," ").indexOf(e)>=0)){if(!n){r.push(u)}}else if(n){t[o]=false}}}return false},ID:function(e){return e[1].replace(f,"")},TAG:function(e,t){return e[1].replace(f,"").toLowerCase()},CHILD:function(e){if(e[1]==="nth"){if(!e[2]){h.error(e[0])}e[2]=e[2].replace(/^\+|\s*/g,"");var t=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(e[2]==="even"&&"2n"||e[2]==="odd"&&"2n+1"||!/\D/.test(e[2])&&"0n+"+e[2]||e[2]);e[2]=t[1]+(t[2]||1)-0;e[3]=t[3]-0}else if(e[2]){h.error(e[0])}e[0]=i++;return e},ATTR:function(e,t,n,r,i,s){var o=e[1]=e[1].replace(f,"");if(!s&&d.attrMap[o]){e[1]=d.attrMap[o]}e[4]=(e[4]||e[5]||"").replace(f,"");if(e[2]==="~="){e[4]=" "+e[4]+" "}return e},PSEUDO:function(t,n,r,i,s){if(t[1]==="not"){if((e.exec(t[3])||"").length>1||/^\w/.test(t[3])){t[3]=h(t[3],null,null,n)}else{var o=h.filter(t[3],n,r,true^s);if(!r){i.push.apply(i,o)}return false}}else if(d.match.POS.test(t[0])||d.match.CHILD.test(t[0])){return true}return t},POS:function(e){e.unshift(true);return e}},filters:{enabled:function(e){return e.disabled===false&&e.type!=="hidden"},disabled:function(e){return e.disabled===true},checked:function(e){return e.checked===true},selected:function(e){if(e.parentNode){e.parentNode.selectedIndex}return e.selected===true},parent:function(e){return!!e.firstChild},empty:function(e){return!e.firstChild},has:function(e,t,n){return!!h(n[3],e).length},header:function(e){return/h\d/i.test(e.nodeName)},text:function(e){var t=e.getAttribute("type"),n=e.type;return e.nodeName.toLowerCase()==="input"&&"text"===n&&(t===n||t===null)},radio:function(e){return e.nodeName.toLowerCase()==="input"&&"radio"===e.type},checkbox:function(e){return e.nodeName.toLowerCase()==="input"&&"checkbox"===e.type},file:function(e){return e.nodeName.toLowerCase()==="input"&&"file"===e.type},password:function(e){return e.nodeName.toLowerCase()==="input"&&"password"===e.type},submit:function(e){var t=e.nodeName.toLowerCase();return(t==="input"||t==="button")&&"submit"===e.type},image:function(e){return e.nodeName.toLowerCase()==="input"&&"image"===e.type},reset:function(e){var t=e.nodeName.toLowerCase();return(t==="input"||t==="button")&&"reset"===e.type},button:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&"button"===e.type||t==="button"},input:function(e){return/input|select|textarea|button/i.test(e.nodeName)},focus:function(e){return e===e.ownerDocument.activeElement}},setFilters:{first:function(e,t){return t===0},last:function(e,t,n,r){return t===r.length-1},even:function(e,t){return t%2===0},odd:function(e,t){return t%2===1},lt:function(e,t,n){return t<n[3]-0},gt:function(e,t,n){return t>n[3]-0},nth:function(e,t,n){return n[3]-0===t},eq:function(e,t,n){return n[3]-0===t}},filter:{PSEUDO:function(e,t,n,r){var i=t[1],s=d.filters[i];if(s){return s(e,n,t,r)}else if(i==="contains"){return(e.textContent||e.innerText||p([e])||"").indexOf(t[3])>=0}else if(i==="not"){var o=t[3];for(var u=0,a=o.length;u<a;u++){if(o[u]===e){return false}}return true}else{h.error(i)}},CHILD:function(e,t){var n,i,s,o,u,a,f,l=t[1],c=e;switch(l){case"only":case"first":while(c=c.previousSibling){if(c.nodeType===1){return false}}if(l==="first"){return true}c=e;case"last":while(c=c.nextSibling){if(c.nodeType===1){return false}}return true;case"nth":n=t[2];i=t[3];if(n===1&&i===0){return true}s=t[0];o=e.parentNode;if(o&&(o[r]!==s||!e.nodeIndex)){a=0;for(c=o.firstChild;c;c=c.nextSibling){if(c.nodeType===1){c.nodeIndex=++a}}o[r]=s}f=e.nodeIndex-i;if(n===0){return f===0}else{return f%n===0&&f/n>=0}}},ID:function(e,t){return e.nodeType===1&&e.getAttribute("id")===t},TAG:function(e,t){return t==="*"&&e.nodeType===1||!!e.nodeName&&e.nodeName.toLowerCase()===t},CLASS:function(e,t){return(" "+(e.className||e.getAttribute("class"))+" ").indexOf(t)>-1},ATTR:function(e,t){var n=t[1],r=h.attr?h.attr(e,n):d.attrHandle[n]?d.attrHandle[n](e):e[n]!=null?e[n]:e.getAttribute(n),i=r+"",s=t[2],o=t[4];return r==null?s==="!=":!s&&h.attr?r!=null:s==="="?i===o:s==="*="?i.indexOf(o)>=0:s==="~="?(" "+i+" ").indexOf(o)>=0:!o?i&&r!==false:s==="!="?i!==o:s==="^="?i.indexOf(o)===0:s==="$="?i.substr(i.length-o.length)===o:s==="|="?i===o||i.substr(0,o.length+1)===o+"-":false},POS:function(e,t,n,r){var i=t[2],s=d.setFilters[i];if(s){return s(e,n,t,r)}}}};var v=d.match.POS,m=function(e,t){return"\\"+(t-0+1)};for(var g in d.match){d.match[g]=new RegExp(d.match[g].source+/(?![^\[]*\])(?![^\(]*\))/.source);d.leftMatch[g]=new RegExp(/(^(?:.|\r|\n)*?)/.source+d.match[g].source.replace(/\\(\d+)/g,m))}d.match.globalPOS=v;var y=function(e,t){e=Array.prototype.slice.call(e,0);if(t){t.push.apply(t,e);return t}return e};try{Array.prototype.slice.call(n.documentElement.childNodes,0)[0].nodeType}catch(b){y=function(e,t){var n=0,r=t||[];if(o.call(e)==="[object Array]"){Array.prototype.push.apply(r,e)}else{if(typeof e.length==="number"){for(var i=e.length;n<i;n++){r.push(e[n])}}else{for(;e[n];n++){r.push(e[n])}}}return r}}var w,E;if(n.documentElement.compareDocumentPosition){w=function(e,t){if(e===t){u=true;return 0}if(!e.compareDocumentPosition||!t.compareDocumentPosition){return e.compareDocumentPosition?-1:1}return e.compareDocumentPosition(t)&4?-1:1}}else{w=function(e,t){if(e===t){u=true;return 0}else if(e.sourceIndex&&t.sourceIndex){return e.sourceIndex-t.sourceIndex}var n,r,i=[],s=[],o=e.parentNode,a=t.parentNode,f=o;if(o===a){return E(e,t)}else if(!o){return-1}else if(!a){return 1}while(f){i.unshift(f);f=f.parentNode}f=a;while(f){s.unshift(f);f=f.parentNode}n=i.length;r=s.length;for(var l=0;l<n&&l<r;l++){if(i[l]!==s[l]){return E(i[l],s[l])}}return l===n?E(e,s[l],-1):E(i[l],t,1)};E=function(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(){var e=n.createElement("div"),r="script"+(new Date).getTime(),i=n.documentElement;e.innerHTML="<a name='"+r+"'/>";i.insertBefore(e,i.firstChild);if(n.getElementById(r)){d.find.ID=function(e,n,r){if(typeof n.getElementById!=="undefined"&&!r){var i=n.getElementById(e[1]);return i?i.id===e[1]||typeof i.getAttributeNode!=="undefined"&&i.getAttributeNode("id").nodeValue===e[1]?[i]:t:[]}};d.filter.ID=function(e,t){var n=typeof e.getAttributeNode!=="undefined"&&e.getAttributeNode("id");return e.nodeType===1&&n&&n.nodeValue===t}}i.removeChild(e);i=e=null})();(function(){var e=n.createElement("div");e.appendChild(n.createComment(""));if(e.getElementsByTagName("*").length>0){d.find.TAG=function(e,t){var n=t.getElementsByTagName(e[1]);if(e[1]==="*"){var r=[];for(var i=0;n[i];i++){if(n[i].nodeType===1){r.push(n[i])}}n=r}return n}}e.innerHTML="<a href='#'></a>";if(e.firstChild&&typeof e.firstChild.getAttribute!=="undefined"&&e.firstChild.getAttribute("href")!=="#"){d.attrHandle.href=function(e){return e.getAttribute("href",2)}}e=null})();if(n.querySelectorAll){(function(){var e=h,t=n.createElement("div"),r="__sizzle__";t.innerHTML="<p class='TEST'></p>";if(t.querySelectorAll&&t.querySelectorAll(".TEST").length===0){return}h=function(t,i,s,o){i=i||n;if(!o&&!h.isXML(i)){var u=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(t);if(u&&(i.nodeType===1||i.nodeType===9)){if(u[1]){return y(i.getElementsByTagName(t),s)}else if(u[2]&&d.find.CLASS&&i.getElementsByClassName){return y(i.getElementsByClassName(u[2]),s)}}if(i.nodeType===9){if(t==="body"&&i.body){return y([i.body],s)}else if(u&&u[3]){var a=i.getElementById(u[3]);if(a&&a.parentNode){if(a.id===u[3]){return y([a],s)}}else{return y([],s)}}try{return y(i.querySelectorAll(t),s)}catch(f){}}else if(i.nodeType===1&&i.nodeName.toLowerCase()!=="object"){var l=i,c=i.getAttribute("id"),p=c||r,v=i.parentNode,m=/^\s*[+~]/.test(t);if(!c){i.setAttribute("id",p)}else{p=p.replace(/'/g,"\\$&")}if(m&&v){i=i.parentNode}try{if(!m||v){return y(i.querySelectorAll("[id='"+p+"'] "+t),s)}}catch(g){}finally{if(!c){l.removeAttribute("id")}}}}return e(t,i,s,o)};for(var i in e){h[i]=e[i]}t=null})()}(function(){var e=n.documentElement,t=e.matchesSelector||e.mozMatchesSelector||e.webkitMatchesSelector||e.msMatchesSelector;if(t){var r=!t.call(n.createElement("div"),"div"),i=false;try{t.call(n.documentElement,"[test!='']:sizzle")}catch(s){i=true}h.matchesSelector=function(e,n){n=n.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!h.isXML(e)){try{if(i||!d.match.PSEUDO.test(n)&&!/!=/.test(n)){var s=t.call(e,n);if(s||!r||e.document&&e.document.nodeType!==11){return s}}}catch(o){}}return h(n,null,null,[e]).length>0}}})();(function(){var e=n.createElement("div");e.innerHTML="<div class='test e'></div><div class='test'></div>";if(!e.getElementsByClassName||e.getElementsByClassName("e").length===0){return}e.lastChild.className="e";if(e.getElementsByClassName("e").length===1){return}d.order.splice(1,0,"CLASS");d.find.CLASS=function(e,t,n){if(typeof t.getElementsByClassName!=="undefined"&&!n){return t.getElementsByClassName(e[1])}};e=null})();if(n.documentElement.contains){h.contains=function(e,t){return e!==t&&(e.contains?e.contains(t):true)}}else if(n.documentElement.compareDocumentPosition){h.contains=function(e,t){return!!(e.compareDocumentPosition(t)&16)}}else{h.contains=function(){return false}}h.isXML=function(e){var t=(e?e.ownerDocument||e:0).documentElement;return t?t.nodeName!=="HTML":false};var T=function(e,t,n){var r,i=[],s="",o=t.nodeType?[t]:t;while(r=d.match.PSEUDO.exec(e)){s+=r[0];e=e.replace(d.match.PSEUDO,"")}e=d.relative[e]?e+"*":e;for(var u=0,a=o.length;u<a;u++){h(e,o[u],i,n)}return h.filter(s,i)};h.attr=s.attr;h.selectors.attrMap={};s.find=h;s.expr=h.selectors;s.expr[":"]=s.expr.filters;s.unique=h.uniqueSort;s.text=h.getText;s.isXMLDoc=h.isXML;s.contains=h.contains})();var j=/Until$/,F=/^(?:parents|prevUntil|prevAll)/,I=/,/,q=/^.[^:#\[\.,]*$/,R=Array.prototype.slice,U=s.expr.match.globalPOS,z={children:true,contents:true,next:true,prev:true};s.fn.extend({find:function(e){var t=this,n,r;if(typeof e!=="string"){return s(e).filter(function(){for(n=0,r=t.length;n<r;n++){if(s.contains(t[n],this)){return true}}})}var i=this.pushStack("","find",e),o,u,a;for(n=0,r=this.length;n<r;n++){o=i.length;s.find(e,this[n],i);if(n>0){for(u=o;u<i.length;u++){for(a=0;a<o;a++){if(i[a]===i[u]){i.splice(u--,1);break}}}}}return i},has:function(e){var t=s(e);return this.filter(function(){for(var e=0,n=t.length;e<n;e++){if(s.contains(this,t[e])){return true}}})},not:function(e){return this.pushStack(X(this,e,false),"not",e)},filter:function(e){return this.pushStack(X(this,e,true),"filter",e)},is:function(e){return!!e&&(typeof e==="string"?U.test(e)?s(e,this.context).index(this[0])>=0:s.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n=[],r,i,o=this[0];if(s.isArray(e)){var u=1;while(o&&o.ownerDocument&&o!==t){for(r=0;r<e.length;r++){if(s(o).is(e[r])){n.push({selector:e[r],elem:o,level:u})}}o=o.parentNode;u++}return n}var a=U.test(e)||typeof e!=="string"?s(e,t||this.context):0;for(r=0,i=this.length;r<i;r++){o=this[r];while(o){if(a?a.index(o)>-1:s.find.matchesSelector(o,e)){n.push(o);break}else{o=o.parentNode;if(!o||!o.ownerDocument||o===t||o.nodeType===11){break}}}}n=n.length>1?s.unique(n):n;return this.pushStack(n,"closest",e)},index:function(e){if(!e){return this[0]&&this[0].parentNode?this.prevAll().length:-1}if(typeof e==="string"){return s.inArray(this[0],s(e))}return s.inArray(e.jquery?e[0]:e,this)},add:function(e,t){var n=typeof e==="string"?s(e,t):s.makeArray(e&&e.nodeType?[e]:e),r=s.merge(this.get(),n);return this.pushStack(W(n[0])||W(r[0])?r:s.unique(r))},andSelf:function(){return this.add(this.prevObject)}});s.each({parent:function(e){var t=e.parentNode;return t&&t.nodeType!==11?t:null},parents:function(e){return s.dir(e,"parentNode")},parentsUntil:function(e,t,n){return s.dir(e,"parentNode",n)},next:function(e){return s.nth(e,2,"nextSibling")},prev:function(e){return s.nth(e,2,"previousSibling")},nextAll:function(e){return s.dir(e,"nextSibling")},prevAll:function(e){return s.dir(e,"previousSibling")},nextUntil:function(e,t,n){return s.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return s.dir(e,"previousSibling",n)},siblings:function(e){return s.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return s.sibling(e.firstChild)},contents:function(e){return s.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:s.makeArray(e.childNodes)}},function(e,t){s.fn[e]=function(n,r){var i=s.map(this,t,n);if(!j.test(e)){r=n}if(r&&typeof r==="string"){i=s.filter(r,i)}i=this.length>1&&!z[e]?s.unique(i):i;if((this.length>1||I.test(r))&&F.test(e)){i=i.reverse()}return this.pushStack(i,e,R.call(arguments).join(","))}});s.extend({filter:function(e,t,n){if(n){e=":not("+e+")"}return t.length===1?s.find.matchesSelector(t[0],e)?[t[0]]:[]:s.find.matches(e,t)},dir:function(e,n,r){var i=[],o=e[n];while(o&&o.nodeType!==9&&(r===t||o.nodeType!==1||!s(o).is(r))){if(o.nodeType===1){i.push(o)}o=o[n]}return i},nth:function(e,t,n,r){t=t||1;var i=0;for(;e;e=e[n]){if(e.nodeType===1&&++i===t){break}}return e},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling){if(e.nodeType===1&&e!==t){n.push(e)}}return n}});var $="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|"+"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",J=/ jQuery\d+="(?:\d+|null)"/g,K=/^\s+/,Q=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,G=/<([\w:]+)/,Y=/<tbody/i,Z=/<|&#?\w+;/,et=/<(?:script|style)/i,tt=/<(?:script|object|embed|option|style)/i,nt=new RegExp("<(?:"+$+")[\\s/>]","i"),rt=/checked\s*(?:[^=]|=\s*.checked.)/i,it=/\/(java|ecma)script/i,st=/^\s*<!(?:\[CDATA\[|\-\-)/,ot={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,"",""]},ut=V(n);ot.optgroup=ot.option;ot.tbody=ot.tfoot=ot.colgroup=ot.caption=ot.thead;ot.th=ot.td;if(!s.support.htmlSerialize){ot._default=[1,"div<div>","</div>"]}s.fn.extend({text:function(e){return s.access(this,function(e){return e===t?s.text(this):this.empty().append((this[0]&&this[0].ownerDocument||n).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(s.isFunction(e)){return this.each(function(t){s(this).wrapAll(e.call(this,t))})}if(this[0]){var t=s(e,this[0].ownerDocument).eq(0).clone(true);if(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){if(s.isFunction(e)){return this.each(function(t){s(this).wrapInner(e.call(this,t))})}return this.each(function(){var t=s(this),n=t.contents();if(n.length){n.wrapAll(e)}else{t.append(e)}})},wrap:function(e){var t=s.isFunction(e);return this.each(function(n){s(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){if(!s.nodeName(this,"body")){s(this).replaceWith(this.childNodes)}}).end()},append:function(){return this.domManip(arguments,true,function(e){if(this.nodeType===1){this.appendChild(e)}})},prepend:function(){return this.domManip(arguments,true,function(e){if(this.nodeType===1){this.insertBefore(e,this.firstChild)}})},before:function(){if(this[0]&&this[0].parentNode){return this.domManip(arguments,false,function(e){this.parentNode.insertBefore(e,this)})}else if(arguments.length){var e=s.clean(arguments);e.push.apply(e,this.toArray());return this.pushStack(e,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode){return this.domManip(arguments,false,function(e){this.parentNode.insertBefore(e,this.nextSibling)})}else if(arguments.length){var e=this.pushStack(this,"after",arguments);e.push.apply(e,s.clean(arguments));return e}},remove:function(e,t){for(var n=0,r;(r=this[n])!=null;n++){if(!e||s.filter(e,[r]).length){if(!t&&r.nodeType===1){s.cleanData(r.getElementsByTagName("*"));s.cleanData([r])}if(r.parentNode){r.parentNode.removeChild(r)}}}return this},empty:function(){for(var e=0,t;(t=this[e])!=null;e++){if(t.nodeType===1){s.cleanData(t.getElementsByTagName("*"))}while(t.firstChild){t.removeChild(t.firstChild)}}return this},clone:function(e,t){e=e==null?false:e;t=t==null?e:t;return this.map(function(){return s.clone(this,e,t)})},html:function(e){return s.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t){return n.nodeType===1?n.innerHTML.replace(J,""):null}if(typeof e==="string"&&!et.test(e)&&(s.support.leadingWhitespace||!K.test(e))&&!ot[(G.exec(e)||["",""])[1].toLowerCase()]){e=e.replace(Q,"<$1></$2>");try{for(;r<i;r++){n=this[r]||{};if(n.nodeType===1){s.cleanData(n.getElementsByTagName("*"));n.innerHTML=e}}n=0}catch(o){}}if(n){this.empty().append(e)}},null,e,arguments.length)},replaceWith:function(e){if(this[0]&&this[0].parentNode){if(s.isFunction(e)){return this.each(function(t){var n=s(this),r=n.html();n.replaceWith(e.call(this,t,r))})}if(typeof e!=="string"){e=s(e).detach()}return this.each(function(){var t=this.nextSibling,n=this.parentNode;s(this).remove();if(t){s(t).before(e)}else{s(n).append(e)}})}else{return this.length?this.pushStack(s(s.isFunction(e)?e():e),"replaceWith",e):this}},detach:function(e){return this.remove(e,true)},domManip:function(e,n,r){var i,o,u,a,f=e[0],l=[];if(!s.support.checkClone&&arguments.length===3&&typeof f==="string"&&rt.test(f)){return this.each(function(){s(this).domManip(e,n,r,true)})}if(s.isFunction(f)){return this.each(function(i){var o=s(this);e[0]=f.call(this,i,n?o.html():t);o.domManip(e,n,r)})}if(this[0]){a=f&&f.parentNode;if(s.support.parentNode&&a&&a.nodeType===11&&a.childNodes.length===this.length){i={fragment:a}}else{i=s.buildFragment(e,this,l)}u=i.fragment;if(u.childNodes.length===1){o=u=u.firstChild}else{o=u.firstChild}if(o){n=n&&s.nodeName(o,"tr");for(var c=0,h=this.length,p=h-1;c<h;c++){r.call(n?at(this[c],o):this[c],i.cacheable||h>1&&c<p?s.clone(u,true,true):u)}}if(l.length){s.each(l,function(e,t){if(t.src){s.ajax({type:"GET",global:false,url:t.src,async:false,dataType:"script"})}else{s.globalEval((t.text||t.textContent||t.innerHTML||"").replace(st,"/*$0*/"))}if(t.parentNode){t.parentNode.removeChild(t)}})}}return this}});s.buildFragment=function(e,t,r){var i,o,u,a,f=e[0];if(t&&t[0]){a=t[0].ownerDocument||t[0]}if(!a.createDocumentFragment){a=n}if(e.length===1&&typeof f==="string"&&f.length<512&&a===n&&f.charAt(0)==="<"&&!tt.test(f)&&(s.support.checkClone||!rt.test(f))&&(s.support.html5Clone||!nt.test(f))){o=true;u=s.fragments[f];if(u&&u!==1){i=u}}if(!i){i=a.createDocumentFragment();s.clean(e,a,i,r)}if(o){s.fragments[f]=u?i:1}return{fragment:i,cacheable:o}};s.fragments={};s.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){s.fn[e]=function(n){var r=[],i=s(n),o=this.length===1&&this[0].parentNode;if(o&&o.nodeType===11&&o.childNodes.length===1&&i.length===1){i[t](this[0]);return this}else{for(var u=0,a=i.length;u<a;u++){var f=(u>0?this.clone(true):this).get();s(i[u])[t](f);r=r.concat(f)}return this.pushStack(r,e,i.selector)}}});s.extend({clone:function(e,t,n){var r,i,o,u=s.support.html5Clone||s.isXMLDoc(e)||!nt.test("<"+e.nodeName+">")?e.cloneNode(true):dt(e);if((!s.support.noCloneEvent||!s.support.noCloneChecked)&&(e.nodeType===1||e.nodeType===11)&&!s.isXMLDoc(e)){lt(e,u);r=ct(e);i=ct(u);for(o=0;r[o];++o){if(i[o]){lt(r[o],i[o])}}}if(t){ft(e,u);if(n){r=ct(e);i=ct(u);for(o=0;r[o];++o){ft(r[o],i[o])}}}r=i=null;return u},clean:function(e,t,r,i){var o,u,a,f=[];t=t||n;if(typeof t.createElement==="undefined"){t=t.ownerDocument||t[0]&&t[0].ownerDocument||n}for(var l=0,c;(c=e[l])!=null;l++){if(typeof c==="number"){c+=""}if(!c){continue}if(typeof c==="string"){if(!Z.test(c)){c=t.createTextNode(c)}else{c=c.replace(Q,"<$1></$2>");var h=(G.exec(c)||["",""])[1].toLowerCase(),p=ot[h]||ot._default,d=p[0],v=t.createElement("div"),m=ut.childNodes,g;if(t===n){ut.appendChild(v)}else{V(t).appendChild(v)}v.innerHTML=p[1]+c+p[2];while(d--){v=v.lastChild}if(!s.support.tbody){var y=Y.test(c),b=h==="table"&&!y?v.firstChild&&v.firstChild.childNodes:p[1]==="<table>"&&!y?v.childNodes:[];for(a=b.length-1;a>=0;--a){if(s.nodeName(b[a],"tbody")&&!b[a].childNodes.length){b[a].parentNode.removeChild(b[a])}}}if(!s.support.leadingWhitespace&&K.test(c)){v.insertBefore(t.createTextNode(K.exec(c)[0]),v.firstChild)}c=v.childNodes;if(v){v.parentNode.removeChild(v);if(m.length>0){g=m[m.length-1];if(g&&g.parentNode){g.parentNode.removeChild(g)}}}}}var w;if(!s.support.appendChecked){if(c[0]&&typeof (w=c.length)==="number"){for(a=0;a<w;a++){pt(c[a])}}else{pt(c)}}if(c.nodeType){f.push(c)}else{f=s.merge(f,c)}}if(r){o=function(e){return!e.type||it.test(e.type)};for(l=0;f[l];l++){u=f[l];if(i&&s.nodeName(u,"script")&&(!u.type||it.test(u.type))){i.push(u.parentNode?u.parentNode.removeChild(u):u)}else{if(u.nodeType===1){var E=s.grep(u.getElementsByTagName("script"),o);f.splice.apply(f,[l+1,0].concat(E))}r.appendChild(u)}}}return f},cleanData:function(e){var t,n,r=s.cache,i=s.event.special,o=s.support.deleteExpando;for(var u=0,a;(a=e[u])!=null;u++){if(a.nodeName&&s.noData[a.nodeName.toLowerCase()]){continue}n=a[s.expando];if(n){t=r[n];if(t&&t.events){for(var f in t.events){if(i[f]){s.event.remove(a,f)}else{s.removeEvent(a,f,t.handle)}}if(t.handle){t.handle.elem=null}}if(o){delete a[s.expando]}else if(a.removeAttribute){a.removeAttribute(s.expando)}delete r[n]}}}});var vt=/alpha\([^)]*\)/i,mt=/opacity=([^)]*)/,gt=/([A-Z]|^ms)/g,yt=/^[\-+]?(?:\d*\.)?\d+$/i,bt=/^-?(?:\d*\.)?\d+(?!px)[^\d\s]+$/i,wt=/^([\-+])=([\-+.\de]+)/,Et=/^margin/,St={position:"absolute",visibility:"hidden",display:"block"},xt=["Top","Right","Bottom","Left"],Tt,Nt,Ct;s.fn.css=function(e,n){return s.access(this,function(e,n,r){return r!==t?s.style(e,n,r):s.css(e,n)},e,n,arguments.length>1)};s.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Tt(e,"opacity");return n===""?"1":n}else{return e.style.opacity}}}},cssNumber:{fillOpacity:true,fontWeight:true,lineHeight:true,opacity:true,orphans:true,widows:true,zIndex:true,zoom:true},cssProps:{"float":s.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(!e||e.nodeType===3||e.nodeType===8||!e.style){return}var o,u,a=s.camelCase(n),f=e.style,l=s.cssHooks[a];n=s.cssProps[a]||a;if(r!==t){u=typeof r;if(u==="string"&&(o=wt.exec(r))){r=+(o[1]+1)*+o[2]+parseFloat(s.css(e,n));u="number"}if(r==null||u==="number"&&isNaN(r)){return}if(u==="number"&&!s.cssNumber[a]){r+="px"}if(!l||!("set"in l)||(r=l.set(e,r))!==t){try{f[n]=r}catch(c){}}}else{if(l&&"get"in l&&(o=l.get(e,false,i))!==t){return o}return f[n]}},css:function(e,n,r){var i,o;n=s.camelCase(n);o=s.cssHooks[n];n=s.cssProps[n]||n;if(n==="cssFloat"){n="float"}if(o&&"get"in o&&(i=o.get(e,true,r))!==t){return i}else if(Tt){return Tt(e,n)}},swap:function(e,t,n){var r={},i,s;for(s in t){r[s]=e.style[s];e.style[s]=t[s]}i=n.call(e);for(s in t){e.style[s]=r[s]}return i}});s.curCSS=s.css;if(n.defaultView&&n.defaultView.getComputedStyle){Nt=function(e,t){var n,r,i,o,u=e.style;t=t.replace(gt,"-$1").toLowerCase();if((r=e.ownerDocument.defaultView)&&(i=r.getComputedStyle(e,null))){n=i.getPropertyValue(t);if(n===""&&!s.contains(e.ownerDocument.documentElement,e)){n=s.style(e,t)}}if(!s.support.pixelMargin&&i&&Et.test(t)&&bt.test(n)){o=u.width;u.width=n;n=i.width;u.width=o}return n}}if(n.documentElement.currentStyle){Ct=function(e,t){var n,r,i,s=e.currentStyle&&e.currentStyle[t],o=e.style;if(s==null&&o&&(i=o[t])){s=i}if(bt.test(s)){n=o.left;r=e.runtimeStyle&&e.runtimeStyle.left;if(r){e.runtimeStyle.left=e.currentStyle.left}o.left=t==="fontSize"?"1em":s;s=o.pixelLeft+"px";o.left=n;if(r){e.runtimeStyle.left=r}}return s===""?"auto":s}}Tt=Nt||Ct;s.each(["height","width"],function(e,t){s.cssHooks[t]={get:function(e,n,r){if(n){if(e.offsetWidth!==0){return kt(e,t,r)}else{return s.swap(e,St,function(){return kt(e,t,r)})}}},set:function(e,t){return yt.test(t)?t+"px":t}}});if(!s.support.opacity){s.cssHooks.opacity={get:function(e,t){return mt.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?parseFloat(RegExp.$1)/100+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=s.isNumeric(t)?"alpha(opacity="+t*100+")":"",o=r&&r.filter||n.filter||"";n.zoom=1;if(t>=1&&s.trim(o.replace(vt,""))===""){n.removeAttribute("filter");if(r&&!r.filter){return}}n.filter=vt.test(o)?o.replace(vt,i):o+" "+i}}}s(function(){if(!s.support.reliableMarginRight){s.cssHooks.marginRight={get:function(e,t){return s.swap(e,{display:"inline-block"},function(){if(t){return Tt(e,"margin-right")}else{return e.style.marginRight}})}}}});if(s.expr&&s.expr.filters){s.expr.filters.hidden=function(e){var t=e.offsetWidth,n=e.offsetHeight;return t===0&&n===0||!s.support.reliableHiddenOffsets&&(e.style&&e.style.display||s.css(e,"display"))==="none"};s.expr.filters.visible=function(e){return!s.expr.filters.hidden(e)}}s.each({margin:"",padding:"",border:"Width"},function(e,t){s.cssHooks[e+t]={expand:function(n){var r,i=typeof n==="string"?n.split(" "):[n],s={};for(r=0;r<4;r++){s[e+xt[r]+t]=i[r]||i[r-2]||i[0]}return s}}});var Lt=/%20/g,At=/\[\]$/,Ot=/\r?\n/g,Mt=/#.*$/,_t=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,Dt=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,Pt=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,Ht=/^(?:GET|HEAD)$/,Bt=/^\/\//,jt=/\?/,Ft=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,It=/^(?:select|textarea)/i,qt=/\s+/,Rt=/([?&])_=[^&]*/,Ut=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,zt=s.fn.load,Wt={},Xt={},Vt,$t,Jt=["*/"]+["*"];try{Vt=i.href}catch(Kt){Vt=n.createElement("a");Vt.href="";Vt=Vt.href}$t=Ut.exec(Vt.toLowerCase())||[];s.fn.extend({load:function(e,n,r){if(typeof e!=="string"&&zt){return zt.apply(this,arguments)}else if(!this.length){return this}var i=e.indexOf(" ");if(i>=0){var o=e.slice(i,e.length);e=e.slice(0,i)}var u="GET";if(n){if(s.isFunction(n)){r=n;n=t}else if(typeof n==="object"){n=s.param(n,s.ajaxSettings.traditional);u="POST"}}var a=this;s.ajax({url:e,type:u,dataType:"html",data:n,complete:function(e,t,n){n=e.responseText;if(e.isResolved()){e.done(function(e){n=e});a.html(o?s("<div>").append(n.replace(Ft,"")).find(o):n)}if(r){a.each(r,[n,t,e])}}});return this},serialize:function(){return s.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?s.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||It.test(this.nodeName)||Dt.test(this.type))}).map(function(e,t){var n=s(this).val();return n==null?null:s.isArray(n)?s.map(n,function(e,n){return{name:t.name,value:e.replace(Ot,"\r\n")}}):{name:t.name,value:n.replace(Ot,"\r\n")}}).get()}});s.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(e,t){s.fn[t]=function(e){return this.on(t,e)}});s.each(["get","post"],function(e,n){s[n]=function(e,r,i,o){if(s.isFunction(r)){o=o||i;i=r;r=t}return s.ajax({type:n,url:e,data:r,success:i,dataType:o})}});s.extend({getScript:function(e,n){return s.get(e,t,n,"script")},getJSON:function(e,t,n){return s.get(e,t,n,"json")},ajaxSetup:function(e,t){if(t){Yt(e,s.ajaxSettings)}else{t=e;e=s.ajaxSettings}Yt(e,t);return e},ajaxSettings:{url:Vt,isLocal:Pt.test($t[1]),global:true,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:true,async:true,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":Jt},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":e.String,"text html":true,"text json":s.parseJSON,"text xml":s.parseXML},flatOptions:{context:true,url:true}},ajaxPrefilter:Qt(Wt),ajaxTransport:Qt(Xt),ajax:function(e,n){function S(e,n,c,h){if(y===2){return}y=2;if(m){clearTimeout(m)}v=t;p=h||"";E.readyState=e>0?4:0;var d,g,w,S=n,x=c?en(r,E,c):t,T,N;if(e>=200&&e<300||e===304){if(r.ifModified){if(T=E.getResponseHeader("Last-Modified")){s.lastModified[l]=T}if(N=E.getResponseHeader("Etag")){s.etag[l]=N}}if(e===304){S="notmodified";d=true}else{try{g=tn(r,x);S="success";d=true}catch(C){S="parsererror";w=C}}}else{w=S;if(!S||e){S="error";if(e<0){e=0}}}E.status=e;E.statusText=""+(n||S);if(d){u.resolveWith(i,[g,S,E])}else{u.rejectWith(i,[E,S,w])}E.statusCode(f);f=t;if(b){o.trigger("ajax"+(d?"Success":"Error"),[E,r,d?g:w])}a.fireWith(i,[E,S]);if(b){o.trigger("ajaxComplete",[E,r]);if(!--s.active){s.event.trigger("ajaxStop")}}}if(typeof e==="object"){n=e;e=t}n=n||{};var r=s.ajaxSetup({},n),i=r.context||r,o=i!==r&&(i.nodeType||i instanceof s)?s(i):s.event,u=s.Deferred(),a=s.Callbacks("once memory"),f=r.statusCode||{},l,c={},h={},p,d,v,m,g,y=0,b,w,E={readyState:0,setRequestHeader:function(e,t){if(!y){var n=e.toLowerCase();e=h[n]=h[n]||e;c[e]=t}return this},getAllResponseHeaders:function(){return y===2?p:null},getResponseHeader:function(e){var n;if(y===2){if(!d){d={};while(n=_t.exec(p)){d[n[1].toLowerCase()]=n[2]}}n=d[e.toLowerCase()]}return n===t?null:n},overrideMimeType:function(e){if(!y){r.mimeType=e}return this},abort:function(e){e=e||"abort";if(v){v.abort(e)}S(0,e);return this}};u.promise(E);E.success=E.done;E.error=E.fail;E.complete=a.add;E.statusCode=function(e){if(e){var t;if(y<2){for(t in e){f[t]=[f[t],e[t]]}}else{t=e[E.status];E.then(t,t)}}return this};r.url=((e||r.url)+"").replace(Mt,"").replace(Bt,$t[1]+"//");r.dataTypes=s.trim(r.dataType||"*").toLowerCase().split(qt);if(r.crossDomain==null){g=Ut.exec(r.url.toLowerCase());r.crossDomain=!!(g&&(g[1]!=$t[1]||g[2]!=$t[2]||(g[3]||(g[1]==="http:"?80:443))!=($t[3]||($t[1]==="http:"?80:443))))}if(r.data&&r.processData&&typeof r.data!=="string"){r.data=s.param(r.data,r.traditional)}Gt(Wt,r,n,E);if(y===2){return false}b=r.global;r.type=r.type.toUpperCase();r.hasContent=!Ht.test(r.type);if(b&&s.active++===0){s.event.trigger("ajaxStart")}if(!r.hasContent){if(r.data){r.url+=(jt.test(r.url)?"&":"?")+r.data;delete r.data}l=r.url;if(r.cache===false){var x=s.now(),T=r.url.replace(Rt,"$1_="+x);r.url=T+(T===r.url?(jt.test(r.url)?"&":"?")+"_="+x:"")}}if(r.data&&r.hasContent&&r.contentType!==false||n.contentType){E.setRequestHeader("Content-Type",r.contentType)}if(r.ifModified){l=l||r.url;if(s.lastModified[l]){E.setRequestHeader("If-Modified-Since",s.lastModified[l])}if(s.etag[l]){E.setRequestHeader("If-None-Match",s.etag[l])}}E.setRequestHeader("Accept",r.dataTypes[0]&&r.accepts[r.dataTypes[0]]?r.accepts[r.dataTypes[0]]+(r.dataTypes[0]!=="*"?", "+Jt+"; q=0.01":""):r.accepts["*"]);for(w in r.headers){E.setRequestHeader(w,r.headers[w])}if(r.beforeSend&&(r.beforeSend.call(i,E,r)===false||y===2)){E.abort();return false}for(w in{success:1,error:1,complete:1}){E[w](r[w])}v=Gt(Xt,r,n,E);if(!v){S(-1,"No Transport")}else{E.readyState=1;if(b){o.trigger("ajaxSend",[E,r])}if(r.async&&r.timeout>0){m=setTimeout(function(){E.abort("timeout")},r.timeout)}try{y=1;v.send(c,S)}catch(N){if(y<2){S(-1,N)}else{throw N}}}return E},param:function(e,n){var r=[],i=function(e,t){t=s.isFunction(t)?t():t;r[r.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(n===t){n=s.ajaxSettings.traditional}if(s.isArray(e)||e.jquery&&!s.isPlainObject(e)){s.each(e,function(){i(this.name,this.value)})}else{for(var o in e){Zt(o,e[o],n,i)}}return r.join("&").replace(Lt,"+")}});s.extend({active:0,lastModified:{},etag:{}});var nn=s.now(),rn=/(\=)\?(&|$)|\?\?/i;s.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return s.expando+"_"+nn++}});s.ajaxPrefilter("json jsonp",function(t,n,r){var i=typeof t.data==="string"&&/^application\/x\-www\-form\-urlencoded/.test(t.contentType);if(t.dataTypes[0]==="jsonp"||t.jsonp!==false&&(rn.test(t.url)||i&&rn.test(t.data))){var o,u=t.jsonpCallback=s.isFunction(t.jsonpCallback)?t.jsonpCallback():t.jsonpCallback,a=e[u],f=t.url,l=t.data,c="$1"+u+"$2";if(t.jsonp!==false){f=f.replace(rn,c);if(t.url===f){if(i){l=l.replace(rn,c)}if(t.data===l){f+=(/\?/.test(f)?"&":"?")+t.jsonp+"="+u}}}t.url=f;t.data=l;e[u]=function(e){o=[e]};r.always(function(){e[u]=a;if(o&&s.isFunction(a)){e[u](o[0])}});t.converters["script json"]=function(){if(!o){s.error(u+" was not called")}return o[0]};t.dataTypes[0]="json";return"script"}});s.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(e){s.globalEval(e);return e}}});s.ajaxPrefilter("script",function(e){if(e.cache===t){e.cache=false}if(e.crossDomain){e.type="GET";e.global=false}});s.ajaxTransport("script",function(e){if(e.crossDomain){var r,i=n.head||n.getElementsByTagName("head")[0]||n.documentElement;return{send:function(s,o){r=n.createElement("script");r.async="async";if(e.scriptCharset){r.charset=e.scriptCharset}r.src=e.url;r.onload=r.onreadystatechange=function(e,n){if(n||!r.readyState||/loaded|complete/.test(r.readyState)){r.onload=r.onreadystatechange=null;if(i&&r.parentNode){i.removeChild(r)}r=t;if(!n){o(200,"success")}}};i.insertBefore(r,i.firstChild)},abort:function(){if(r){r.onload(0,1)}}}}});var sn=e.ActiveXObject?function(){for(var e in un){un[e](0,1)}}:false,on=0,un;s.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&an()||fn()}:an;(function(e){s.extend(s.support,{ajax:!!e,cors:!!e&&"withCredentials"in e})})(s.ajaxSettings.xhr());if(s.support.ajax){s.ajaxTransport(function(n){if(!n.crossDomain||s.support.cors){var r;return{send:function(i,o){var u=n.xhr(),a,f;if(n.username){u.open(n.type,n.url,n.async,n.username,n.password)}else{u.open(n.type,n.url,n.async)}if(n.xhrFields){for(f in n.xhrFields){u[f]=n.xhrFields[f]}}if(n.mimeType&&u.overrideMimeType){u.overrideMimeType(n.mimeType)}if(!n.crossDomain&&!i["X-Requested-With"]){i["X-Requested-With"]="XMLHttpRequest"}try{for(f in i){u.setRequestHeader(f,i[f])}}catch(l){}u.send(n.hasContent&&n.data||null);r=function(e,i){var f,l,c,h,p;try{if(r&&(i||u.readyState===4)){r=t;if(a){u.onreadystatechange=s.noop;if(sn){delete un[a]}}if(i){if(u.readyState!==4){u.abort()}}else{f=u.status;c=u.getAllResponseHeaders();h={};p=u.responseXML;if(p&&p.documentElement){h.xml=p}try{h.text=u.responseText}catch(e){}try{l=u.statusText}catch(d){l=""}if(!f&&n.isLocal&&!n.crossDomain){f=h.text?200:404}else if(f===1223){f=204}}}}catch(v){if(!i){o(-1,v)}}if(h){o(f,l,h,c)}};if(!n.async||u.readyState===4){r()}else{a=++on;if(sn){if(!un){un={};s(e).unload(sn)}un[a]=r}u.onreadystatechange=r}},abort:function(){if(r){r(0,1)}}}}})}var ln={},cn,hn,pn=/^(?:toggle|show|hide)$/,dn=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,vn,mn=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]],gn;s.fn.extend({show:function(e,t,n){var r,i;if(e||e===0){return this.animate(wn("show",3),e,t,n)}else{for(var o=0,u=this.length;o<u;o++){r=this[o];if(r.style){i=r.style.display;if(!s._data(r,"olddisplay")&&i==="none"){i=r.style.display=""}if(i===""&&s.css(r,"display")==="none"||!s.contains(r.ownerDocument.documentElement,r)){s._data(r,"olddisplay",En(r.nodeName))}}}for(o=0;o<u;o++){r=this[o];if(r.style){i=r.style.display;if(i===""||i==="none"){r.style.display=s._data(r,"olddisplay")||""}}}return this}},hide:function(e,t,n){if(e||e===0){return this.animate(wn("hide",3),e,t,n)}else{var r,i,o=0,u=this.length;for(;o<u;o++){r=this[o];if(r.style){i=s.css(r,"display");if(i!=="none"&&!s._data(r,"olddisplay")){s._data(r,"olddisplay",i)}}}for(o=0;o<u;o++){if(this[o].style){this[o].style.display="none"}}return this}},_toggle:s.fn.toggle,toggle:function(e,t,n){var r=typeof e==="boolean";if(s.isFunction(e)&&s.isFunction(t)){this._toggle.apply(this,arguments)}else if(e==null||r){this.each(function(){var t=r?e:s(this).is(":hidden");s(this)[t?"show":"hide"]()})}else{this.animate(wn("toggle",3),e,t,n)}return this},fadeTo:function(e,t,n,r){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){function o(){if(i.queue===false){s._mark(this)}var t=s.extend({},i),n=this.nodeType===1,r=n&&s(this).is(":hidden"),o,u,a,f,l,c,h,p,d,v,m;t.animatedProperties={};for(a in e){o=s.camelCase(a);if(a!==o){e[o]=e[a];delete e[a]}if((l=s.cssHooks[o])&&"expand"in l){c=l.expand(e[o]);delete e[o];for(a in c){if(!(a in e)){e[a]=c[a]}}}}for(o in e){u=e[o];if(s.isArray(u)){t.animatedProperties[o]=u[1];u=e[o]=u[0]}else{t.animatedProperties[o]=t.specialEasing&&t.specialEasing[o]||t.easing||"swing"}if(u==="hide"&&r||u==="show"&&!r){return t.complete.call(this)}if(n&&(o==="height"||o==="width")){t.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY];if(s.css(this,"display")==="inline"&&s.css(this,"float")==="none"){if(!s.support.inlineBlockNeedsLayout||En(this.nodeName)==="inline"){this.style.display="inline-block"}else{this.style.zoom=1}}}}if(t.overflow!=null){this.style.overflow="hidden"}for(a in e){f=new s.fx(this,t,a);u=e[a];if(pn.test(u)){m=s._data(this,"toggle"+a)||(u==="toggle"?r?"show":"hide":0);if(m){s._data(this,"toggle"+a,m==="show"?"hide":"show");f[m]()}else{f[u]()}}else{h=dn.exec(u);p=f.cur();if(h){d=parseFloat(h[2]);v=h[3]||(s.cssNumber[a]?"":"px");if(v!=="px"){s.style(this,a,(d||1)+v);p=(d||1)/f.cur()*p;s.style(this,a,p+v)}if(h[1]){d=(h[1]==="-="?-1:1)*d+p}f.custom(p,d,v)}else{f.custom(p,u,"")}}}return true}var i=s.speed(t,n,r);if(s.isEmptyObject(e)){return this.each(i.complete,[false])}e=s.extend({},e);return i.queue===false?this.each(o):this.queue(i.queue,o)},stop:function(e,n,r){if(typeof e!=="string"){r=n;n=e;e=t}if(n&&e!==false){this.queue(e||"fx",[])}return this.each(function(){function u(e,t,n){var i=t[n];s.removeData(e,n,true);i.stop(r)}var t,n=false,i=s.timers,o=s._data(this);if(!r){s._unmark(true,this)}if(e==null){for(t in o){if(o[t]&&o[t].stop&&t.indexOf(".run")===t.length-4){u(this,o,t)}}}else if(o[t=e+".run"]&&o[t].stop){u(this,o,t)}for(t=i.length;t--;){if(i[t].elem===this&&(e==null||i[t].queue===e)){if(r){i[t](true)}else{i[t].saveState()}n=true;i.splice(t,1)}}if(!(r&&n)){s.dequeue(this,e)}})}});s.each({slideDown:wn("show",1),slideUp:wn("hide",1),slideToggle:wn("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){s.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}});s.extend({speed:function(e,t,n){var r=e&&typeof e==="object"?s.extend({},e):{complete:n||!n&&t||s.isFunction(e)&&e,duration:e,easing:n&&t||t&&!s.isFunction(t)&&t};r.duration=s.fx.off?0:typeof r.duration==="number"?r.duration:r.duration in s.fx.speeds?s.fx.speeds[r.duration]:s.fx.speeds._default;if(r.queue==null||r.queue===true){r.queue="fx"}r.old=r.complete;r.complete=function(e){if(s.isFunction(r.old)){r.old.call(this)}if(r.queue){s.dequeue(this,r.queue)}else if(e!==false){s._unmark(this)}};return r},easing:{linear:function(e){return e},swing:function(e){return-Math.cos(e*Math.PI)/2+.5}},timers:[],fx:function(e,t,n){this.options=t;this.elem=e;this.prop=n;t.orig=t.orig||{}}});s.fx.prototype={update:function(){if(this.options.step){this.options.step.call(this.elem,this.now,this)}(s.fx.step[this.prop]||s.fx.step._default)(this)},cur:function(){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null)){return this.elem[this.prop]}var e,t=s.css(this.elem,this.prop);return isNaN(e=parseFloat(t))?!t||t==="auto"?0:t:e},custom:function(e,n,r){function u(e){return i.step(e)}var i=this,o=s.fx;this.startTime=gn||yn();this.end=n;this.now=this.start=e;this.pos=this.state=0;this.unit=r||this.unit||(s.cssNumber[this.prop]?"":"px");u.queue=this.options.queue;u.elem=this.elem;u.saveState=function(){if(s._data(i.elem,"fxshow"+i.prop)===t){if(i.options.hide){s._data(i.elem,"fxshow"+i.prop,i.start)}else if(i.options.show){s._data(i.elem,"fxshow"+i.prop,i.end)}}};if(u()&&s.timers.push(u)&&!vn){vn=setInterval(o.tick,o.interval)}},show:function(){var e=s._data(this.elem,"fxshow"+this.prop);this.options.orig[this.prop]=e||s.style(this.elem,this.prop);this.options.show=true;if(e!==t){this.custom(this.cur(),e)}else{this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur())}s(this.elem).show()},hide:function(){this.options.orig[this.prop]=s._data(this.elem,"fxshow"+this.prop)||s.style(this.elem,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(e){var t,n,r,i=gn||yn(),o=true,u=this.elem,a=this.options;if(e||i>=a.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();a.animatedProperties[this.prop]=true;for(t in a.animatedProperties){if(a.animatedProperties[t]!==true){o=false}}if(o){if(a.overflow!=null&&!s.support.shrinkWrapBlocks){s.each(["","X","Y"],function(e,t){u.style["overflow"+t]=a.overflow[e]})}if(a.hide){s(u).hide()}if(a.hide||a.show){for(t in a.animatedProperties){s.style(u,t,a.orig[t]);s.removeData(u,"fxshow"+t,true);s.removeData(u,"toggle"+t,true)}}r=a.complete;if(r){a.complete=false;r.call(u)}}return false}else{if(a.duration==Infinity){this.now=i}else{n=i-this.startTime;this.state=n/a.duration;this.pos=s.easing[a.animatedProperties[this.prop]](this.state,n,0,1,a.duration);this.now=this.start+(this.end-this.start)*this.pos}this.update()}return true}};s.extend(s.fx,{tick:function(){var e,t=s.timers,n=0;for(;n<t.length;n++){e=t[n];if(!e()&&t[n]===e){t.splice(n--,1)}}if(!t.length){s.fx.stop()}},interval:13,stop:function(){clearInterval(vn);vn=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(e){s.style(e.elem,"opacity",e.now)},_default:function(e){if(e.elem.style&&e.elem.style[e.prop]!=null){e.elem.style[e.prop]=e.now+e.unit}else{e.elem[e.prop]=e.now}}}});s.each(mn.concat.apply([],mn),function(e,t){if(t.indexOf("margin")){s.fx.step[t]=function(e){s.style(e.elem,t,Math.max(0,e.now)+e.unit)}}});if(s.expr&&s.expr.filters){s.expr.filters.animated=function(e){return s.grep(s.timers,function(t){return e===t.elem}).length}}var Sn,xn=/^t(?:able|d|h)$/i,Tn=/^(?:body|html)$/i;if("getBoundingClientRect"in n.documentElement){Sn=function(e,t,n,r){try{r=e.getBoundingClientRect()}catch(i){}if(!r||!s.contains(n,e)){return r?{top:r.top,left:r.left}:{top:0,left:0}}var o=t.body,u=Nn(t),a=n.clientTop||o.clientTop||0,f=n.clientLeft||o.clientLeft||0,l=u.pageYOffset||s.support.boxModel&&n.scrollTop||o.scrollTop,c=u.pageXOffset||s.support.boxModel&&n.scrollLeft||o.scrollLeft,h=r.top+l-a,p=r.left+c-f;return{top:h,left:p}}}else{Sn=function(e,t,n){var r,i=e.offsetParent,o=e,u=t.body,a=t.defaultView,f=a?a.getComputedStyle(e,null):e.currentStyle,l=e.offsetTop,c=e.offsetLeft;while((e=e.parentNode)&&e!==u&&e!==n){if(s.support.fixedPosition&&f.position==="fixed"){break}r=a?a.getComputedStyle(e,null):e.currentStyle;l-=e.scrollTop;c-=e.scrollLeft;if(e===i){l+=e.offsetTop;c+=e.offsetLeft;if(s.support.doesNotAddBorder&&!(s.support.doesAddBorderForTableAndCells&&xn.test(e.nodeName))){l+=parseFloat(r.borderTopWidth)||0;c+=parseFloat(r.borderLeftWidth)||0}o=i;i=e.offsetParent}if(s.support.subtractsBorderForOverflowNotVisible&&r.overflow!=="visible"){l+=parseFloat(r.borderTopWidth)||0;c+=parseFloat(r.borderLeftWidth)||0}f=r}if(f.position==="relative"||f.position==="static"){l+=u.offsetTop;c+=u.offsetLeft}if(s.support.fixedPosition&&f.position==="fixed"){l+=Math.max(n.scrollTop,u.scrollTop);c+=Math.max(n.scrollLeft,u.scrollLeft)}return{top:l,left:c}}}s.fn.offset=function(e){if(arguments.length){return e===t?this:this.each(function(t){s.offset.setOffset(this,e,t)})}var n=this[0],r=n&&n.ownerDocument;if(!r){return null}if(n===r.body){return s.offset.bodyOffset(n)}return Sn(n,r,r.documentElement)};s.offset={bodyOffset:function(e){var t=e.offsetTop,n=e.offsetLeft;if(s.support.doesNotIncludeMarginInBodyOffset){t+=parseFloat(s.css(e,"marginTop"))||0;n+=parseFloat(s.css(e,"marginLeft"))||0}return{top:t,left:n}},setOffset:function(e,t,n){var r=s.css(e,"position");if(r==="static"){e.style.position="relative"}var i=s(e),o=i.offset(),u=s.css(e,"top"),a=s.css(e,"left"),f=(r==="absolute"||r==="fixed")&&s.inArray("auto",[u,a])>-1,l={},c={},h,p;if(f){c=i.position();h=c.top;p=c.left}else{h=parseFloat(u)||0;p=parseFloat(a)||0}if(s.isFunction(t)){t=t.call(e,n,o)}if(t.top!=null){l.top=t.top-o.top+h}if(t.left!=null){l.left=t.left-o.left+p}if("using"in t){t.using.call(e,l)}else{i.css(l)}}};s.fn.extend({position:function(){if(!this[0]){return null}var e=this[0],t=this.offsetParent(),n=this.offset(),r=Tn.test(t[0].nodeName)?{top:0,left:0}:t.offset();n.top-=parseFloat(s.css(e,"marginTop"))||0;n.left-=parseFloat(s.css(e,"marginLeft"))||0;r.top+=parseFloat(s.css(t[0],"borderTopWidth"))||0;r.left+=parseFloat(s.css(t[0],"borderLeftWidth"))||0;return{top:n.top-r.top,left:n.left-r.left}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||n.body;while(e&&!Tn.test(e.nodeName)&&s.css(e,"position")==="static"){e=e.offsetParent}return e})}});s.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);s.fn[e]=function(i){return s.access(this,function(e,i,o){var u=Nn(e);if(o===t){return u?n in u?u[n]:s.support.boxModel&&u.document.documentElement[i]||u.document.body[i]:e[i]}if(u){u.scrollTo(!r?o:s(u).scrollLeft(),r?o:s(u).scrollTop())}else{e[i]=o}},e,i,arguments.length,null)}});s.each({Height:"height",Width:"width"},function(e,n){var r="client"+e,i="scroll"+e,o="offset"+e;s.fn["inner"+e]=function(){var e=this[0];return e?e.style?parseFloat(s.css(e,n,"padding")):this[n]():null};s.fn["outer"+e]=function(e){var t=this[0];return t?t.style?parseFloat(s.css(t,n,e?"margin":"border")):this[n]():null};s.fn[n]=function(e){return s.access(this,function(e,n,u){var a,f,l,c;if(s.isWindow(e)){a=e.document;f=a.documentElement[r];return s.support.boxModel&&f||a.body&&a.body[r]||f}if(e.nodeType===9){a=e.documentElement;if(a[r]>=a[i]){return a[r]}return Math.max(e.body[i],a[i],e.body[o],a[o])}if(u===t){l=s.css(e,n);c=parseFloat(l);return s.isNumeric(c)?c:l}s(e).css(n,u)},n,e,arguments.length,null)}});e.jQuery=e.$=s;if(typeof define==="function"&&define.amd&&define.amd.jQuery){define("jquery",[],function(){return s})}})(window);(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().addBack().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.10.0",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("<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.fn.addBack||(e.fn.addBack=function(e){return this.add(e==null?this.prevObject:this.prevObject.filter(e))}),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)),e.ui.ie=!!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase()),e.support.selectstart="onselectstart"in document.createElement("div"),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)}},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)}})})(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={},f=t.split(".")[0];t=t.split(".")[1],i=f+"-"+t,r||(r=n,n=e.Widget),e.expr[":"][i.toLowerCase()]=function(t){return!!e.data(t,i)},e[f]=e[f]||{},s=e[f][t],o=e[f][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,r){if(!e.isFunction(r)){a[t]=r;return}a[t]=function(){var e=function(){return n.prototype[t].apply(this,arguments)},i=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=i,s=r.apply(this,arguments),this._super=t,this._superApply=n,s}}()}),o.prototype=e.widget.extend(u,{widgetEventPrefix:s?u.widgetEventPrefix:t},a,{constructor:o,namespace:f,widgetName:t,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.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]?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()})}})})(jQuery);(function(e,t){var n=!1;e(document).mouseup(function(){n=!1}),e.widget("ui.mouse",{version:"1.10.0",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||document.documentMode<9)&&!t.button?this._mouseUp(t):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)},_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(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return!0}})})(jQuery);(function(e,t){function n(e,t,n){return[parseInt(e[0],10)*(p.test(e[0])?t/100:1),parseInt(e[1],10)*(p.test(e[1])?n/100:1)]}function r(t,n){return parseInt(e.css(t,n),10)||0}function i(t){var n=t[0];return n.nodeType===9?{width:t.width(),height:t.height(),offset:{top:0,left:0}}:e.isWindow(n)?{width:t.width(),height:t.height(),offset:{top:t.scrollTop(),left:t.scrollLeft()}}:n.preventDefault?{width:0,height:0,offset:{top:n.pageY,left:n.pageX}}:{width:t.outerWidth(),height:t.outerHeight(),offset:t.offset()}}e.ui=e.ui||{};var s,o=Math.max,u=Math.abs,a=Math.round,f=/left|center|right/,l=/top|center|bottom/,c=/[\+\-]\d+%?/,h=/^\w+/,p=/%$/,d=e.fn.position;e.position={scrollbarWidth:function(){if(s!==t)return s;var n,r,i=e("<div style='display:block;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>"),o=i.children()[0];return e("body").append(i),n=o.offsetWidth,i.css("overflow","scroll"),r=o.offsetWidth,n===r&&(r=i[0].clientWidth),i.remove(),s=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 d.apply(this,arguments);t=e.extend({},t);var s,p,v,m,g,y,b=e(t.of),w=e.position.getWithinInfo(t.within),E=e.position.getScrollInfo(w),S=(t.collision||"flip").split(" "),x={};return y=i(b),b[0].preventDefault&&(t.at="left top"),p=y.width,v=y.height,m=y.offset,g=e.extend({},m),e.each(["my","at"],function(){var e=(t[this]||"").split(" "),n,r;e.length===1&&(e=f.test(e[0])?e.concat(["center"]):l.test(e[0])?["center"].concat(e):["center","center"]),e[0]=f.test(e[0])?e[0]:"center",e[1]=l.test(e[1])?e[1]:"center",n=c.exec(e[0]),r=c.exec(e[1]),x[this]=[n?n[0]:0,r?r[0]:0],t[this]=[h.exec(e[0])[0],h.exec(e[1])[0]]}),S.length===1&&(S[1]=S[0]),t.at[0]==="right"?g.left+=p:t.at[0]==="center"&&(g.left+=p/2),t.at[1]==="bottom"?g.top+=v:t.at[1]==="center"&&(g.top+=v/2),s=n(x.at,p,v),g.left+=s[0],g.top+=s[1],this.each(function(){var i,f,l=e(this),c=l.outerWidth(),h=l.outerHeight(),d=r(this,"marginLeft"),y=r(this,"marginTop"),T=c+d+r(this,"marginRight")+E.width,N=h+y+r(this,"marginBottom")+E.height,C=e.extend({},g),k=n(x.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-=h:t.my[1]==="center"&&(C.top-=h/2),C.left+=k[0],C.top+=k[1],e.support.offsetFractions||(C.left=a(C.left),C.top=a(C.top)),i={marginLeft:d,marginTop:y},e.each(["left","top"],function(n,r){e.ui.position[S[n]]&&e.ui.position[S[n]][r](C,{targetWidth:p,targetHeight:v,elemWidth:c,elemHeight:h,collisionPosition:i,collisionWidth:T,collisionHeight:N,offset:[s[0]+k[0],s[1]+k[1]],my:t.my,at:t.at,within:w,elem:l})}),t.using&&(f=function(e){var n=m.left-C.left,r=n+p-c,i=m.top-C.top,s=i+v-h,a={target:{element:b,left:m.left,top:m.top,width:p,height:v},element:{element:l,left:C.left,top:C.top,width:c,height:h},horizontal:r<0?"left":n>0?"right":"center",vertical:s<0?"top":i>0?"bottom":"middle"};p<c&&u(n+r)<p&&(a.horizontal="center"),v<h&&u(i+s)<v&&(a.vertical="middle"),o(u(n),u(r))>o(u(i),u(s))?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,s=e.left-t.collisionPosition.marginLeft,u=r-s,a=s+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=o(e.left-s,e.left)},top:function(e,t){var n=t.within,r=n.isWindow?n.scrollTop:n.offset.top,i=t.within.height,s=e.top-t.collisionPosition.marginTop,u=r-s,a=s+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=o(e.top-s,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,o=e.left-t.collisionPosition.marginLeft,a=o-s,f=o+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<u(a))e.left+=l+c+h}else if(f>0){d=e.left-t.collisionPosition.marginLeft+l+c+h-s;if(d>0||u(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,o=e.top-t.collisionPosition.marginTop,a=o-s,f=o+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<u(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||u(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)}()})(jQuery);(function(e,t){e.widget("ui.draggable",e.ui.mouse,{version:"1.10.0",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,drag:null,start:null,stop:null},_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).closest(".ui-resizable-handle").length>0?!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,r=this,i=!1,s=!1;e.ui.ddmanager&&!this.options.dropBehaviour&&(s=e.ui.ddmanager.drop(this,t)),this.dropped&&(s=this.dropped,this.dropped=!1),n=this.element[0];while(n&&(n=n.parentNode))n===document&&(i=!0);return!i&&this.options.helper==="original"?!1:(this.options.revert==="invalid"&&!s||this.options.revert==="valid"&&s||this.options.revert===!0||e.isFunction(this.options.revert)&&this.options.revert.call(this.element,s)?e(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){r._trigger("stop",t)!==!1&&r._clear()}):this._trigger("stop",t)!==!1&&this._clear(),!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("*").addBack().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,n,r,i=this.options;i.containment==="parent"&&(i.containment=this.helper[0].parentNode);if(i.containment==="document"||i.containment==="window")this.containment=[i.containment==="document"?0:e(window).scrollLeft()-this.offset.relative.left-this.offset.parent.left,i.containment==="document"?0:e(window).scrollTop()-this.offset.relative.top-this.offset.parent.top,(i.containment==="document"?0:e(window).scrollLeft())+e(i.containment==="document"?document:window).width()-this.helperProportions.width-this.margins.left,(i.containment==="document"?0:e(window).scrollTop())+(e(i.containment==="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top];if(!/^(document|window|parent)$/.test(i.containment)&&i.containment.constructor!==Array){n=e(i.containment),r=n[0];if(!r)return;t=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),(t?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,(t?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 i.containment.constructor===Array&&(this.containment=i.containment)},_convertPositionTo:function(t,n){n||(n=this.position);var r=t==="absolute"?1:-1,i=this.cssPosition!=="absolute"||this.scrollParent[0]!==document&&!!e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,s=/(html|body)/i.test(i[0].tagName);return{top:n.top+this.offset.relative.top*r+this.offset.parent.top*r-(this.cssPosition==="fixed"?-this.scrollParent.scrollTop():s?0:i.scrollTop())*r,left:n.left+this.offset.relative.left*r+this.offset.parent.left*r-(this.cssPosition==="fixed"?-this.scrollParent.scrollLeft():s?0:i.scrollLeft())*r}},_generatePosition:function(t){var n,r,i,s,o=this.options,u=this.cssPosition!=="absolute"||this.scrollParent[0]!==document&&!!e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,a=/(html|body)/i.test(u[0].tagName),f=t.pageX,l=t.pageY;return this.originalPosition&&(this.containment&&(this.relative_container?(r=this.relative_container.offset(),n=[this.containment[0]+r.left,this.containment[1]+r.top,this.containment[2]+r.left,this.containment[3]+r.top]):n=this.containment,t.pageX-this.offset.click.left<n[0]&&(f=n[0]+this.offset.click.left),t.pageY-this.offset.click.top<n[1]&&(l=n[1]+this.offset.click.top),t.pageX-this.offset.click.left>n[2]&&(f=n[2]+this.offset.click.left),t.pageY-this.offset.click.top>n[3]&&(l=n[3]+this.offset.click.top)),o.grid&&(i=o.grid[1]?this.originalPageY+Math.round((l-this.originalPageY)/o.grid[1])*o.grid[1]:this.originalPageY,l=n?i-this.offset.click.top>=n[1]||i-this.offset.click.top>n[3]?i:i-this.offset.click.top>=n[1]?i-o.grid[1]:i+o.grid[1]:i,s=o.grid[0]?this.originalPageX+Math.round((f-this.originalPageX)/o.grid[0])*o.grid[0]:this.originalPageX,f=n?s-this.offset.click.left>=n[0]||s-this.offset.click.left>n[2]?s:s-this.offset.click.left>=n[0]?s-o.grid[0]:s+o.grid[0]:s)),{top:l-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(this.cssPosition==="fixed"?-this.scrollParent.scrollTop():a?0:u.scrollTop()),left:f-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(this.cssPosition==="fixed"?-this.scrollParent.scrollLeft():a?0:u.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(){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("ui-draggable"),i=r.options,s=e.extend({},n,{item:r.element});r.sortables=[],e(i.connectToSortable).each(function(){var n=e.data(this,"ui-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("ui-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("ui-draggable"),i=this;e.each(r.sortables,function(){var s=!1,o=this;this.instance.positionAbs=r.positionAbs,this.instance.helperProportions=r.helperProportions,this.instance.offset.click=r.offset.click,this.instance._intersectsWith(this.instance.containerCache)&&(s=!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!==o&&this.instance._intersectsWith(this.instance.containerCache)&&e.ui.contains(o.instance.element[0],this.instance.element[0])&&(s=!1),s})),s?(this.instance.isOver||(this.instance.isOver=1,this.instance.currentItem=e(i).clone().removeAttr("id").appendTo(this.instance.element).data("ui-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(){var t=e("body"),n=e(this).data("ui-draggable").options;t.css("cursor")&&(n._cursor=t.css("cursor")),t.css("cursor",n.cursor)},stop:function(){var t=e(this).data("ui-draggable").options;t._cursor&&e("body").css("cursor",t._cursor)}}),e.ui.plugin.add("draggable","opacity",{start:function(t,n){var r=e(n.helper),i=e(this).data("ui-draggable").options;r.css("opacity")&&(i._opacity=r.css("opacity")),r.css("opacity",i.opacity)},stop:function(t,n){var r=e(this).data("ui-draggable").options;r._opacity&&e(n.helper).css("opacity",r._opacity)}}),e.ui.plugin.add("draggable","scroll",{start:function(){var t=e(this).data("ui-draggable");t.scrollParent[0]!==document&&t.scrollParent[0].tagName!=="HTML"&&(t.overflowOffset=t.scrollParent.offset())},drag:function(t){var n=e(this).data("ui-draggable"),r=n.options,i=!1;if(n.scrollParent[0]!==document&&n.scrollParent[0].tagName!=="HTML"){if(!r.axis||r.axis!=="x")n.overflowOffset.top+n.scrollParent[0].offsetHeight-t.pageY<r.scrollSensitivity?n.scrollParent[0].scrollTop=i=n.scrollParent[0].scrollTop+r.scrollSpeed:t.pageY-n.overflowOffset.top<r.scrollSensitivity&&(n.scrollParent[0].scrollTop=i=n.scrollParent[0].scrollTop-r.scrollSpeed);if(!r.axis||r.axis!=="y")n.overflowOffset.left+n.scrollParent[0].offsetWidth-t.pageX<r.scrollSensitivity?n.scrollParent[0].scrollLeft=i=n.scrollParent[0].scrollLeft+r.scrollSpeed:t.pageX-n.overflowOffset.left<r.scrollSensitivity&&(n.scrollParent[0].scrollLeft=i=n.scrollParent[0].scrollLeft-r.scrollSpeed)}else{if(!r.axis||r.axis!=="x")t.pageY-e(document).scrollTop()<r.scrollSensitivity?i=e(document).scrollTop(e(document).scrollTop()-r.scrollSpeed):e(window).height()-(t.pageY-e(document).scrollTop())<r.scrollSensitivity&&(i=e(document).scrollTop(e(document).scrollTop()+r.scrollSpeed));if(!r.axis||r.axis!=="y")t.pageX-e(document).scrollLeft()<r.scrollSensitivity?i=e(document).scrollLeft(e(document).scrollLeft()-r.scrollSpeed):e(window).width()-(t.pageX-e(document).scrollLeft())<r.scrollSensitivity&&(i=e(document).scrollLeft(e(document).scrollLeft()+r.scrollSpeed))}i!==!1&&e.ui.ddmanager&&!r.dropBehaviour&&e.ui.ddmanager.prepareOffsets(n,t)}}),e.ui.plugin.add("draggable","snap",{start:function(){var t=e(this).data("ui-draggable"),n=t.options;t.snapElements=[],e(n.snap.constructor!==String?n.snap.items||":data(ui-draggable)":n.snap).each(function(){var n=e(this),r=n.offset();this!==t.element[0]&&t.snapElements.push({item:this,width:n.outerWidth(),height:n.outerHeight(),top:r.top,left:r.left})})},drag:function(t,n){var r,i,s,o,u,a,f,l,c,h,p=e(this).data("ui-draggable"),d=p.options,v=d.snapTolerance,m=n.offset.left,g=m+p.helperProportions.width,y=n.offset.top,b=y+p.helperProportions.height;for(c=p.snapElements.length-1;c>=0;c--){u=p.snapElements[c].left,a=u+p.snapElements[c].width,f=p.snapElements[c].top,l=f+p.snapElements[c].height;if(!(u-v<m&&m<a+v&&f-v<y&&y<l+v||u-v<m&&m<a+v&&f-v<b&&b<l+v||u-v<g&&g<a+v&&f-v<y&&y<l+v||u-v<g&&g<a+v&&f-v<b&&b<l+v)){p.snapElements[c].snapping&&p.options.snap.release&&p.options.snap.release.call(p.element,t,e.extend(p._uiHash(),{snapItem:p.snapElements[c].item})),p.snapElements[c].snapping=!1;continue}d.snapMode!=="inner"&&(r=Math.abs(f-b)<=v,i=Math.abs(l-y)<=v,s=Math.abs(u-g)<=v,o=Math.abs(a-m)<=v,r&&(n.position.top=p._convertPositionTo("relative",{top:f-p.helperProportions.height,left:0}).top-p.margins.top),i&&(n.position.top=p._convertPositionTo("relative",{top:l,left:0}).top-p.margins.top),s&&(n.position.left=p._convertPositionTo("relative",{top:0,left:u-p.helperProportions.width}).left-p.margins.left),o&&(n.position.left=p._convertPositionTo("relative",{top:0,left:a}).left-p.margins.left)),h=r||i||s||o,d.snapMode!=="outer"&&(r=Math.abs(f-y)<=v,i=Math.abs(l-b)<=v,s=Math.abs(u-m)<=v,o=Math.abs(a-g)<=v,r&&(n.position.top=p._convertPositionTo("relative",{top:f,left:0}).top-p.margins.top),i&&(n.position.top=p._convertPositionTo("relative",{top:l-p.helperProportions.height,left:0}).top-p.margins.top),s&&(n.position.left=p._convertPositionTo("relative",{top:0,left:u}).left-p.margins.left),o&&(n.position.left=p._convertPositionTo("relative",{top:0,left:a-p.helperProportions.width}).left-p.margins.left)),!p.snapElements[c].snapping&&(r||i||s||o||h)&&p.options.snap.snap&&p.options.snap.snap.call(p.element,t,e.extend(p._uiHash(),{snapItem:p.snapElements[c].item})),p.snapElements[c].snapping=r||i||s||o||h}}}),e.ui.plugin.add("draggable","stack",{start:function(){var t,n=e(this).data("ui-draggable").options,r=e.makeArray(e(n.stack)).sort(function(t,n){return(parseInt(e(t).css("zIndex"),10)||0)-(parseInt(e(n).css("zIndex"),10)||0)});if(!r.length)return;t=parseInt(r[0].style.zIndex,10)||0,e(r).each(function(e){this.style.zIndex=t+e}),this[0].style.zIndex=t+r.length}}),e.ui.plugin.add("draggable","zIndex",{start:function(t,n){var r=e(n.helper),i=e(this).data("ui-draggable").options;r.css("zIndex")&&(i._zIndex=r.css("zIndex")),r.css("zIndex",i.zIndex)},stop:function(t,n){var r=e(this).data("ui-draggable").options;r._zIndex&&e(n.helper).css("zIndex",r._zIndex)}})})(jQuery);(function(e,t){function n(e,t,n){return e>t&&e<t+n}e.widget("ui.droppable",{version:"1.10.0",widgetEventPrefix:"drop",options:{accept:"*",activeClass:!1,addClasses:!0,greedy:!1,hoverClass:!1,scope:"default",tolerance:"intersect",activate:null,deactivate:null,drop:null,out:null,over:null},_create:function(){var t=this.options,n=t.accept;this.isover=!1,this.isout=!0,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=0,n=e.ui.ddmanager.droppables[this.options.scope];for(;t<n.length;t++)n[t]===this&&n.splice(t,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,i=!1;return!r||(r.currentItem||r.element)[0]===this.element[0]?!1:(this.element.find(":data(ui-droppable)").not(".ui-draggable-dragging").each(function(){var t=e.data(this,"ui-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(e,t,r){if(!t.offset)return!1;var i,s,o=(e.positionAbs||e.position.absolute).left,u=o+e.helperProportions.width,a=(e.positionAbs||e.position.absolute).top,f=a+e.helperProportions.height,l=t.offset.left,c=l+t.proportions.width,h=t.offset.top,p=h+t.proportions.height;switch(r){case"fit":return l<=o&&u<=c&&h<=a&&f<=p;case"intersect":return l<o+e.helperProportions.width/2&&u-e.helperProportions.width/2<c&&h<a+e.helperProportions.height/2&&f-e.helperProportions.height/2<p;case"pointer":return i=(e.positionAbs||e.position.absolute).left+(e.clickOffset||e.offset.click).left,s=(e.positionAbs||e.position.absolute).top+(e.clickOffset||e.offset.click).top,n(s,h,t.proportions.height)&&n(i,l,t.proportions.width);case"touch":return(a>=h&&a<=p||f>=h&&f<=p||a<h&&f>p)&&(o>=l&&o<=c||u>=l&&u<=c||o<l&&u>c);default:return!1}},e.ui.ddmanager={current:null,droppables:{"default":[]},prepareOffsets:function(t,n){var r,i,s=e.ui.ddmanager.droppables[t.options.scope]||[],o=n?n.type:null,u=(t.currentItem||t.element).find(":data(ui-droppable)").addBack();e:for(r=0;r<s.length;r++){if(s[r].options.disabled||t&&!s[r].accept.call(s[r].element[0],t.currentItem||t.element))continue;for(i=0;i<u.length;i++)if(u[i]===s[r].element[0]){s[r].proportions.height=0;continue e}s[r].visible=s[r].element.css("display")!=="none";if(!s[r].visible)continue;o==="mousedown"&&s[r]._activate.call(s[r],n),s[r].offset=s[r].element.offset(),s[r].proportions={width:s[r].element[0].offsetWidth,height:s[r].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=!0,this.isover=!1,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,i,s,o=e.ui.intersect(t,this,this.options.tolerance),u=!o&&this.isover?"isout":o&&!this.isover?"isover":null;if(!u)return;this.options.greedy&&(i=this.options.scope,s=this.element.parents(":data(ui-droppable)").filter(function(){return e.data(this,"ui-droppable").options.scope===i}),s.length&&(r=e.data(s[0],"ui-droppable"),r.greedyChild=u==="isover")),r&&u==="isover"&&(r.isover=!1,r.isout=!0,r._out.call(r,n)),this[u]=!0,this[u==="isout"?"isover":"isout"]=!1,this[u==="isover"?"_over":"_out"].call(this,n),r&&u==="isout"&&(r.isout=!1,r.isover=!0,r._over.call(r,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){function n(e){return parseInt(e,10)||0}function r(e){return!isNaN(parseInt(e,10))}e.widget("ui.resizable",e.ui.mouse,{version:"1.10.0",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:90,resize:null,start:null,stop:null},_create:function(){var t,n,r,i,s,o=this,u=this.options;this.element.addClass("ui-resizable"),e.extend(this,{_aspectRatio:!!u.aspectRatio,aspectRatio:u.aspectRatio,originalElement:this.element,_proportionallyResizeElements:[],_helper:u.helper||u.ghost||u.animate?u.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("ui-resizable",this.element.data("ui-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=u.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"),t=this.handles.split(","),this.handles={};for(n=0;n<t.length;n++)r=e.trim(t[n]),s="ui-resizable-"+r,i=e("<div class='ui-resizable-handle "+s+"'></div>"),i.css({zIndex:u.zIndex}),"se"===r&&i.addClass("ui-icon ui-icon-gripsmall-diagonal-se"),this.handles[r]=".ui-resizable-"+r,this.element.append(i)}this._renderAxis=function(t){var n,r,i,s;t=t||this.element;for(n in this.handles){this.handles[n].constructor===String&&(this.handles[n]=e(this.handles[n],this.element).show()),this.elementIsWrapper&&this.originalElement[0].nodeName.match(/textarea|input|select|button/i)&&(r=e(this.handles[n],this.element),s=/sw|ne|nw|se|n|s/.test(n)?r.outerHeight():r.outerWidth(),i=["padding",/ne|nw|n/.test(n)?"Top":/se|sw|s/.test(n)?"Bottom":/^e$/.test(n)?"Right":"Left"].join(""),t.css(i,s),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(){o.resizing||(this.className&&(i=this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i)),o.axis=i&&i[1]?i[1]:"se")}),u.autoHide&&(this._handles.hide(),e(this.element).addClass("ui-resizable-autohide").mouseenter(function(){if(u.disabled)return;e(this).removeClass("ui-resizable-autohide"),o._handles.show()}).mouseleave(function(){if(u.disabled)return;o.resizing||(e(this).addClass("ui-resizable-autohide"),o._handles.hide())})),this._mouseInit()},_destroy:function(){this._mouseDestroy();var t,n=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()};return this.elementIsWrapper&&(n(this.element),t=this.element,this.originalElement.css({position:t.css("position"),width:t.outerWidth(),height:t.outerHeight(),top:t.css("top"),left:t.css("left")}).insertAfter(t),t.remove()),this.originalElement.css("resize",this.originalResizeStyle),n(this.originalElement),this},_mouseCapture:function(t){var n,r,i=!1;for(n in this.handles){r=e(this.handles[n])[0];if(r===t.target||e.contains(r,t.target))i=!0}return!this.options.disabled&&i},_mouseStart:function(t){var r,i,s,o=this.options,u=this.element.position(),a=this.element;return this.resizing=!0,/absolute/.test(a.css("position"))?a.css({position:"absolute",top:a.css("top"),left:a.css("left")}):a.is(".ui-draggable")&&a.css({position:"absolute",top:u.top,left:u.left}),this._renderProxy(),r=n(this.helper.css("left")),i=n(this.helper.css("top")),o.containment&&(r+=e(o.containment).scrollLeft()||0,i+=e(o.containment).scrollTop()||0),this.offset=this.helper.offset(),this.position={left:r,top:i},this.size=this._helper?{width:a.outerWidth(),height:a.outerHeight()}:{width:a.width(),height:a.height()},this.originalSize=this._helper?{width:a.outerWidth(),height:a.outerHeight()}:{width:a.width(),height:a.height()},this.originalPosition={left:r,top:i},this.sizeDiff={width:a.outerWidth()-a.width(),height:a.outerHeight()-a.height()},this.originalMousePosition={left:t.pageX,top:t.pageY},this.aspectRatio=typeof o.aspectRatio=="number"?o.aspectRatio:this.originalSize.width/this.originalSize.height||1,s=e(".ui-resizable-"+this.axis).css("cursor"),e("body").css("cursor",s==="auto"?this.axis+"-resize":s),a.addClass("ui-resizable-resizing"),this._propagate("start",t),!0},_mouseDrag:function(t){var n,r=this.helper,i={},s=this.originalMousePosition,o=this.axis,u=this.position.top,a=this.position.left,f=this.size.width,l=this.size.height,c=t.pageX-s.left||0,h=t.pageY-s.top||0,p=this._change[o];if(!p)return!1;n=p.apply(this,[t,c,h]),this._updateVirtualBoundaries(t.shiftKey);if(this._aspectRatio||t.shiftKey)n=this._updateRatio(n,t);return n=this._respectSize(n,t),this._updateCache(n),this._propagate("resize",t),this.position.top!==u&&(i.top=this.position.top+"px"),this.position.left!==a&&(i.left=this.position.left+"px"),this.size.width!==f&&(i.width=this.size.width+"px"),this.size.height!==l&&(i.height=this.size.height+"px"),r.css(i),!this._helper&&this._proportionallyResizeElements.length&&this._proportionallyResize(),e.isEmptyObject(i)||this._trigger("resize",t,this.ui()),!1},_mouseStop:function(t){this.resizing=!1;var n,r,i,s,o,u,a,f=this.options,l=this;return this._helper&&(n=this._proportionallyResizeElements,r=n.length&&/textarea/i.test(n[0].nodeName),i=r&&e.ui.hasScroll(n[0],"left")?0:l.sizeDiff.height,s=r?0:l.sizeDiff.width,o={width:l.helper.width()-s,height:l.helper.height()-i},u=parseInt(l.element.css("left"),10)+(l.position.left-l.originalPosition.left)||null,a=parseInt(l.element.css("top"),10)+(l.position.top-l.originalPosition.top)||null,f.animate||this.element.css(e.extend(o,{top:a,left:u})),l.helper.height(l.size.height),l.helper.width(l.size.width),this._helper&&!f.animate&&this._proportionallyResize()),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,n,i,s,o,u=this.options;o={minWidth:r(u.minWidth)?u.minWidth:0,maxWidth:r(u.maxWidth)?u.maxWidth:Infinity,minHeight:r(u.minHeight)?u.minHeight:0,maxHeight:r(u.maxHeight)?u.maxHeight:Infinity};if(this._aspectRatio||e)t=o.minHeight*this.aspectRatio,i=o.minWidth/this.aspectRatio,n=o.maxHeight*this.aspectRatio,s=o.maxWidth/this.aspectRatio,t>o.minWidth&&(o.minWidth=t),i>o.minHeight&&(o.minHeight=i),n<o.maxWidth&&(o.maxWidth=n),s<o.maxHeight&&(o.maxHeight=s);this._vBoundaries=o},_updateCache:function(e){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){var t=this.position,n=this.size,i=this.axis;return r(e.height)?e.width=e.height*this.aspectRatio:r(e.width)&&(e.height=e.width/this.aspectRatio),i==="sw"&&(e.left=t.left+(n.width-e.width),e.top=null),i==="nw"&&(e.top=t.top+(n.height-e.height),e.left=t.left+(n.width-e.width)),e},_respectSize:function(e){var t=this._vBoundaries,n=this.axis,i=r(e.width)&&t.maxWidth&&t.maxWidth<e.width,s=r(e.height)&&t.maxHeight&&t.maxHeight<e.height,o=r(e.width)&&t.minWidth&&t.minWidth>e.width,u=r(e.height)&&t.minHeight&&t.minHeight>e.height,a=this.originalPosition.left+this.originalSize.width,f=this.position.top+this.size.height,l=/sw|nw|w/.test(n),c=/nw|ne|n/.test(n);return o&&(e.width=t.minWidth),u&&(e.height=t.minHeight),i&&(e.width=t.maxWidth),s&&(e.height=t.maxHeight),o&&l&&(e.left=a-t.minWidth),i&&l&&(e.left=a-t.maxWidth),u&&c&&(e.top=f-t.minHeight),s&&c&&(e.top=f-t.maxHeight),!e.width&&!e.height&&!e.left&&e.top?e.top=null:!e.width&&!e.height&&!e.top&&e.left&&(e.left=null),e},_proportionallyResize:function(){if(!this._proportionallyResizeElements.length)return;var e,t,n,r,i,s=this.helper||this.element;for(e=0;e<this._proportionallyResizeElements.length;e++){i=this._proportionallyResizeElements[e];if(!this.borderDif){this.borderDif=[],n=[i.css("borderTopWidth"),i.css("borderRightWidth"),i.css("borderBottomWidth"),i.css("borderLeftWidth")],r=[i.css("paddingTop"),i.css("paddingRight"),i.css("paddingBottom"),i.css("paddingLeft")];for(t=0;t<n.length;t++)this.borderDif[t]=(parseInt(n[t],10)||0)+(parseInt(r[t],10)||0)}i.css({height:s.height()-this.borderDif[0]-this.borderDif[2]||0,width:s.width()-this.borderDif[1]-this.borderDif[3]||0})}},_renderProxy:function(){var t=this.element,n=this.options;this.elementOffset=t.offset(),this._helper?(this.helper=this.helper||e("<div style='overflow:hidden;'></div>"),this.helper.addClass(this._helper).css({width:this.element.outerWidth()-1,height:this.element.outerHeight()-1,position:"absolute",left:this.elementOffset.left+"px",top:this.elementOffset.top+"px",zIndex:++n.zIndex}),this.helper.appendTo("body").disableSelection()):this.helper=this.element},_change:{e:function(e,t){return{width:this.originalSize.width+t}},w:function(e,t){var n=this.originalSize,r=this.originalPosition;return{left:r.left+t,width:n.width-t}},n:function(e,t,n){var r=this.originalSize,i=this.originalPosition;return{top:i.top+n,height:r.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","animate",{stop:function(t){var n=e(this).data("ui-resizable"),r=n.options,i=n._proportionallyResizeElements,s=i.length&&/textarea/i.test(i[0].nodeName),o=s&&e.ui.hasScroll(i[0],"left")?0:n.sizeDiff.height,u=s?0:n.sizeDiff.width,a={width:n.size.width-u,height:n.size.height-o},f=parseInt(n.element.css("left"),10)+(n.position.left-n.originalPosition.left)||null,l=parseInt(n.element.css("top"),10)+(n.position.top-n.originalPosition.top)||null;n.element.animate(e.extend(a,l&&f?{top:l,left:f}:{}),{duration:r.animateDuration,easing:r.animateEasing,step:function(){var r={width:parseInt(n.element.css("width"),10),height:parseInt(n.element.css("height"),10),top:parseInt(n.element.css("top"),10),left:parseInt(n.element.css("left"),10)};i&&i.length&&e(i[0]).css({width:r.width,height:r.height}),n._updateCache(r),n._propagate("resize",t)}})}}),e.ui.plugin.add("resizable","containment",{start:function(){var t,r,i,s,o,u,a,f=e(this).data("ui-resizable"),l=f.options,c=f.element,h=l.containment,p=h instanceof e?h.get(0):/parent/.test(h)?c.parent().get(0):h;if(!p)return;f.containerElement=e(p),/document/.test(h)||h===document?(f.containerOffset={left:0,top:0},f.containerPosition={left:0,top:0},f.parentData={element:e(document),left:0,top:0,width:e(document).width(),height:e(document).height()||document.body.parentNode.scrollHeight}):(t=e(p),r=[],e(["Top","Right","Left","Bottom"]).each(function(e,i){r[e]=n(t.css("padding"+i))}),f.containerOffset=t.offset(),f.containerPosition=t.position(),f.containerSize={height:t.innerHeight()-r[3],width:t.innerWidth()-r[1]},i=f.containerOffset,s=f.containerSize.height,o=f.containerSize.width,u=e.ui.hasScroll(p,"left")?p.scrollWidth:o,a=e.ui.hasScroll(p)?p.scrollHeight:s,f.parentData={element:p,left:i.left,top:i.top,width:u,height:a})},resize:function(t){var n,r,i,s,o=e(this).data("ui-resizable"),u=o.options,a=o.containerOffset,f=o.position,l=o._aspectRatio||t.shiftKey,c={top:0,left:0},h=o.containerElement;h[0]!==document&&/static/.test(h.css("position"))&&(c=a),f.left<(o._helper?a.left:0)&&(o.size.width=o.size.width+(o._helper?o.position.left-a.left:o.position.left-c.left),l&&(o.size.height=o.size.width/o.aspectRatio),o.position.left=u.helper?a.left:0),f.top<(o._helper?a.top:0)&&(o.size.height=o.size.height+(o._helper?o.position.top-a.top:o.position.top),l&&(o.size.width=o.size.height*o.aspectRatio),o.position.top=o._helper?a.top:0),o.offset.left=o.parentData.left+o.position.left,o.offset.top=o.parentData.top+o.position.top,n=Math.abs((o._helper?o.offset.left-c.left:o.offset.left-c.left)+o.sizeDiff.width),r=Math.abs((o._helper?o.offset.top-c.top:o.offset.top-a.top)+o.sizeDiff.height),i=o.containerElement.get(0)===o.element.parent().get(0),s=/relative|absolute/.test(o.containerElement.css("position")),i&&s&&(n-=o.parentData.left),n+o.size.width>=o.parentData.width&&(o.size.width=o.parentData.width-n,l&&(o.size.height=o.size.width/o.aspectRatio)),r+o.size.height>=o.parentData.height&&(o.size.height=o.parentData.height-r,l&&(o.size.width=o.size.height*o.aspectRatio))},stop:function(){var t=e(this).data("ui-resizable"),n=t.options,r=t.containerOffset,i=t.containerPosition,s=t.containerElement,o=e(t.helper),u=o.offset(),a=o.outerWidth()-t.sizeDiff.width,f=o.outerHeight()-t.sizeDiff.height;t._helper&&!n.animate&&/relative/.test(s.css("position"))&&e(this).css({left:u.left-i.left-r.left,width:a,height:f}),t._helper&&!n.animate&&/static/.test(s.css("position"))&&e(this).css({left:u.left-i.left-r.left,width:a,height:f})}}),e.ui.plugin.add("resizable","alsoResize",{start:function(){var t=e(this).data("ui-resizable"),n=t.options,r=function(t){e(t).each(function(){var t=e(this);t.data("ui-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 n.alsoResize=="object"&&!n.alsoResize.parentNode?n.alsoResize.length?(n.alsoResize=n.alsoResize[0],r(n.alsoResize)):e.each(n.alsoResize,function(e){r(e)}):r(n.alsoResize)},resize:function(t,n){var r=e(this).data("ui-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("ui-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(){e(this).removeData("resizable-alsoresize")}}),e.ui.plugin.add("resizable","ghost",{start:function(){var t=e(this).data("ui-resizable"),n=t.options,r=t.size;t.ghost=t.originalElement.clone(),t.ghost.css({opacity:.25,display:"block",position:"relative",height:r.height,width:r.width,margin:0,left:0,top:0}).addClass("ui-resizable-ghost").addClass(typeof n.ghost=="string"?n.ghost:""),t.ghost.appendTo(t.helper)},resize:function(){var t=e(this).data("ui-resizable");t.ghost&&t.ghost.css({position:"relative",height:t.size.height,width:t.size.width})},stop:function(){var t=e(this).data("ui-resizable");t.ghost&&t.helper&&t.helper.get(0).removeChild(t.ghost.get(0))}}),e.ui.plugin.add("resizable","grid",{resize:function(){var t=e(this).data("ui-resizable"),n=t.options,r=t.size,i=t.originalSize,s=t.originalPosition,o=t.axis,u=typeof n.grid=="number"?[n.grid,n.grid]:n.grid,a=u[0]||1,f=u[1]||1,l=Math.round((r.width-i.width)/a)*a,c=Math.round((r.height-i.height)/f)*f,h=i.width+l,p=i.height+c,d=n.maxWidth&&n.maxWidth<h,v=n.maxHeight&&n.maxHeight<p,m=n.minWidth&&n.minWidth>h,g=n.minHeight&&n.minHeight>p;n.grid=u,m&&(h+=a),g&&(p+=f),d&&(h-=a),v&&(p-=f),/^(se|s|e)$/.test(o)?(t.size.width=h,t.size.height=p):/^(ne)$/.test(o)?(t.size.width=h,t.size.height=p,t.position.top=s.top-c):/^(sw)$/.test(o)?(t.size.width=h,t.size.height=p,t.position.left=s.left-l):(t.size.width=h,t.size.height=p,t.position.top=s.top-c,t.position.left=s.left-l)}})})(jQuery);(function(e,t){e.widget("ui.selectable",e.ui.mouse,{version:"1.10.0",options:{appendTo:"body",autoRefresh:!0,distance:0,filter:"*",tolerance:"touch",selected:null,selecting:null,start:null,stop:null,unselected:null,unselecting:null},_create:function(){var t,n=this;this.element.addClass("ui-selectable"),this.dragged=!1,this.refresh=function(){t=e(n.options.filter,n.element[0]),t.addClass("ui-selectee"),t.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=t.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,r=this.options;this.opos=[t.pageX,t.pageY];if(this.options.disabled)return;this.selectees=e(r.filter,this.element[0]),this._trigger("start",t),e(r.appendTo).append(this.helper),this.helper.css({left:t.pageX,top:t.pageY,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().addBack().each(function(){var r,i=e.data(this,"selectable-item");if(i)return r=!t.metaKey&&!t.ctrlKey||!i.$element.hasClass("ui-selected"),i.$element.removeClass(r?"ui-unselecting":"ui-selected").addClass(r?"ui-selecting":"ui-unselecting"),i.unselecting=!r,i.selecting=r,i.selected=r,r?n._trigger("selecting",t,{selecting:i.element}):n._trigger("unselecting",t,{unselecting:i.element}),!1})},_mouseDrag:function(t){this.dragged=!0;if(this.options.disabled)return;var n,r=this,i=this.options,s=this.opos[0],o=this.opos[1],u=t.pageX,a=t.pageY;return s>u&&(n=u,u=s,s=n),o>a&&(n=a,a=o,o=n),this.helper.css({left:s,top:o,width:u-s,height:a-o}),this.selectees.each(function(){var n=e.data(this,"selectable-item"),f=!1;if(!n||n.element===r.element[0])return;i.tolerance==="touch"?f=!(n.left>u||n.right<s||n.top>a||n.bottom<o):i.tolerance==="fit"&&(f=n.left>s&&n.right<u&&n.top>o&&n.bottom<a),f?(n.selected&&(n.$element.removeClass("ui-selected"),n.selected=!1),n.unselecting&&(n.$element.removeClass("ui-unselecting"),n.unselecting=!1),n.selecting||(n.$element.addClass("ui-selecting"),n.selecting=!0,r._trigger("selecting",t,{selecting:n.element}))):(n.selecting&&((t.metaKey||t.ctrlKey)&&n.startselected?(n.$element.removeClass("ui-selecting"),n.selecting=!1,n.$element.addClass("ui-selected"),n.selected=!0):(n.$element.removeClass("ui-selecting"),n.selecting=!1,n.startselected&&(n.$element.addClass("ui-unselecting"),n.unselecting=!0),r._trigger("unselecting",t,{unselecting:n.element}))),n.selected&&!t.metaKey&&!t.ctrlKey&&!n.startselected&&(n.$element.removeClass("ui-selected"),n.selected=!1,n.$element.addClass("ui-unselecting"),n.unselecting=!0,r._trigger("unselecting",t,{unselecting:n.element})))}),!1},_mouseStop:function(t){var n=this;return this.dragged=!1,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){function n(e,t,n){return e>t&&e<t+n}e.widget("ui.sortable",e.ui.mouse,{version:"1.10.0",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,activate:null,beforeStop:null,change:null,deactivate:null,out:null,over:null,receive:null,remove:null,sort:null,start:null,stop:null,update:null},_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=null,i=!1,s=this;if(this.reverting)return!1;if(this.options.disabled||this.options.type==="static")return!1;this._refreshItems(t),e(t.target).parents().each(function(){if(e.data(this,s.widgetName+"-item")===s)return r=e(this),!1}),e.data(t.target,s.widgetName+"-item")===s&&(r=e(t.target));if(!r)return!1;if(this.options.handle&&!n){e(this.options.handle,r).find("*").addBack().each(function(){this===t.target&&(i=!0)});if(!i)return!1}return this.currentItem=r,this._removeCurrentsFromItems(),!0},_mouseStart:function(t,n,r){var i,s=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,s.cursorAt&&this._adjustOffsetFromHelper(s.cursorAt),this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]},this.helper[0]!==this.currentItem[0]&&this.currentItem.hide(),this._createPlaceholder(),s.containment&&this._setContainment(),s.cursor&&(e("body").css("cursor")&&(this._storedCursor=e("body").css("cursor")),e("body").css("cursor",s.cursor)),s.opacity&&(this.helper.css("opacity")&&(this._storedOpacity=this.helper.css("opacity")),this.helper.css("opacity",s.opacity)),s.zIndex&&(this.helper.css("zIndex")&&(this._storedZIndex=this.helper.css("zIndex")),this.helper.css("zIndex",s.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(i=this.containers.length-1;i>=0;i--)this.containers[i]._trigger("activate",t,this._uiHash(this));return e.ui.ddmanager&&(e.ui.ddmanager.current=this),e.ui.ddmanager&&!s.dropBehaviour&&e.ui.ddmanager.prepareOffsets(this,t),this.dragging=!0,this.helper.addClass("ui-sortable-helper"),this._mouseDrag(t),!0},_mouseDrag:function(t){var n,r,i,s,o=this.options,u=!1;this.position=this._generatePosition(t),this.positionAbs=this._convertPositionTo("absolute"),this.lastPositionAbs||(this.lastPositionAbs=this.positionAbs),this.options.scroll&&(this.scrollParent[0]!==document&&this.scrollParent[0].tagName!=="HTML"?(this.overflowOffset.top+this.scrollParent[0].offsetHeight-t.pageY<o.scrollSensitivity?this.scrollParent[0].scrollTop=u=this.scrollParent[0].scrollTop+o.scrollSpeed:t.pageY-this.overflowOffset.top<o.scrollSensitivity&&(this.scrollParent[0].scrollTop=u=this.scrollParent[0].scrollTop-o.scrollSpeed),this.overflowOffset.left+this.scrollParent[0].offsetWidth-t.pageX<o.scrollSensitivity?this.scrollParent[0].scrollLeft=u=this.scrollParent[0].scrollLeft+o.scrollSpeed:t.pageX-this.overflowOffset.left<o.scrollSensitivity&&(this.scrollParent[0].scrollLeft=u=this.scrollParent[0].scrollLeft-o.scrollSpeed)):(t.pageY-e(document).scrollTop()<o.scrollSensitivity?u=e(document).scrollTop(e(document).scrollTop()-o.scrollSpeed):e(window).height()-(t.pageY-e(document).scrollTop())<o.scrollSensitivity&&(u=e(document).scrollTop(e(document).scrollTop()+o.scrollSpeed)),t.pageX-e(document).scrollLeft()<o.scrollSensitivity?u=e(document).scrollLeft(e(document).scrollLeft()-o.scrollSpeed):e(window).width()-(t.pageX-e(document).scrollLeft())<o.scrollSensitivity&&(u=e(document).scrollLeft(e(document).scrollLeft()+o.scrollSpeed))),u!==!1&&e.ui.ddmanager&&!o.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(n=this.items.length-1;n>=0;n--){r=this.items[n],i=r.item[0],s=this._intersectsWithPointer(r);if(!s)continue;if(r.instance!==this.currentContainer)continue;if(i!==this.currentItem[0]&&this.placeholder[s===1?"next":"prev"]()[0]!==i&&!e.contains(this.placeholder[0],i)&&(this.options.type==="semi-dynamic"?!e.contains(this.element[0],i):!0)){this.direction=s===1?"down":"up";if(this.options.tolerance!=="pointer"&&!this._intersectsWithSides(r))break;this._rearrange(t,r),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(e){var t=this.options.axis==="x"||n(this.positionAbs.top+this.offset.click.top,e.top,e.height),r=this.options.axis==="y"||n(this.positionAbs.left+this.offset.click.left,e.left,e.width),i=t&&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(e){var t=n(this.positionAbs.top+this.offset.click.top,e.top+e.height/2,e.height),r=n(this.positionAbs.left+this.offset.click.left,e.left+e.width/2,e.width),i=this._getDragVerticalDirection(),s=this._getDragHorizontalDirection();return this.floating&&s?s==="right"&&r||s==="left"&&!r:i&&(i==="down"&&t||i==="up"&&!t)},_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,s,o=[],u=[],a=this._connectWith();if(a&&t)for(n=a.length-1;n>=0;n--){i=e(a[n]);for(r=i.length-1;r>=0;r--)s=e.data(i[r],this.widgetFullName),s&&s!==this&&!s.options.disabled&&u.push([e.isFunction(s.options.items)?s.options.items.call(s.element):e(s.options.items,s.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),s])}u.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(n=u.length-1;n>=0;n--)u[n][0].each(function(){o.push(this)});return e(o)},_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,r,i,s,o,u,a,f,l=this.items,c=[[e.isFunction(this.options.items)?this.options.items.call(this.element[0],t,{item:this.currentItem}):e(this.options.items,this.element),this]],h=this._connectWith();if(h&&this.ready)for(n=h.length-1;n>=0;n--){i=e(h[n]);for(r=i.length-1;r>=0;r--)s=e.data(i[r],this.widgetFullName),s&&s!==this&&!s.options.disabled&&(c.push([e.isFunction(s.options.items)?s.options.items.call(s.element[0],t,{item:this.currentItem}):e(s.options.items,s.element),s]),this.containers.push(s))}for(n=c.length-1;n>=0;n--){o=c[n][1],u=c[n][0];for(r=0,f=u.length;r<f;r++)a=e(u[r]),a.data(this.widgetName+"-item",o),l.push({item:a,instance:o,width:0,height:0,left:0,top:0})}},refreshPositions:function(t){this.offsetParent&&this.helper&&(this.offset.parent=this._getParentOffset());var n,r,i,s;for(n=this.items.length-1;n>=0;n--){r=this.items[n];if(r.instance!==this.currentContainer&&this.currentContainer&&r.item[0]!==this.currentItem[0])continue;i=this.options.toleranceElement?e(this.options.toleranceElement,r.item):r.item,t||(r.width=i.outerWidth(),r.height=i.outerHeight()),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(n=this.containers.length-1;n>=0;n--)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,r=t.options;if(!r.placeholder||r.placeholder.constructor===String)n=r.placeholder,r.placeholder={element:function(){var r=e(document.createElement(t.currentItem[0].nodeName)).addClass(n||t.currentItem[0].className+" ui-sortable-placeholder").removeClass("ui-sortable-helper")[0];return n||(r.style.visibility="hidden"),r},update:function(e,i){if(n&&!r.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(r.placeholder.element.call(t.element,t.currentItem)),t.currentItem.after(t.placeholder),r.placeholder.update(t,t.placeholder)},_contactContainers:function(t){var n,r,i,s,o,u,a,f,l,c=null,h=null;for(n=this.containers.length-1;n>=0;n--){if(e.contains(this.currentItem[0],this.containers[n].element[0]))continue;if(this._intersectsWith(this.containers[n].containerCache)){if(c&&e.contains(this.containers[n].element[0],c.element[0]))continue;c=this.containers[n],h=n}else this.containers[n].containerCache.over&&(this.containers[n]._trigger("out",t,this._uiHash(this)),this.containers[n].containerCache.over=0)}if(!c)return;if(this.containers.length===1)this.containers[h]._trigger("over",t,this._uiHash(this)),this.containers[h].containerCache.over=1;else{i=1e4,s=null,o=this.containers[h].floating?"left":"top",u=this.containers[h].floating?"width":"height",a=this.positionAbs[o]+this.offset.click[o];for(r=this.items.length-1;r>=0;r--){if(!e.contains(this.containers[h].element[0],this.items[r].item[0]))continue;if(this.items[r].item[0]===this.currentItem[0])continue;f=this.items[r].item.offset()[o],l=!1,Math.abs(f-a)>Math.abs(f+this.items[r][u]-a)&&(l=!0,f+=this.items[r][u]),Math.abs(f-a)<i&&(i=Math.abs(f-a),s=this.items[r],this.direction=l?"up":"down")}if(!s&&!this.options.dropOnEmpty)return;this.currentContainer=this.containers[h],s?this._rearrange(t,s,null,!0):this._rearrange(t,null,this.containers[h].element,!0),this._trigger("change",t,this._uiHash()),this.containers[h]._trigger("change",t,this._uiHash(this)),this.options.placeholder.update(this.currentContainer,this.placeholder),this.containers[h]._trigger("over",t,this._uiHash(this)),this.containers[h].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,n,r,i=this.options;i.containment==="parent"&&(i.containment=this.helper[0].parentNode);if(i.containment==="document"||i.containment==="window")this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,e(i.containment==="document"?document:window).width()-this.helperProportions.width-this.margins.left,(e(i.containment==="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top];/^(document|window|parent)$/.test(i.containment)||(t=e(i.containment)[0],n=e(i.containment).offset(),r=e(t).css("overflow")!=="hidden",this.containment=[n.left+(parseInt(e(t).css("borderLeftWidth"),10)||0)+(parseInt(e(t).css("paddingLeft"),10)||0)-this.margins.left,n.top+(parseInt(e(t).css("borderTopWidth"),10)||0)+(parseInt(e(t).css("paddingTop"),10)||0)-this.margins.top,n.left+(r?Math.max(t.scrollWidth,t.offsetWidth):t.offsetWidth)-(parseInt(e(t).css("borderLeftWidth"),10)||0)-(parseInt(e(t).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,n.top+(r?Math.max(t.scrollHeight,t.offsetHeight):t.offsetHeight)-(parseInt(e(t).css("borderTopWidth"),10)||0)-(parseInt(e(t).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.cssPosition!=="absolute"||this.scrollParent[0]!==document&&!!e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,s=/(html|body)/i.test(i[0].tagName);return{top:n.top+this.offset.relative.top*r+this.offset.parent.top*r-(this.cssPosition==="fixed"?-this.scrollParent.scrollTop():s?0:i.scrollTop())*r,left:n.left+this.offset.relative.left*r+this.offset.parent.left*r-(this.cssPosition==="fixed"?-this.scrollParent.scrollLeft():s?0:i.scrollLeft())*r}},_generatePosition:function(t){var n,r,i=this.options,s=t.pageX,o=t.pageY,u=this.cssPosition!=="absolute"||this.scrollParent[0]!==document&&!!e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,a=/(html|body)/i.test(u[0].tagName);return this.cssPosition==="relative"&&(this.scrollParent[0]===document||this.scrollParent[0]===this.offsetParent[0])&&(this.offset.relative=this._getRelativeOffset()),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)),i.grid&&(n=this.originalPageY+Math.round((o-this.originalPageY)/i.grid[1])*i.grid[1],o=this.containment?n-this.offset.click.top>=this.containment[1]&&n-this.offset.click.top<=this.containment[3]?n:n-this.offset.click.top>=this.containment[1]?n-i.grid[1]:n+i.grid[1]:n,r=this.originalPageX+Math.round((s-this.originalPageX)/i.grid[0])*i.grid[0],s=this.containment?r-this.offset.click.left>=this.containment[0]&&r-this.offset.click.left<=this.containment[2]?r:r-this.offset.click.left>=this.containment[0]?r-i.grid[0]:r+i.grid[0]:r)),{top:o-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(this.cssPosition==="fixed"?-this.scrollParent.scrollTop():a?0:u.scrollTop()),left:s-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(this.cssPosition==="fixed"?-this.scrollParent.scrollLeft():a?0:u.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,i=[];!this._noFinalSort&&this.currentItem.parent().length&&this.placeholder.before(this.currentItem),this._noFinalSort=null;if(this.helper[0]===this.currentItem[0]){for(r in this._storedCSS)if(this._storedCSS[r]==="auto"||this._storedCSS[r]==="static")this._storedCSS[r]="";this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else this.currentItem.show();this.fromOutside&&!n&&i.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&&i.push(function(e){this._trigger("update",e,this._uiHash())}),this!==this.currentContainer&&(n||(i.push(function(e){this._trigger("remove",e,this._uiHash())}),i.push(function(e){return function(t){e._trigger("receive",t,this._uiHash(this))}}.call(this,this.currentContainer)),i.push(function(e){return function(t){e._trigger("update",t,this._uiHash(this))}}.call(this,this.currentContainer))));for(r=this.containers.length-1;r>=0;r--)n||i.push(function(e){return function(t){e._trigger("deactivate",t,this._uiHash(this))}}.call(this,this.containers[r])),this.containers[r].containerCache.over&&(i.push(function(e){return function(t){e._trigger("out",t,this._uiHash(this))}}.call(this,this.containers[r])),this.containers[r].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(r=0;r<i.length;r++)i[r].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(r=0;r<i.length;r++)i[r].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);(function(e,t){var n=0,r={},i={};r.height=r.paddingTop=r.paddingBottom=r.borderTopWidth=r.borderBottomWidth="hide",i.height=i.paddingTop=i.paddingBottom=i.borderTopWidth=i.borderBottomWidth="show",e.widget("ui.accordion",{version:"1.10.0",options:{active:0,animate:{},collapsible:!1,event:"click",header:"> li > :first-child,> :not(li):even",heightStyle:"auto",icons:{activeHeader:"ui-icon-triangle-1-s",header:"ui-icon-triangle-1-e"},activate:null,beforeActivate:null},_create:function(){var t=this.options;this.prevShow=this.prevHide=e(),this.element.addClass("ui-accordion ui-widget ui-helper-reset").attr("role","tablist"),!t.collapsible&&(t.active===!1||t.active==null)&&(t.active=0),this._processPanels(),t.active<0&&(t.active+=this.headers.length),this._refresh()},_getCreateEventData:function(){return{header:this.active,content:this.active.length?this.active.next():e()}},_createIcons:function(){var t=this.options.icons;t&&(e("<span>").addClass("ui-accordion-header-icon ui-icon "+t.header).prependTo(this.headers),this.active.children(".ui-accordion-header-icon").removeClass(t.header).addClass(t.activeHeader),this.headers.addClass("ui-accordion-icons"))},_destroyIcons:function(){this.headers.removeClass("ui-accordion-icons").children(".ui-accordion-header-icon").remove()},_destroy:function(){var e;this.element.removeClass("ui-accordion ui-widget ui-helper-reset").removeAttr("role"),this.headers.removeClass("ui-accordion-header ui-accordion-header-active ui-helper-reset ui-state-default ui-corner-all ui-state-active ui-state-disabled ui-corner-top").removeAttr("role").removeAttr("aria-selected").removeAttr("aria-controls").removeAttr("tabIndex").each(function(){/^ui-accordion/.test(this.id)&&this.removeAttribute("id")}),this._destroyIcons(),e=this.headers.next().css("display","").removeAttr("role").removeAttr("aria-expanded").removeAttr("aria-hidden").removeAttr("aria-labelledby").removeClass("ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content ui-accordion-content-active ui-state-disabled").each(function(){/^ui-accordion/.test(this.id)&&this.removeAttribute("id")}),this.options.heightStyle!=="content"&&e.css("height","")},_setOption:function(e,t){if(e==="active"){this._activate(t);return}e==="event"&&(this.options.event&&this._off(this.headers,this.options.event),this._setupEvents(t)),this._super(e,t),e==="collapsible"&&!t&&this.options.active===!1&&this._activate(0),e==="icons"&&(this._destroyIcons(),t&&this._createIcons()),e==="disabled"&&this.headers.add(this.headers.next()).toggleClass("ui-state-disabled",!!t)},_keydown:function(t){if(t.altKey||t.ctrlKey)return;var n=e.ui.keyCode,r=this.headers.length,i=this.headers.index(t.target),s=!1;switch(t.keyCode){case n.RIGHT:case n.DOWN:s=this.headers[(i+1)%r];break;case n.LEFT:case n.UP:s=this.headers[(i-1+r)%r];break;case n.SPACE:case n.ENTER:this._eventHandler(t);break;case n.HOME:s=this.headers[0];break;case n.END:s=this.headers[r-1]}s&&(e(t.target).attr("tabIndex",-1),e(s).attr("tabIndex",0),s.focus(),t.preventDefault())},_panelKeyDown:function(t){t.keyCode===e.ui.keyCode.UP&&t.ctrlKey&&e(t.currentTarget).prev().focus()},refresh:function(){var t=this.options;this._processPanels();if(t.active===!1&&t.collapsible===!0||!this.headers.length)t.active=!1,this.active=e();t.active===!1?this._activate(0):this.active.length&&!e.contains(this.element[0],this.active[0])?this.headers.length===this.headers.find(".ui-state-disabled").length?(t.active=!1,this.active=e()):this._activate(Math.max(0,t.active-1)):t.active=this.headers.index(this.active),this._destroyIcons(),this._refresh()},_processPanels:function(){this.headers=this.element.find(this.options.header).addClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-all"),this.headers.next().addClass("ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom").filter(":not(.ui-accordion-content-active)").hide()},_refresh:function(){var t,r=this.options,i=r.heightStyle,s=this.element.parent(),o=this.accordionId="ui-accordion-"+(this.element.attr("id")||++n);this.active=this._findActive(r.active).addClass("ui-accordion-header-active ui-state-active").toggleClass("ui-corner-all ui-corner-top"),this.active.next().addClass("ui-accordion-content-active").show(),this.headers.attr("role","tab").each(function(t){var n=e(this),r=n.attr("id"),i=n.next(),s=i.attr("id");r||(r=o+"-header-"+t,n.attr("id",r)),s||(s=o+"-panel-"+t,i.attr("id",s)),n.attr("aria-controls",s),i.attr("aria-labelledby",r)}).next().attr("role","tabpanel"),this.headers.not(this.active).attr({"aria-selected":"false",tabIndex:-1}).next().attr({"aria-expanded":"false","aria-hidden":"true"}).hide(),this.active.length?this.active.attr({"aria-selected":"true",tabIndex:0}).next().attr({"aria-expanded":"true","aria-hidden":"false"}):this.headers.eq(0).attr("tabIndex",0),this._createIcons(),this._setupEvents(r.event),i==="fill"?(t=s.height(),this.element.siblings(":visible").each(function(){var n=e(this),r=n.css("position");if(r==="absolute"||r==="fixed")return;t-=n.outerHeight(!0)}),this.headers.each(function(){t-=e(this).outerHeight(!0)}),this.headers.next().each(function(){e(this).height(Math.max(0,t-e(this).innerHeight()+e(this).height()))}).css("overflow","auto")):i==="auto"&&(t=0,this.headers.next().each(function(){t=Math.max(t,e(this).css("height","").height())}).height(t))},_activate:function(t){var n=this._findActive(t)[0];if(n===this.active[0])return;n=n||this.active[0],this._eventHandler({target:n,currentTarget:n,preventDefault:e.noop})},_findActive:function(t){return typeof t=="number"?this.headers.eq(t):e()},_setupEvents:function(t){var n={keydown:"_keydown"};t&&e.each(t.split(" "),function(e,t){n[t]="_eventHandler"}),this._off(this.headers.add(this.headers.next())),this._on(this.headers,n),this._on(this.headers.next(),{keydown:"_panelKeyDown"}),this._hoverable(this.headers),this._focusable(this.headers)},_eventHandler:function(t){var n=this.options,r=this.active,i=e(t.currentTarget),s=i[0]===r[0],o=s&&n.collapsible,u=o?e():i.next(),a=r.next(),f={oldHeader:r,oldPanel:a,newHeader:o?e():i,newPanel:u};t.preventDefault();if(s&&!n.collapsible||this._trigger("beforeActivate",t,f)===!1)return;n.active=o?!1:this.headers.index(i),this.active=s?e():i,this._toggle(f),r.removeClass("ui-accordion-header-active ui-state-active"),n.icons&&r.children(".ui-accordion-header-icon").removeClass(n.icons.activeHeader).addClass(n.icons.header),s||(i.removeClass("ui-corner-all").addClass("ui-accordion-header-active ui-state-active ui-corner-top"),n.icons&&i.children(".ui-accordion-header-icon").removeClass(n.icons.header).addClass(n.icons.activeHeader),i.next().addClass("ui-accordion-content-active"))},_toggle:function(t){var n=t.newPanel,r=this.prevShow.length?this.prevShow:t.oldPanel;this.prevShow.add(this.prevHide).stop(!0,!0),this.prevShow=n,this.prevHide=r,this.options.animate?this._animate(n,r,t):(r.hide(),n.show(),this._toggleComplete(t)),r.attr({"aria-expanded":"false","aria-hidden":"true"}),r.prev().attr("aria-selected","false"),n.length&&r.length?r.prev().attr("tabIndex",-1):n.length&&this.headers.filter(function(){return e(this).attr("tabIndex")===0}).attr("tabIndex",-1),n.attr({"aria-expanded":"true","aria-hidden":"false"}).prev().attr({"aria-selected":"true",tabIndex:0})},_animate:function(e,t,n){var s,o,u,a=this,f=0,l=e.length&&(!t.length||e.index()<t.index()),c=this.options.animate||{},h=l&&c.down||c,p=function(){a._toggleComplete(n)};typeof h=="number"&&(u=h),typeof h=="string"&&(o=h),o=o||h.easing||c.easing,u=u||h.duration||c.duration;if(!t.length)return e.animate(i,u,o,p);if(!e.length)return t.animate(r,u,o,p);s=e.show().outerHeight(),t.animate(r,{duration:u,easing:o,step:function(e,t){t.now=Math.round(e)}}),e.hide().animate(i,{duration:u,easing:o,complete:p,step:function(e,n){n.now=Math.round(e),n.prop!=="height"?f+=n.now:a.options.heightStyle!=="content"&&(n.now=Math.round(s-t.outerHeight()-f),f=0)}})},_toggleComplete:function(e){var t=e.oldPanel;t.removeClass("ui-accordion-content-active").prev().removeClass("ui-corner-top").addClass("ui-corner-all"),t.length&&(t.parent()[0].className=t.parent()[0].className),this._trigger("activate",null,e)}})})(jQuery);(function(e,t){var n=0;e.widget("ui.autocomplete",{version:"1.10.0",defaultElement:"<input>",options:{appendTo:null,autoFocus:!1,delay:300,minLength:1,position:{my:"left top",at:"left bottom",collision:"none"},source:null,change:null,close:null,focus:null,open:null,response:null,search:null,select:null},pending:0,_create:function(){var t,n,r;this.isMultiLine=this._isMultiLine(),this.valueMethod=this.element[this.element.is("input,textarea")?"val":"text"],this.isNewMenu=!0,this.element.addClass("ui-autocomplete-input").attr("autocomplete","off"),this._on(this.element,{keydown:function(i){if(this.element.prop("readOnly")){t=!0,r=!0,n=!0;return}t=!1,r=!1,n=!1;var s=e.ui.keyCode;switch(i.keyCode){case s.PAGE_UP:t=!0,this._move("previousPage",i);break;case s.PAGE_DOWN:t=!0,this._move("nextPage",i);break;case s.UP:t=!0,this._keyEvent("previous",i);break;case s.DOWN:t=!0,this._keyEvent("next",i);break;case s.ENTER:case s.NUMPAD_ENTER:this.menu.active&&(t=!0,i.preventDefault(),this.menu.select(i));break;case s.TAB:this.menu.active&&this.menu.select(i);break;case s.ESCAPE:this.menu.element.is(":visible")&&(this._value(this.term),this.close(i),i.preventDefault());break;default:n=!0,this._searchTimeout(i)}},keypress:function(r){if(t){t=!1,r.preventDefault();return}if(n)return;var i=e.ui.keyCode;switch(r.keyCode){case i.PAGE_UP:this._move("previousPage",r);break;case i.PAGE_DOWN:this._move("nextPage",r);break;case i.UP:this._keyEvent("previous",r);break;case i.DOWN:this._keyEvent("next",r)}},input:function(e){if(r){r=!1,e.preventDefault();return}this._searchTimeout(e)},focus:function(){this.selectedItem=null,this.previous=this._value()},blur:function(e){if(this.cancelBlur){delete this.cancelBlur;return}clearTimeout(this.searching),this.close(e),this._change(e)}}),this._initSource(),this.menu=e("<ul>").addClass("ui-autocomplete").appendTo(this._appendTo()).menu({input:e(),role:null}).zIndex(this.element.zIndex()+1).hide().data("ui-menu"),this._on(this.menu.element,{mousedown:function(t){t.preventDefault(),this.cancelBlur=!0,this._delay(function(){delete this.cancelBlur});var n=this.menu.element[0];e(t.target).closest(".ui-menu-item").length||this._delay(function(){var t=this;this.document.one("mousedown",function(r){r.target!==t.element[0]&&r.target!==n&&!e.contains(n,r.target)&&t.close()})})},menufocus:function(t,n){if(this.isNewMenu){this.isNewMenu=!1;if(t.originalEvent&&/^mouse/.test(t.originalEvent.type)){this.menu.blur(),this.document.one("mousemove",function(){e(t.target).trigger(t.originalEvent)});return}}var r=n.item.data("ui-autocomplete-item");!1!==this._trigger("focus",t,{item:r})?t.originalEvent&&/^key/.test(t.originalEvent.type)&&this._value(r.value):this.liveRegion.text(r.value)},menuselect:function(e,t){var n=t.item.data("ui-autocomplete-item"),r=this.previous;this.element[0]!==this.document[0].activeElement&&(this.element.focus(),this.previous=r,this._delay(function(){this.previous=r,this.selectedItem=n})),!1!==this._trigger("select",e,{item:n})&&this._value(n.value),this.term=this._value(),this.close(e),this.selectedItem=n}}),this.liveRegion=e("<span>",{role:"status","aria-live":"polite"}).addClass("ui-helper-hidden-accessible").insertAfter(this.element),this._on(this.window,{beforeunload:function(){this.element.removeAttr("autocomplete")}})},_destroy:function(){clearTimeout(this.searching),this.element.removeClass("ui-autocomplete-input").removeAttr("autocomplete"),this.menu.element.remove(),this.liveRegion.remove()},_setOption:function(e,t){this._super(e,t),e==="source"&&this._initSource(),e==="appendTo"&&this.menu.element.appendTo(this._appendTo()),e==="disabled"&&t&&this.xhr&&this.xhr.abort()},_appendTo:function(){var t=this.options.appendTo;return t&&(t=t.jquery||t.nodeType?e(t):this.document.find(t).eq(0)),t||(t=this.element.closest(".ui-front")),t.length||(t=this.document[0].body),t},_isMultiLine:function(){return this.element.is("textarea")?!0:this.element.is("input")?!1:this.element.prop("isContentEditable")},_initSource:function(){var t,n,r=this;e.isArray(this.options.source)?(t=this.options.source,this.source=function(n,r){r(e.ui.autocomplete.filter(t,n.term))}):typeof this.options.source=="string"?(n=this.options.source,this.source=function(t,i){r.xhr&&r.xhr.abort(),r.xhr=e.ajax({url:n,data:t,dataType:"json",success:function(e){i(e)},error:function(){i([])}})}):this.source=this.options.source},_searchTimeout:function(e){clearTimeout(this.searching),this.searching=this._delay(function(){this.term!==this._value()&&(this.selectedItem=null,this.search(null,e))},this.options.delay)},search:function(e,t){e=e!=null?e:this._value(),this.term=this._value();if(e.length<this.options.minLength)return this.close(t);if(this._trigger("search",t)===!1)return;return this._search(e)},_search:function(e){this.pending++,this.element.addClass("ui-autocomplete-loading"),this.cancelSearch=!1,this.source({term:e},this._response())},_response:function(){var e=this,t=++n;return function(r){t===n&&e.__response(r),e.pending--,e.pending||e.element.removeClass("ui-autocomplete-loading")}},__response:function(e){e&&(e=this._normalize(e)),this._trigger("response",null,{content:e}),!this.options.disabled&&e&&e.length&&!this.cancelSearch?(this._suggest(e),this._trigger("open")):this._close()},close:function(e){this.cancelSearch=!0,this._close(e)},_close:function(e){this.menu.element.is(":visible")&&(this.menu.element.hide(),this.menu.blur(),this.isNewMenu=!0,this._trigger("close",e))},_change:function(e){this.previous!==this._value()&&this._trigger("change",e,{item:this.selectedItem})},_normalize:function(t){return t.length&&t[0].label&&t[0].value?t:e.map(t,function(t){return typeof t=="string"?{label:t,value:t}:e.extend({label:t.label||t.value,value:t.value||t.label},t)})},_suggest:function(t){var n=this.menu.element.empty().zIndex(this.element.zIndex()+1);this._renderMenu(n,t),this.menu.refresh(),n.show(),this._resizeMenu(),n.position(e.extend({of:this.element},this.options.position)),this.options.autoFocus&&this.menu.next()},_resizeMenu:function(){var e=this.menu.element;e.outerWidth(Math.max(e.width("").outerWidth()+1,this.element.outerWidth()))},_renderMenu:function(t,n){var r=this;e.each(n,function(e,n){r._renderItemData(t,n)})},_renderItemData:function(e,t){return this._renderItem(e,t).data("ui-autocomplete-item",t)},_renderItem:function(t,n){return e("<li>").append(e("<a>").text(n.label)).appendTo(t)},_move:function(e,t){if(!this.menu.element.is(":visible")){this.search(null,t);return}if(this.menu.isFirstItem()&&/^previous/.test(e)||this.menu.isLastItem()&&/^next/.test(e)){this._value(this.term),this.menu.blur();return}this.menu[e](t)},widget:function(){return this.menu.element},_value:function(){return this.valueMethod.apply(this.element,arguments)},_keyEvent:function(e,t){if(!this.isMultiLine||this.menu.element.is(":visible"))this._move(e,t),t.preventDefault()}}),e.extend(e.ui.autocomplete,{escapeRegex:function(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")},filter:function(t,n){var r=new RegExp(e.ui.autocomplete.escapeRegex(n),"i");return e.grep(t,function(e){return r.test(e.label||e.value||e)})}}),e.widget("ui.autocomplete",e.ui.autocomplete,{options:{messages:{noResults:"No search results.",results:function(e){return e+(e>1?" results are":" result is")+" available, use up and down arrow keys to navigate."}}},__response:function(e){var t;this._superApply(arguments);if(this.options.disabled||this.cancelSearch)return;e&&e.length?t=this.options.messages.results(e.length):t=this.options.messages.noResults,this.liveRegion.text(t)}})})(jQuery);(function(e,t){var n,r,i,s,o="ui-button ui-widget ui-state-default ui-corner-all",u="ui-state-hover ui-state-active ",a="ui-button-icons-only ui-button-icon-only ui-button-text-icons ui-button-text-icon-primary ui-button-text-icon-secondary ui-button-text-only",f=function(){var t=e(this).find(":ui-button");setTimeout(function(){t.button("refresh")},1)},l=function(t){var n=t.name,r=t.form,i=e([]);return n&&(n=n.replace(/'/g,"\\'"),r?i=e(r).find("[name='"+n+"']"):i=e("[name='"+n+"']",t.ownerDocument).filter(function(){return!this.form})),i};e.widget("ui.button",{version:"1.10.0",defaultElement:"<button>",options:{disabled:null,text:!0,label:null,icons:{primary:null,secondary:null}},_create:function(){this.element.closest("form").unbind("reset"+this.eventNamespace).bind("reset"+this.eventNamespace,f),typeof this.options.disabled!="boolean"?this.options.disabled=!!this.element.prop("disabled"):this.element.prop("disabled",this.options.disabled),this._determineButtonType(),this.hasTitle=!!this.buttonElement.attr("title");var t=this,u=this.options,a=this.type==="checkbox"||this.type==="radio",c=a?"":"ui-state-active",h="ui-state-focus";u.label===null&&(u.label=this.type==="input"?this.buttonElement.val():this.buttonElement.html()),this._hoverable(this.buttonElement),this.buttonElement.addClass(o).attr("role","button").bind("mouseenter"+this.eventNamespace,function(){if(u.disabled)return;this===n&&e(this).addClass("ui-state-active")}).bind("mouseleave"+this.eventNamespace,function(){if(u.disabled)return;e(this).removeClass(c)}).bind("click"+this.eventNamespace,function(e){u.disabled&&(e.preventDefault(),e.stopImmediatePropagation())}),this.element.bind("focus"+this.eventNamespace,function(){t.buttonElement.addClass(h)}).bind("blur"+this.eventNamespace,function(){t.buttonElement.removeClass(h)}),a&&(this.element.bind("change"+this.eventNamespace,function(){if(s)return;t.refresh()}),this.buttonElement.bind("mousedown"+this.eventNamespace,function(e){if(u.disabled)return;s=!1,r=e.pageX,i=e.pageY}).bind("mouseup"+this.eventNamespace,function(e){if(u.disabled)return;if(r!==e.pageX||i!==e.pageY)s=!0})),this.type==="checkbox"?this.buttonElement.bind("click"+this.eventNamespace,function(){if(u.disabled||s)return!1}):this.type==="radio"?this.buttonElement.bind("click"+this.eventNamespace,function(){if(u.disabled||s)return!1;e(this).addClass("ui-state-active"),t.buttonElement.attr("aria-pressed","true");var n=t.element[0];l(n).not(n).map(function(){return e(this).button("widget")[0]}).removeClass("ui-state-active").attr("aria-pressed","false")}):(this.buttonElement.bind("mousedown"+this.eventNamespace,function(){if(u.disabled)return!1;e(this).addClass("ui-state-active"),n=this,t.document.one("mouseup",function(){n=null})}).bind("mouseup"+this.eventNamespace,function(){if(u.disabled)return!1;e(this).removeClass("ui-state-active")}).bind("keydown"+this.eventNamespace,function(t){if(u.disabled)return!1;(t.keyCode===e.ui.keyCode.SPACE||t.keyCode===e.ui.keyCode.ENTER)&&e(this).addClass("ui-state-active")}).bind("keyup"+this.eventNamespace+" blur"+this.eventNamespace,function(){e(this).removeClass("ui-state-active")}),this.buttonElement.is("a")&&this.buttonElement.keyup(function(t){t.keyCode===e.ui.keyCode.SPACE&&e(this).click()})),this._setOption("disabled",u.disabled),this._resetButton()},_determineButtonType:function(){var e,t,n;this.element.is("[type=checkbox]")?this.type="checkbox":this.element.is("[type=radio]")?this.type="radio":this.element.is("input")?this.type="input":this.type="button",this.type==="checkbox"||this.type==="radio"?(e=this.element.parents().last(),t="label[for='"+this.element.attr("id")+"']",this.buttonElement=e.find(t),this.buttonElement.length||(e=e.length?e.siblings():this.element.siblings(),this.buttonElement=e.filter(t),this.buttonElement.length||(this.buttonElement=e.find(t))),this.element.addClass("ui-helper-hidden-accessible"),n=this.element.is(":checked"),n&&this.buttonElement.addClass("ui-state-active"),this.buttonElement.prop("aria-pressed",n)):this.buttonElement=this.element},widget:function(){return this.buttonElement},_destroy:function(){this.element.removeClass("ui-helper-hidden-accessible"),this.buttonElement.removeClass(o+" "+u+" "+a).removeAttr("role").removeAttr("aria-pressed").html(this.buttonElement.find(".ui-button-text").html()),this.hasTitle||this.buttonElement.removeAttr("title")},_setOption:function(e,t){this._super(e,t);if(e==="disabled"){t?this.element.prop("disabled",!0):this.element.prop("disabled",!1);return}this._resetButton()},refresh:function(){var t=this.element.is("input, button")?this.element.is(":disabled"):this.element.hasClass("ui-button-disabled");t!==this.options.disabled&&this._setOption("disabled",t),this.type==="radio"?l(this.element[0]).each(function(){e(this).is(":checked")?e(this).button("widget").addClass("ui-state-active").attr("aria-pressed","true"):e(this).button("widget").removeClass("ui-state-active").attr("aria-pressed","false")}):this.type==="checkbox"&&(this.element.is(":checked")?this.buttonElement.addClass("ui-state-active").attr("aria-pressed","true"):this.buttonElement.removeClass("ui-state-active").attr("aria-pressed","false"))},_resetButton:function(){if(this.type==="input"){this.options.label&&this.element.val(this.options.label);return}var t=this.buttonElement.removeClass(a),n=e("<span></span>",this.document[0]).addClass("ui-button-text").html(this.options.label).appendTo(t.empty()).text(),r=this.options.icons,i=r.primary&&r.secondary,s=[];r.primary||r.secondary?(this.options.text&&s.push("ui-button-text-icon"+(i?"s":r.primary?"-primary":"-secondary")),r.primary&&t.prepend("<span class='ui-button-icon-primary ui-icon "+r.primary+"'></span>"),r.secondary&&t.append("<span class='ui-button-icon-secondary ui-icon "+r.secondary+"'></span>"),this.options.text||(s.push(i?"ui-button-icons-only":"ui-button-icon-only"),this.hasTitle||t.attr("title",e.trim(n)))):s.push("ui-button-text-only"),t.addClass(s.join(" "))}}),e.widget("ui.buttonset",{version:"1.10.0",options:{items:"button, input[type=button], input[type=submit], input[type=reset], input[type=checkbox], input[type=radio], a, :data(ui-button)"},_create:function(){this.element.addClass("ui-buttonset")},_init:function(){this.refresh()},_setOption:function(e,t){e==="disabled"&&this.buttons.button("option",e,t),this._super(e,t)},refresh:function(){var t=this.element.css("direction")==="rtl";this.buttons=this.element.find(this.options.items).filter(":ui-button").button("refresh").end().not(":ui-button").button().end().map(function(){return e(this).button("widget")[0]}).removeClass("ui-corner-all ui-corner-left ui-corner-right").filter(":first").addClass(t?"ui-corner-right":"ui-corner-left").end().filter(":last").addClass(t?"ui-corner-left":"ui-corner-right").end().end()},_destroy:function(){this.element.removeClass("ui-buttonset"),this.buttons.map(function(){return e(this).button("widget")[0]}).removeClass("ui-corner-left ui-corner-right").end().button("destroy")}})})(jQuery);(function(e,t){function n(){this._curInst=null,this._keyEvent=!1,this._disabledInputs=[],this._datepickerShowing=!1,this._inDialog=!1,this._mainDivId="ui-datepicker-div",this._inlineClass="ui-datepicker-inline",this._appendClass="ui-datepicker-append",this._triggerClass="ui-datepicker-trigger",this._dialogClass="ui-datepicker-dialog",this._disableClass="ui-datepicker-disabled",this._unselectableClass="ui-datepicker-unselectable",this._currentClass="ui-datepicker-current-day",this._dayOverClass="ui-datepicker-days-cell-over",this.regional=[],this.regional[""]={closeText:"Done",prevText:"Prev",nextText:"Next",currentText:"Today",monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["Su","Mo","Tu","We","Th","Fr","Sa"],weekHeader:"Wk",dateFormat:"mm/dd/yy",firstDay:0,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},this._defaults={showOn:"focus",showAnim:"fadeIn",showOptions:{},defaultDate:null,appendText:"",buttonText:"...",buttonImage:"",buttonImageOnly:!1,hideIfNoPrevNext:!1,navigationAsDateFormat:!1,gotoCurrent:!1,changeMonth:!1,changeYear:!1,yearRange:"c-10:c+10",showOtherMonths:!1,selectOtherMonths:!1,showWeek:!1,calculateWeek:this.iso8601Week,shortYearCutoff:"+10",minDate:null,maxDate:null,duration:"fast",beforeShowDay:null,beforeShow:null,onSelect:null,onChangeMonthYear:null,onClose:null,numberOfMonths:1,showCurrentAtPos:0,stepMonths:1,stepBigMonths:12,altField:"",altFormat:"",constrainInput:!0,showButtonPanel:!1,autoSize:!1,disabled:!1},e.extend(this._defaults,this.regional[""]),this.dpDiv=r(e("<div id='"+this._mainDivId+"' class='ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>"))}function r(t){var n="button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";return t.delegate(n,"mouseout",function(){e(this).removeClass("ui-state-hover"),this.className.indexOf("ui-datepicker-prev")!==-1&&e(this).removeClass("ui-datepicker-prev-hover"),this.className.indexOf("ui-datepicker-next")!==-1&&e(this).removeClass("ui-datepicker-next-hover")}).delegate(n,"mouseover",function(){e.datepicker._isDisabledDatepicker(u.inline?t.parent()[0]:u.input[0])||(e(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover"),e(this).addClass("ui-state-hover"),this.className.indexOf("ui-datepicker-prev")!==-1&&e(this).addClass("ui-datepicker-prev-hover"),this.className.indexOf("ui-datepicker-next")!==-1&&e(this).addClass("ui-datepicker-next-hover"))})}function i(t,n){e.extend(t,n);for(var r in n)n[r]==null&&(t[r]=n[r]);return t}e.extend(e.ui,{datepicker:{version:"1.10.0"}});var s="datepicker",o=(new Date).getTime(),u;e.extend(n.prototype,{markerClassName:"hasDatepicker",maxRows:4,_widgetDatepicker:function(){return this.dpDiv},setDefaults:function(e){return i(this._defaults,e||{}),this},_attachDatepicker:function(t,n){var r,i,s;r=t.nodeName.toLowerCase(),i=r==="div"||r==="span",t.id||(this.uuid+=1,t.id="dp"+this.uuid),s=this._newInst(e(t),i),s.settings=e.extend({},n||{}),r==="input"?this._connectDatepicker(t,s):i&&this._inlineDatepicker(t,s)},_newInst:function(t,n){var i=t[0].id.replace(/([^A-Za-z0-9_\-])/g,"\\\\$1");return{id:i,input:t,selectedDay:0,selectedMonth:0,selectedYear:0,drawMonth:0,drawYear:0,inline:n,dpDiv:n?r(e("<div class='"+this._inlineClass+" ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>")):this.dpDiv}},_connectDatepicker:function(t,n){var r=e(t);n.append=e([]),n.trigger=e([]);if(r.hasClass(this.markerClassName))return;this._attachments(r,n),r.addClass(this.markerClassName).keydown(this._doKeyDown).keypress(this._doKeyPress).keyup(this._doKeyUp),this._autoSize(n),e.data(t,s,n),n.settings.disabled&&this._disableDatepicker(t)},_attachments:function(t,n){var r,i,s,o=this._get(n,"appendText"),u=this._get(n,"isRTL");n.append&&n.append.remove(),o&&(n.append=e("<span class='"+this._appendClass+"'>"+o+"</span>"),t[u?"before":"after"](n.append)),t.unbind("focus",this._showDatepicker),n.trigger&&n.trigger.remove(),r=this._get(n,"showOn"),(r==="focus"||r==="both")&&t.focus(this._showDatepicker);if(r==="button"||r==="both")i=this._get(n,"buttonText"),s=this._get(n,"buttonImage"),n.trigger=e(this._get(n,"buttonImageOnly")?e("<img/>").addClass(this._triggerClass).attr({src:s,alt:i,title:i}):e("<button type='button'></button>").addClass(this._triggerClass).html(s?e("<img/>").attr({src:s,alt:i,title:i}):i)),t[u?"before":"after"](n.trigger),n.trigger.click(function(){return e.datepicker._datepickerShowing&&e.datepicker._lastInput===t[0]?e.datepicker._hideDatepicker():e.datepicker._datepickerShowing&&e.datepicker._lastInput!==t[0]?(e.datepicker._hideDatepicker(),e.datepicker._showDatepicker(t[0])):e.datepicker._showDatepicker(t[0]),!1})},_autoSize:function(e){if(this._get(e,"autoSize")&&!e.inline){var t,n,r,i,s=new Date(2009,11,20),o=this._get(e,"dateFormat");o.match(/[DM]/)&&(t=function(e){n=0,r=0;for(i=0;i<e.length;i++)e[i].length>n&&(n=e[i].length,r=i);return r},s.setMonth(t(this._get(e,o.match(/MM/)?"monthNames":"monthNamesShort"))),s.setDate(t(this._get(e,o.match(/DD/)?"dayNames":"dayNamesShort"))+20-s.getDay())),e.input.attr("size",this._formatDate(e,s).length)}},_inlineDatepicker:function(t,n){var r=e(t);if(r.hasClass(this.markerClassName))return;r.addClass(this.markerClassName).append(n.dpDiv),e.data(t,s,n),this._setDate(n,this._getDefaultDate(n),!0),this._updateDatepicker(n),this._updateAlternate(n),n.settings.disabled&&this._disableDatepicker(t),n.dpDiv.css("display","block")},_dialogDatepicker:function(t,n,r,o,u){var a,f,l,c,h,p=this._dialogInst;return p||(this.uuid+=1,a="dp"+this.uuid,this._dialogInput=e("<input type='text' id='"+a+"' style='position: absolute; top: -100px; width: 0px;'/>"),this._dialogInput.keydown(this._doKeyDown),e("body").append(this._dialogInput),p=this._dialogInst=this._newInst(this._dialogInput,!1),p.settings={},e.data(this._dialogInput[0],s,p)),i(p.settings,o||{}),n=n&&n.constructor===Date?this._formatDate(p,n):n,this._dialogInput.val(n),this._pos=u?u.length?u:[u.pageX,u.pageY]:null,this._pos||(f=document.documentElement.clientWidth,l=document.documentElement.clientHeight,c=document.documentElement.scrollLeft||document.body.scrollLeft,h=document.documentElement.scrollTop||document.body.scrollTop,this._pos=[f/2-100+c,l/2-150+h]),this._dialogInput.css("left",this._pos[0]+20+"px").css("top",this._pos[1]+"px"),p.settings.onSelect=r,this._inDialog=!0,this.dpDiv.addClass(this._dialogClass),this._showDatepicker(this._dialogInput[0]),e.blockUI&&e.blockUI(this.dpDiv),e.data(this._dialogInput[0],s,p),this},_destroyDatepicker:function(t){var n,r=e(t),i=e.data(t,s);if(!r.hasClass(this.markerClassName))return;n=t.nodeName.toLowerCase(),e.removeData(t,s),n==="input"?(i.append.remove(),i.trigger.remove(),r.removeClass(this.markerClassName).unbind("focus",this._showDatepicker).unbind("keydown",this._doKeyDown).unbind("keypress",this._doKeyPress).unbind("keyup",this._doKeyUp)):(n==="div"||n==="span")&&r.removeClass(this.markerClassName).empty()},_enableDatepicker:function(t){var n,r,i=e(t),o=e.data(t,s);if(!i.hasClass(this.markerClassName))return;n=t.nodeName.toLowerCase();if(n==="input")t.disabled=!1,o.trigger.filter("button").each(function(){this.disabled=!1}).end().filter("img").css({opacity:"1.0",cursor:""});else if(n==="div"||n==="span")r=i.children("."+this._inlineClass),r.children().removeClass("ui-state-disabled"),r.find("select.ui-datepicker-month, select.ui-datepicker-year").prop("disabled",!1);this._disabledInputs=e.map(this._disabledInputs,function(e){return e===t?null:e})},_disableDatepicker:function(t){var n,r,i=e(t),o=e.data(t,s);if(!i.hasClass(this.markerClassName))return;n=t.nodeName.toLowerCase();if(n==="input")t.disabled=!0,o.trigger.filter("button").each(function(){this.disabled=!0}).end().filter("img").css({opacity:"0.5",cursor:"default"});else if(n==="div"||n==="span")r=i.children("."+this._inlineClass),r.children().addClass("ui-state-disabled"),r.find("select.ui-datepicker-month, select.ui-datepicker-year").prop("disabled",!0);this._disabledInputs=e.map(this._disabledInputs,function(e){return e===t?null:e}),this._disabledInputs[this._disabledInputs.length]=t},_isDisabledDatepicker:function(e){if(!e)return!1;for(var t=0;t<this._disabledInputs.length;t++)if(this._disabledInputs[t]===e)return!0;return!1},_getInst:function(t){try{return e.data(t,s)}catch(n){throw"Missing instance data for this datepicker"}},_optionDatepicker:function(n,r,s){var o,u,a,f,l=this._getInst(n);if(arguments.length===2&&typeof r=="string")return r==="defaults"?e.extend({},e.datepicker._defaults):l?r==="all"?e.extend({},l.settings):this._get(l,r):null;o=r||{},typeof r=="string"&&(o={},o[r]=s),l&&(this._curInst===l&&this._hideDatepicker(),u=this._getDateDatepicker(n,!0),a=this._getMinMaxDate(l,"min"),f=this._getMinMaxDate(l,"max"),i(l.settings,o),a!==null&&o.dateFormat!==t&&o.minDate===t&&(l.settings.minDate=this._formatDate(l,a)),f!==null&&o.dateFormat!==t&&o.maxDate===t&&(l.settings.maxDate=this._formatDate(l,f)),"disabled"in o&&(o.disabled?this._disableDatepicker(n):this._enableDatepicker(n)),this._attachments(e(n),l),this._autoSize(l),this._setDate(l,u),this._updateAlternate(l),this._updateDatepicker(l))},_changeDatepicker:function(e,t,n){this._optionDatepicker(e,t,n)},_refreshDatepicker:function(e){var t=this._getInst(e);t&&this._updateDatepicker(t)},_setDateDatepicker:function(e,t){var n=this._getInst(e);n&&(this._setDate(n,t),this._updateDatepicker(n),this._updateAlternate(n))},_getDateDatepicker:function(e,t){var n=this._getInst(e);return n&&!n.inline&&this._setDateFromField(n,t),n?this._getDate(n):null},_doKeyDown:function(t){var n,r,i,s=e.datepicker._getInst(t.target),o=!0,u=s.dpDiv.is(".ui-datepicker-rtl");s._keyEvent=!0;if(e.datepicker._datepickerShowing)switch(t.keyCode){case 9:e.datepicker._hideDatepicker(),o=!1;break;case 13:return i=e("td."+e.datepicker._dayOverClass+":not(."+e.datepicker._currentClass+")",s.dpDiv),i[0]&&e.datepicker._selectDay(t.target,s.selectedMonth,s.selectedYear,i[0]),n=e.datepicker._get(s,"onSelect"),n?(r=e.datepicker._formatDate(s),n.apply(s.input?s.input[0]:null,[r,s])):e.datepicker._hideDatepicker(),!1;case 27:e.datepicker._hideDatepicker();break;case 33:e.datepicker._adjustDate(t.target,t.ctrlKey?-e.datepicker._get(s,"stepBigMonths"):-e.datepicker._get(s,"stepMonths"),"M");break;case 34:e.datepicker._adjustDate(t.target,t.ctrlKey?+e.datepicker._get(s,"stepBigMonths"):+e.datepicker._get(s,"stepMonths"),"M");break;case 35:(t.ctrlKey||t.metaKey)&&e.datepicker._clearDate(t.target),o=t.ctrlKey||t.metaKey;break;case 36:(t.ctrlKey||t.metaKey)&&e.datepicker._gotoToday(t.target),o=t.ctrlKey||t.metaKey;break;case 37:(t.ctrlKey||t.metaKey)&&e.datepicker._adjustDate(t.target,u?1:-1,"D"),o=t.ctrlKey||t.metaKey,t.originalEvent.altKey&&e.datepicker._adjustDate(t.target,t.ctrlKey?-e.datepicker._get(s,"stepBigMonths"):-e.datepicker._get(s,"stepMonths"),"M");break;case 38:(t.ctrlKey||t.metaKey)&&e.datepicker._adjustDate(t.target,-7,"D"),o=t.ctrlKey||t.metaKey;break;case 39:(t.ctrlKey||t.metaKey)&&e.datepicker._adjustDate(t.target,u?-1:1,"D"),o=t.ctrlKey||t.metaKey,t.originalEvent.altKey&&e.datepicker._adjustDate(t.target,t.ctrlKey?+e.datepicker._get(s,"stepBigMonths"):+e.datepicker._get(s,"stepMonths"),"M");break;case 40:(t.ctrlKey||t.metaKey)&&e.datepicker._adjustDate(t.target,7,"D"),o=t.ctrlKey||t.metaKey;break;default:o=!1}else t.keyCode===36&&t.ctrlKey?e.datepicker._showDatepicker(this):o=!1;o&&(t.preventDefault(),t.stopPropagation())},_doKeyPress:function(t){var n,r,i=e.datepicker._getInst(t.target);if(e.datepicker._get(i,"constrainInput"))return n=e.datepicker._possibleChars(e.datepicker._get(i,"dateFormat")),r=String.fromCharCode(t.charCode==null?t.keyCode:t.charCode),t.ctrlKey||t.metaKey||r<" "||!n||n.indexOf(r)>-1},_doKeyUp:function(t){var n,r=e.datepicker._getInst(t.target);if(r.input.val()!==r.lastVal)try{n=e.datepicker.parseDate(e.datepicker._get(r,"dateFormat"),r.input?r.input.val():null,e.datepicker._getFormatConfig(r)),n&&(e.datepicker._setDateFromField(r),e.datepicker._updateAlternate(r),e.datepicker._updateDatepicker(r))}catch(i){}return!0},_showDatepicker:function(t){t=t.target||t,t.nodeName.toLowerCase()!=="input"&&(t=e("input",t.parentNode)[0]);if(e.datepicker._isDisabledDatepicker(t)||e.datepicker._lastInput===t)return;var n,r,s,o,u,a,f;n=e.datepicker._getInst(t),e.datepicker._curInst&&e.datepicker._curInst!==n&&(e.datepicker._curInst.dpDiv.stop(!0,!0),n&&e.datepicker._datepickerShowing&&e.datepicker._hideDatepicker(e.datepicker._curInst.input[0])),r=e.datepicker._get(n,"beforeShow"),s=r?r.apply(t,[t,n]):{};if(s===!1)return;i(n.settings,s),n.lastVal=null,e.datepicker._lastInput=t,e.datepicker._setDateFromField(n),e.datepicker._inDialog&&(t.value=""),e.datepicker._pos||(e.datepicker._pos=e.datepicker._findPos(t),e.datepicker._pos[1]+=t.offsetHeight),o=!1,e(t).parents().each(function(){return o|=e(this).css("position")==="fixed",!o}),u={left:e.datepicker._pos[0],top:e.datepicker._pos[1]},e.datepicker._pos=null,n.dpDiv.empty(),n.dpDiv.css({position:"absolute",display:"block",top:"-1000px"}),e.datepicker._updateDatepicker(n),u=e.datepicker._checkOffset(n,u,o),n.dpDiv.css({position:e.datepicker._inDialog&&e.blockUI?"static":o?"fixed":"absolute",display:"none",left:u.left+"px",top:u.top+"px"}),n.inline||(a=e.datepicker._get(n,"showAnim"),f=e.datepicker._get(n,"duration"),n.dpDiv.zIndex(e(t).zIndex()+1),e.datepicker._datepickerShowing=!0,e.effects&&e.effects.effect[a]?n.dpDiv.show(a,e.datepicker._get(n,"showOptions"),f):n.dpDiv[a||"show"](a?f:null),n.input.is(":visible")&&!n.input.is(":disabled")&&n.input.focus(),e.datepicker._curInst=n)},_updateDatepicker:function(t){this.maxRows=4,u=t,t.dpDiv.empty().append(this._generateHTML(t)),this._attachHandlers(t),t.dpDiv.find("."+this._dayOverClass+" a").mouseover();var n,r=this._getNumberOfMonths(t),i=r[1],s=17;t.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width(""),i>1&&t.dpDiv.addClass("ui-datepicker-multi-"+i).css("width",s*i+"em"),t.dpDiv[(r[0]!==1||r[1]!==1?"add":"remove")+"Class"]("ui-datepicker-multi"),t.dpDiv[(this._get(t,"isRTL")?"add":"remove")+"Class"]("ui-datepicker-rtl"),t===e.datepicker._curInst&&e.datepicker._datepickerShowing&&t.input&&t.input.is(":visible")&&!t.input.is(":disabled")&&t.input[0]!==document.activeElement&&t.input.focus(),t.yearshtml&&(n=t.yearshtml,setTimeout(function(){n===t.yearshtml&&t.yearshtml&&t.dpDiv.find("select.ui-datepicker-year:first").replaceWith(t.yearshtml),n=t.yearshtml=null},0))},_getBorders:function(e){var t=function(e){return{thin:1,medium:2,thick:3}[e]||e};return[parseFloat(t(e.css("border-left-width"))),parseFloat(t(e.css("border-top-width")))]},_checkOffset:function(t,n,r){var i=t.dpDiv.outerWidth(),s=t.dpDiv.outerHeight(),o=t.input?t.input.outerWidth():0,u=t.input?t.input.outerHeight():0,a=document.documentElement.clientWidth+(r?0:e(document).scrollLeft()),f=document.documentElement.clientHeight+(r?0:e(document).scrollTop());return n.left-=this._get(t,"isRTL")?i-o:0,n.left-=r&&n.left===t.input.offset().left?e(document).scrollLeft():0,n.top-=r&&n.top===t.input.offset().top+u?e(document).scrollTop():0,n.left-=Math.min(n.left,n.left+i>a&&a>i?Math.abs(n.left+i-a):0),n.top-=Math.min(n.top,n.top+s>f&&f>s?Math.abs(s+u):0),n},_findPos:function(t){var n,r=this._getInst(t),i=this._get(r,"isRTL");while(t&&(t.type==="hidden"||t.nodeType!==1||e.expr.filters.hidden(t)))t=t[i?"previousSibling":"nextSibling"];return n=e(t).offset(),[n.left,n.top]},_hideDatepicker:function(t){var n,r,i,o,u=this._curInst;if(!u||t&&u!==e.data(t,s))return;this._datepickerShowing&&(n=this._get(u,"showAnim"),r=this._get(u,"duration"),i=function(){e.datepicker._tidyDialog(u)},e.effects&&(e.effects.effect[n]||e.effects[n])?u.dpDiv.hide(n,e.datepicker._get(u,"showOptions"),r,i):u.dpDiv[n==="slideDown"?"slideUp":n==="fadeIn"?"fadeOut":"hide"](n?r:null,i),n||i(),this._datepickerShowing=!1,o=this._get(u,"onClose"),o&&o.apply(u.input?u.input[0]:null,[u.input?u.input.val():"",u]),this._lastInput=null,this._inDialog&&(this._dialogInput.css({position:"absolute",left:"0",top:"-100px"}),e.blockUI&&(e.unblockUI(),e("body").append(this.dpDiv))),this._inDialog=!1)},_tidyDialog:function(e){e.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar")},_checkExternalClick:function(t){if(!e.datepicker._curInst)return;var n=e(t.target),r=e.datepicker._getInst(n[0]);(n[0].id!==e.datepicker._mainDivId&&n.parents("#"+e.datepicker._mainDivId).length===0&&!n.hasClass(e.datepicker.markerClassName)&&!n.closest("."+e.datepicker._triggerClass).length&&e.datepicker._datepickerShowing&&(!e.datepicker._inDialog||!e.blockUI)||n.hasClass(e.datepicker.markerClassName)&&e.datepicker._curInst!==r)&&e.datepicker._hideDatepicker()},_adjustDate:function(t,n,r){var i=e(t),s=this._getInst(i[0]);if(this._isDisabledDatepicker(i[0]))return;this._adjustInstDate(s,n+(r==="M"?this._get(s,"showCurrentAtPos"):0),r),this._updateDatepicker(s)},_gotoToday:function(t){var n,r=e(t),i=this._getInst(r[0]);this._get(i,"gotoCurrent")&&i.currentDay?(i.selectedDay=i.currentDay,i.drawMonth=i.selectedMonth=i.currentMonth,i.drawYear=i.selectedYear=i.currentYear):(n=new Date,i.selectedDay=n.getDate(),i.drawMonth=i.selectedMonth=n.getMonth(),i.drawYear=i.selectedYear=n.getFullYear()),this._notifyChange(i),this._adjustDate(r)},_selectMonthYear:function(t,n,r){var i=e(t),s=this._getInst(i[0]);s["selected"+(r==="M"?"Month":"Year")]=s["draw"+(r==="M"?"Month":"Year")]=parseInt(n.options[n.selectedIndex].value,10),this._notifyChange(s),this._adjustDate(i)},_selectDay:function(t,n,r,i){var s,o=e(t);if(e(i).hasClass(this._unselectableClass)||this._isDisabledDatepicker(o[0]))return;s=this._getInst(o[0]),s.selectedDay=s.currentDay=e("a",i).html(),s.selectedMonth=s.currentMonth=n,s.selectedYear=s.currentYear=r,this._selectDate(t,this._formatDate(s,s.currentDay,s.currentMonth,s.currentYear))},_clearDate:function(t){var n=e(t);this._selectDate(n,"")},_selectDate:function(t,n){var r,i=e(t),s=this._getInst(i[0]);n=n!=null?n:this._formatDate(s),s.input&&s.input.val(n),this._updateAlternate(s),r=this._get(s,"onSelect"),r?r.apply(s.input?s.input[0]:null,[n,s]):s.input&&s.input.trigger("change"),s.inline?this._updateDatepicker(s):(this._hideDatepicker(),this._lastInput=s.input[0],typeof s.input[0]!="object"&&s.input.focus(),this._lastInput=null)},_updateAlternate:function(t){var n,r,i,s=this._get(t,"altField");s&&(n=this._get(t,"altFormat")||this._get(t,"dateFormat"),r=this._getDate(t),i=this.formatDate(n,r,this._getFormatConfig(t)),e(s).each(function(){e(this).val(i)}))},noWeekends:function(e){var t=e.getDay();return[t>0&&t<6,""]},iso8601Week:function(e){var t,n=new Date(e.getTime());return n.setDate(n.getDate()+4-(n.getDay()||7)),t=n.getTime(),n.setMonth(0),n.setDate(1),Math.floor(Math.round((t-n)/864e5)/7)+1},parseDate:function(t,n,r){if(t==null||n==null)throw"Invalid arguments";n=typeof n=="object"?n.toString():n+"";if(n==="")return null;var i,s,o,u=0,a=(r?r.shortYearCutoff:null)||this._defaults.shortYearCutoff,f=typeof a!="string"?a:(new Date).getFullYear()%100+parseInt(a,10),l=(r?r.dayNamesShort:null)||this._defaults.dayNamesShort,c=(r?r.dayNames:null)||this._defaults.dayNames,h=(r?r.monthNamesShort:null)||this._defaults.monthNamesShort,p=(r?r.monthNames:null)||this._defaults.monthNames,d=-1,v=-1,m=-1,g=-1,y=!1,b,w=function(e){var n=i+1<t.length&&t.charAt(i+1)===e;return n&&i++,n},E=function(e){var t=w(e),r=e==="@"?14:e==="!"?20:e==="y"&&t?4:e==="o"?3:2,i=new RegExp("^\\d{1,"+r+"}"),s=n.substring(u).match(i);if(!s)throw"Missing number at position "+u;return u+=s[0].length,parseInt(s[0],10)},S=function(t,r,i){var s=-1,o=e.map(w(t)?i:r,function(e,t){return[[t,e]]}).sort(function(e,t){return-(e[1].length-t[1].length)});e.each(o,function(e,t){var r=t[1];if(n.substr(u,r.length).toLowerCase()===r.toLowerCase())return s=t[0],u+=r.length,!1});if(s!==-1)return s+1;throw"Unknown name at position "+u},x=function(){if(n.charAt(u)!==t.charAt(i))throw"Unexpected literal at position "+u;u++};for(i=0;i<t.length;i++)if(y)t.charAt(i)==="'"&&!w("'")?y=!1:x();else switch(t.charAt(i)){case"d":m=E("d");break;case"D":S("D",l,c);break;case"o":g=E("o");break;case"m":v=E("m");break;case"M":v=S("M",h,p);break;case"y":d=E("y");break;case"@":b=new Date(E("@")),d=b.getFullYear(),v=b.getMonth()+1,m=b.getDate();break;case"!":b=new Date((E("!")-this._ticksTo1970)/1e4),d=b.getFullYear(),v=b.getMonth()+1,m=b.getDate();break;case"'":w("'")?x():y=!0;break;default:x()}if(u<n.length){o=n.substr(u);if(!/^\s+/.test(o))throw"Extra/unparsed characters found in date: "+o}d===-1?d=(new Date).getFullYear():d<100&&(d+=(new Date).getFullYear()-(new Date).getFullYear()%100+(d<=f?0:-100));if(g>-1){v=1,m=g;do{s=this._getDaysInMonth(d,v-1);if(m<=s)break;v++,m-=s}while(!0)}b=this._daylightSavingAdjust(new Date(d,v-1,m));if(b.getFullYear()!==d||b.getMonth()+1!==v||b.getDate()!==m)throw"Invalid date";return b},ATOM:"yy-mm-dd",COOKIE:"D, dd M yy",ISO_8601:"yy-mm-dd",RFC_822:"D, d M y",RFC_850:"DD, dd-M-y",RFC_1036:"D, d M y",RFC_1123:"D, d M yy",RFC_2822:"D, d M yy",RSS:"D, d M y",TICKS:"!",TIMESTAMP:"@",W3C:"yy-mm-dd",_ticksTo1970:(718685+Math.floor(492.5)-Math.floor(19.7)+Math.floor(4.925))*24*60*60*1e7,formatDate:function(e,t,n){if(!t)return"";var r,i=(n?n.dayNamesShort:null)||this._defaults.dayNamesShort,s=(n?n.dayNames:null)||this._defaults.dayNames,o=(n?n.monthNamesShort:null)||this._defaults.monthNamesShort,u=(n?n.monthNames:null)||this._defaults.monthNames,a=function(t){var n=r+1<e.length&&e.charAt(r+1)===t;return n&&r++,n},f=function(e,t,n){var r=""+t;if(a(e))while(r.length<n)r="0"+r;return r},l=function(e,t,n,r){return a(e)?r[t]:n[t]},c="",h=!1;if(t)for(r=0;r<e.length;r++)if(h)e.charAt(r)==="'"&&!a("'")?h=!1:c+=e.charAt(r);else switch(e.charAt(r)){case"d":c+=f("d",t.getDate(),2);break;case"D":c+=l("D",t.getDay(),i,s);break;case"o":c+=f("o",Math.round(((new Date(t.getFullYear(),t.getMonth(),t.getDate())).getTime()-(new Date(t.getFullYear(),0,0)).getTime())/864e5),3);break;case"m":c+=f("m",t.getMonth()+1,2);break;case"M":c+=l("M",t.getMonth(),o,u);break;case"y":c+=a("y")?t.getFullYear():(t.getYear()%100<10?"0":"")+t.getYear()%100;break;case"@":c+=t.getTime();break;case"!":c+=t.getTime()*1e4+this._ticksTo1970;break;case"'":a("'")?c+="'":h=!0;break;default:c+=e.charAt(r)}return c},_possibleChars:function(e){var t,n="",r=!1,i=function(n){var r=t+1<e.length&&e.charAt(t+1)===n;return r&&t++,r};for(t=0;t<e.length;t++)if(r)e.charAt(t)==="'"&&!i("'")?r=!1:n+=e.charAt(t);else switch(e.charAt(t)){case"d":case"m":case"y":case"@":n+="0123456789";break;case"D":case"M":return null;case"'":i("'")?n+="'":r=!0;break;default:n+=e.charAt(t)}return n},_get:function(e,n){return e.settings[n]!==t?e.settings[n]:this._defaults[n]},_setDateFromField:function(e,t){if(e.input.val()===e.lastVal)return;var n=this._get(e,"dateFormat"),r=e.lastVal=e.input?e.input.val():null,i=this._getDefaultDate(e),s=i,o=this._getFormatConfig(e);try{s=this.parseDate(n,r,o)||i}catch(u){r=t?"":r}e.selectedDay=s.getDate(),e.drawMonth=e.selectedMonth=s.getMonth(),e.drawYear=e.selectedYear=s.getFullYear(),e.currentDay=r?s.getDate():0,e.currentMonth=r?s.getMonth():0,e.currentYear=r?s.getFullYear():0,this._adjustInstDate(e)},_getDefaultDate:function(e){return this._restrictMinMax(e,this._determineDate(e,this._get(e,"defaultDate"),new Date))},_determineDate:function(t,n,r){var i=function(e){var t=new Date;return t.setDate(t.getDate()+e),t},s=function(n){try{return e.datepicker.parseDate(e.datepicker._get(t,"dateFormat"),n,e.datepicker._getFormatConfig(t))}catch(r){}var i=(n.toLowerCase().match(/^c/)?e.datepicker._getDate(t):null)||new Date,s=i.getFullYear(),o=i.getMonth(),u=i.getDate(),a=/([+\-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,f=a.exec(n);while(f){switch(f[2]||"d"){case"d":case"D":u+=parseInt(f[1],10);break;case"w":case"W":u+=parseInt(f[1],10)*7;break;case"m":case"M":o+=parseInt(f[1],10),u=Math.min(u,e.datepicker._getDaysInMonth(s,o));break;case"y":case"Y":s+=parseInt(f[1],10),u=Math.min(u,e.datepicker._getDaysInMonth(s,o))}f=a.exec(n)}return new Date(s,o,u)},o=n==null||n===""?r:typeof n=="string"?s(n):typeof n=="number"?isNaN(n)?r:i(n):new Date(n.getTime());return o=o&&o.toString()==="Invalid Date"?r:o,o&&(o.setHours(0),o.setMinutes(0),o.setSeconds(0),o.setMilliseconds(0)),this._daylightSavingAdjust(o)},_daylightSavingAdjust:function(e){return e?(e.setHours(e.getHours()>12?e.getHours()+2:0),e):null},_setDate:function(e,t,n){var r=!t,i=e.selectedMonth,s=e.selectedYear,o=this._restrictMinMax(e,this._determineDate(e,t,new Date));e.selectedDay=e.currentDay=o.getDate(),e.drawMonth=e.selectedMonth=e.currentMonth=o.getMonth(),e.drawYear=e.selectedYear=e.currentYear=o.getFullYear(),(i!==e.selectedMonth||s!==e.selectedYear)&&!n&&this._notifyChange(e),this._adjustInstDate(e),e.input&&e.input.val(r?"":this._formatDate(e))},_getDate:function(e){var t=!e.currentYear||e.input&&e.input.val()===""?null:this._daylightSavingAdjust(new Date(e.currentYear,e.currentMonth,e.currentDay));return t},_attachHandlers:function(t){var n=this._get(t,"stepMonths"),r="#"+t.id.replace(/\\\\/g,"\\");t.dpDiv.find("[data-handler]").map(function(){var t={prev:function(){window["DP_jQuery_"+o].datepicker._adjustDate(r,-n,"M")},next:function(){window["DP_jQuery_"+o].datepicker._adjustDate(r,+n,"M")},hide:function(){window["DP_jQuery_"+o].datepicker._hideDatepicker()},today:function(){window["DP_jQuery_"+o].datepicker._gotoToday(r)},selectDay:function(){return window["DP_jQuery_"+o].datepicker._selectDay(r,+this.getAttribute("data-month"),+this.getAttribute("data-year"),this),!1},selectMonth:function(){return window["DP_jQuery_"+o].datepicker._selectMonthYear(r,this,"M"),!1},selectYear:function(){return window["DP_jQuery_"+o].datepicker._selectMonthYear(r,this,"Y"),!1}};e(this).bind(this.getAttribute("data-event"),t[this.getAttribute("data-handler")])})},_generateHTML:function(e){var t,n,r,i,s,o,u,a,f,l,c,h,p,d,v,m,g,y,b,w,E,S,x,T,N,C,k,L,A,O,M,_,D,P,H,B,j,F,I,q=new Date,R=this._daylightSavingAdjust(new Date(q.getFullYear(),q.getMonth(),q.getDate())),U=this._get(e,"isRTL"),z=this._get(e,"showButtonPanel"),W=this._get(e,"hideIfNoPrevNext"),X=this._get(e,"navigationAsDateFormat"),V=this._getNumberOfMonths(e),$=this._get(e,"showCurrentAtPos"),J=this._get(e,"stepMonths"),K=V[0]!==1||V[1]!==1,Q=this._daylightSavingAdjust(e.currentDay?new Date(e.currentYear,e.currentMonth,e.currentDay):new Date(9999,9,9)),G=this._getMinMaxDate(e,"min"),Y=this._getMinMaxDate(e,"max"),Z=e.drawMonth-$,et=e.drawYear;Z<0&&(Z+=12,et--);if(Y){t=this._daylightSavingAdjust(new Date(Y.getFullYear(),Y.getMonth()-V[0]*V[1]+1,Y.getDate())),t=G&&t<G?G:t;while(this._daylightSavingAdjust(new Date(et,Z,1))>t)Z--,Z<0&&(Z=11,et--)}e.drawMonth=Z,e.drawYear=et,n=this._get(e,"prevText"),n=X?this.formatDate(n,this._daylightSavingAdjust(new Date(et,Z-J,1)),this._getFormatConfig(e)):n,r=this._canAdjustMonth(e,-1,et,Z)?"<a class='ui-datepicker-prev ui-corner-all' data-handler='prev' data-event='click' title='"+n+"'><span class='ui-icon ui-icon-circle-triangle-"+(U?"e":"w")+"'>"+n+"</span></a>":W?"":"<a class='ui-datepicker-prev ui-corner-all ui-state-disabled' title='"+n+"'><span class='ui-icon ui-icon-circle-triangle-"+(U?"e":"w")+"'>"+n+"</span></a>",i=this._get(e,"nextText"),i=X?this.formatDate(i,this._daylightSavingAdjust(new Date(et,Z+J,1)),this._getFormatConfig(e)):i,s=this._canAdjustMonth(e,1,et,Z)?"<a class='ui-datepicker-next ui-corner-all' data-handler='next' data-event='click' title='"+i+"'><span class='ui-icon ui-icon-circle-triangle-"+(U?"w":"e")+"'>"+i+"</span></a>":W?"":"<a class='ui-datepicker-next ui-corner-all ui-state-disabled' title='"+i+"'><span class='ui-icon ui-icon-circle-triangle-"+(U?"w":"e")+"'>"+i+"</span></a>",o=this._get(e,"currentText"),u=this._get(e,"gotoCurrent")&&e.currentDay?Q:R,o=X?this.formatDate(o,u,this._getFormatConfig(e)):o,a=e.inline?"":"<button type='button' class='ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all' data-handler='hide' data-event='click'>"+this._get(e,"closeText")+"</button>",f=z?"<div class='ui-datepicker-buttonpane ui-widget-content'>"+(U?a:"")+(this._isInRange(e,u)?"<button type='button' class='ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all' data-handler='today' data-event='click'>"+o+"</button>":"")+(U?"":a)+"</div>":"",l=parseInt(this._get(e,"firstDay"),10),l=isNaN(l)?0:l,c=this._get(e,"showWeek"),h=this._get(e,"dayNames"),p=this._get(e,"dayNamesMin"),d=this._get(e,"monthNames"),v=this._get(e,"monthNamesShort"),m=this._get(e,"beforeShowDay"),g=this._get(e,"showOtherMonths"),y=this._get(e,"selectOtherMonths"),b=this._getDefaultDate(e),w="",E;for(S=0;S<V[0];S++){x="",this.maxRows=4;for(T=0;T<V[1];T++){N=this._daylightSavingAdjust(new Date(et,Z,e.selectedDay)),C=" ui-corner-all",k="";if(K){k+="<div class='ui-datepicker-group";if(V[1]>1)switch(T){case 0:k+=" ui-datepicker-group-first",C=" ui-corner-"+(U?"right":"left");break;case V[1]-1:k+=" ui-datepicker-group-last",C=" ui-corner-"+(U?"left":"right");break;default:k+=" ui-datepicker-group-middle",C=""}k+="'>"}k+="<div class='ui-datepicker-header ui-widget-header ui-helper-clearfix"+C+"'>"+(/all|left/.test(C)&&S===0?U?s:r:"")+(/all|right/.test(C)&&S===0?U?r:s:"")+this._generateMonthYearHeader(e,Z,et,G,Y,S>0||T>0,d,v)+"</div><table class='ui-datepicker-calendar'><thead>"+"<tr>",L=c?"<th class='ui-datepicker-week-col'>"+this._get(e,"weekHeader")+"</th>":"";for(E=0;E<7;E++)A=(E+l)%7,L+="<th"+((E+l+6)%7>=5?" class='ui-datepicker-week-end'":"")+">"+"<span title='"+h[A]+"'>"+p[A]+"</span></th>";k+=L+"</tr></thead><tbody>",O=this._getDaysInMonth(et,Z),et===e.selectedYear&&Z===e.selectedMonth&&(e.selectedDay=Math.min(e.selectedDay,O)),M=(this._getFirstDayOfMonth(et,Z)-l+7)%7,_=Math.ceil((M+O)/7),D=K?this.maxRows>_?this.maxRows:_:_,this.maxRows=D,P=this._daylightSavingAdjust(new Date(et,Z,1-M));for(H=0;H<D;H++){k+="<tr>",B=c?"<td class='ui-datepicker-week-col'>"+this._get(e,"calculateWeek")(P)+"</td>":"";for(E=0;E<7;E++)j=m?m.apply(e.input?e.input[0]:null,[P]):[!0,""],F=P.getMonth()!==Z,I=F&&!y||!j[0]||G&&P<G||Y&&P>Y,B+="<td class='"+((E+l+6)%7>=5?" ui-datepicker-week-end":"")+(F?" ui-datepicker-other-month":"")+(P.getTime()===N.getTime()&&Z===e.selectedMonth&&e._keyEvent||b.getTime()===P.getTime()&&b.getTime()===N.getTime()?" "+this._dayOverClass:"")+(I?" "+this._unselectableClass+" ui-state-disabled":"")+(F&&!g?"":" "+j[1]+(P.getTime()===Q.getTime()?" "+this._currentClass:"")+(P.getTime()===R.getTime()?" ui-datepicker-today":""))+"'"+((!F||g)&&j[2]?" title='"+j[2]+"'":"")+(I?"":" data-handler='selectDay' data-event='click' data-month='"+P.getMonth()+"' data-year='"+P.getFullYear()+"'")+">"+(F&&!g?" ":I?"<span class='ui-state-default'>"+P.getDate()+"</span>":"<a class='ui-state-default"+(P.getTime()===R.getTime()?" ui-state-highlight":"")+(P.getTime()===Q.getTime()?" ui-state-active":"")+(F?" ui-priority-secondary":"")+"' href='#'>"+P.getDate()+"</a>")+"</td>",P.setDate(P.getDate()+1),P=this._daylightSavingAdjust(P);k+=B+"</tr>"}Z++,Z>11&&(Z=0,et++),k+="</tbody></table>"+(K?"</div>"+(V[0]>0&&T===V[1]-1?"<div class='ui-datepicker-row-break'></div>":""):""),x+=k}w+=x}return w+=f,e._keyEvent=!1,w},_generateMonthYearHeader:function(e,t,n,r,i,s,o,u){var a,f,l,c,h,p,d,v,m=this._get(e,"changeMonth"),g=this._get(e,"changeYear"),y=this._get(e,"showMonthAfterYear"),b="<div class='ui-datepicker-title'>",w="";if(s||!m)w+="<span class='ui-datepicker-month'>"+o[t]+"</span>";else{a=r&&r.getFullYear()===n,f=i&&i.getFullYear()===n,w+="<select class='ui-datepicker-month' data-handler='selectMonth' data-event='change'>";for(l=0;l<12;l++)(!a||l>=r.getMonth())&&(!f||l<=i.getMonth())&&(w+="<option value='"+l+"'"+(l===t?" selected='selected'":"")+">"+u[l]+"</option>");w+="</select>"}y||(b+=w+(s||!m||!g?" ":""));if(!e.yearshtml){e.yearshtml="";if(s||!g)b+="<span class='ui-datepicker-year'>"+n+"</span>";else{c=this._get(e,"yearRange").split(":"),h=(new Date).getFullYear(),p=function(e){var t=e.match(/c[+\-].*/)?n+parseInt(e.substring(1),10):e.match(/[+\-].*/)?h+parseInt(e,10):parseInt(e,10);return isNaN(t)?h:t},d=p(c[0]),v=Math.max(d,p(c[1]||"")),d=r?Math.max(d,r.getFullYear()):d,v=i?Math.min(v,i.getFullYear()):v,e.yearshtml+="<select class='ui-datepicker-year' data-handler='selectYear' data-event='change'>";for(;d<=v;d++)e.yearshtml+="<option value='"+d+"'"+(d===n?" selected='selected'":"")+">"+d+"</option>";e.yearshtml+="</select>",b+=e.yearshtml,e.yearshtml=null}}return b+=this._get(e,"yearSuffix"),y&&(b+=(s||!m||!g?" ":"")+w),b+="</div>",b},_adjustInstDate:function(e,t,n){var r=e.drawYear+(n==="Y"?t:0),i=e.drawMonth+(n==="M"?t:0),s=Math.min(e.selectedDay,this._getDaysInMonth(r,i))+(n==="D"?t:0),o=this._restrictMinMax(e,this._daylightSavingAdjust(new Date(r,i,s)));e.selectedDay=o.getDate(),e.drawMonth=e.selectedMonth=o.getMonth(),e.drawYear=e.selectedYear=o.getFullYear(),(n==="M"||n==="Y")&&this._notifyChange(e)},_restrictMinMax:function(e,t){var n=this._getMinMaxDate(e,"min"),r=this._getMinMaxDate(e,"max"),i=n&&t<n?n:t;return r&&i>r?r:i},_notifyChange:function(e){var t=this._get(e,"onChangeMonthYear");t&&t.apply(e.input?e.input[0]:null,[e.selectedYear,e.selectedMonth+1,e])},_getNumberOfMonths:function(e){var t=this._get(e,"numberOfMonths");return t==null?[1,1]:typeof t=="number"?[1,t]:t},_getMinMaxDate:function(e,t){return this._determineDate(e,this._get(e,t+"Date"),null)},_getDaysInMonth:function(e,t){return 32-this._daylightSavingAdjust(new Date(e,t,32)).getDate()},_getFirstDayOfMonth:function(e,t){return(new Date(e,t,1)).getDay()},_canAdjustMonth:function(e,t,n,r){var i=this._getNumberOfMonths(e),s=this._daylightSavingAdjust(new Date(n,r+(t<0?t:i[0]*i[1]),1));return t<0&&s.setDate(this._getDaysInMonth(s.getFullYear(),s.getMonth())),this._isInRange(e,s)},_isInRange:function(e,t){var n,r,i=this._getMinMaxDate(e,"min"),s=this._getMinMaxDate(e,"max"),o=null,u=null,a=this._get(e,"yearRange");return a&&(n=a.split(":"),r=(new Date).getFullYear(),o=parseInt(n[0],10)+r,u=parseInt(n[1],10)+r),(!i||t.getTime()>=i.getTime())&&(!s||t.getTime()<=s.getTime())&&(!o||t.getFullYear()>=o)&&(!u||t.getFullYear()<=u)},_getFormatConfig:function(e){var t=this._get(e,"shortYearCutoff");return t=typeof t!="string"?t:(new Date).getFullYear()%100+parseInt(t,10),{shortYearCutoff:t,dayNamesShort:this._get(e,"dayNamesShort"),dayNames:this._get(e,"dayNames"),monthNamesShort:this._get(e,"monthNamesShort"),monthNames:this._get(e,"monthNames")}},_formatDate:function(e,t,n,r){t||(e.currentDay=e.selectedDay,e.currentMonth=e.selectedMonth,e.currentYear=e.selectedYear);var i=t?typeof t=="object"?t:this._daylightSavingAdjust(new Date(r,n,t)):this._daylightSavingAdjust(new Date(e.currentYear,e.currentMonth,e.currentDay));return this.formatDate(this._get(e,"dateFormat"),i,this._getFormatConfig(e))}}),e.fn.datepicker=function(t){if(!this.length)return this;e.datepicker.initialized||(e(document).mousedown(e.datepicker._checkExternalClick),e.datepicker.initialized=!0),e("#"+e.datepicker._mainDivId).length===0&&e("body").append(e.datepicker.dpDiv);var n=Array.prototype.slice.call(arguments,1);return typeof t!="string"||t!=="isDisabled"&&t!=="getDate"&&t!=="widget"?t==="option"&&arguments.length===2&&typeof arguments[1]=="string"?e.datepicker["_"+t+"Datepicker"].apply(e.datepicker,[this[0]].concat(n)):this.each(function(){typeof t=="string"?e.datepicker["_"+t+"Datepicker"].apply(e.datepicker,[this].concat(n)):e.datepicker._attachDatepicker(this,t)}):e.datepicker["_"+t+"Datepicker"].apply(e.datepicker,[this[0]].concat(n))},e.datepicker=new n,e.datepicker.initialized=!1,e.datepicker.uuid=(new Date).getTime(),e.datepicker.version="1.10.0",window["DP_jQuery_"+o]=e})(jQuery);(function(e,t){var n={buttons:!0,height:!0,maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0,width:!0},r={maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0};e.widget("ui.dialog",{version:"1.10.0",options:{appendTo:"body",autoOpen:!0,buttons:[],closeOnEscape:!0,closeText:"close",dialogClass:"",draggable:!0,hide:null,height:"auto",maxHeight:null,maxWidth:null,minHeight:150,minWidth:150,modal:!1,position:{my:"center",at:"center",of:window,collision:"fit",using:function(t){var n=e(this).css(t).offset().top;n<0&&e(this).css("top",t.top-n)}},resizable:!0,show:null,title:null,width:300,beforeClose:null,close:null,drag:null,dragStart:null,dragStop:null,focus:null,open:null,resize:null,resizeStart:null,resizeStop:null},_create:function(){this.originalCss={display:this.element[0].style.display,width:this.element[0].style.width,minHeight:this.element[0].style.minHeight,maxHeight:this.element[0].style.maxHeight,height:this.element[0].style.height},this.originalPosition={parent:this.element.parent(),index:this.element.parent().children().index(this.element)},this.originalTitle=this.element.attr("title"),this.options.title=this.options.title||this.originalTitle,this._createWrapper(),this.element.show().removeAttr("title").addClass("ui-dialog-content ui-widget-content").appendTo(this.uiDialog),this._createTitlebar(),this._createButtonPane(),this.options.draggable&&e.fn.draggable&&this._makeDraggable(),this.options.resizable&&e.fn.resizable&&this._makeResizable(),this._isOpen=!1},_init:function(){this.options.autoOpen&&this.open()},_appendTo:function(){var t=this.options.appendTo;return t&&(t.jquery||t.nodeType)?e(t):this.document.find(t||"body").eq(0)},_destroy:function(){var e,t=this.originalPosition;this._destroyOverlay(),this.element.removeUniqueId().removeClass("ui-dialog-content ui-widget-content").css(this.originalCss).detach(),this.uiDialog.stop(!0,!0).remove(),this.originalTitle&&this.element.attr("title",this.originalTitle),e=t.parent.children().eq(t.index),e.length&&e[0]!==this.element[0]?e.before(this.element):t.parent.append(this.element)},widget:function(){return this.uiDialog},disable:e.noop,enable:e.noop,close:function(t){var n=this;if(!this._isOpen||this._trigger("beforeClose",t)===!1)return;this._isOpen=!1,this._destroyOverlay(),this.opener.filter(":focusable").focus().length||e(this.document[0].activeElement).blur(),this._hide(this.uiDialog,this.options.hide,function(){n._trigger("close",t)})},isOpen:function(){return this._isOpen},moveToTop:function(){this._moveToTop()},_moveToTop:function(e,t){var n=!!this.uiDialog.nextAll(":visible").insertBefore(this.uiDialog).length;return n&&!t&&this._trigger("focus",e),n},open:function(){if(this._isOpen){this._moveToTop()&&this._focusTabbable();return}this.opener=e(this.document[0].activeElement),this._size(),this._position(),this._createOverlay(),this._moveToTop(null,!0),this._show(this.uiDialog,this.options.show),this._focusTabbable(),this._isOpen=!0,this._trigger("open"),this._trigger("focus")},_focusTabbable:function(){var e=this.element.find("[autofocus]");e.length||(e=this.element.find(":tabbable")),e.length||(e=this.uiDialogButtonPane.find(":tabbable")),e.length||(e=this.uiDialogTitlebarClose.filter(":tabbable")),e.length||(e=this.uiDialog),e.eq(0).focus()},_keepFocus:function(t){function n(){var t=this.document[0].activeElement,n=this.uiDialog[0]===t||e.contains(this.uiDialog[0],t);n||this._focusTabbable()}t.preventDefault(),n.call(this),this._delay(n)},_createWrapper:function(){this.uiDialog=e("<div>").addClass("ui-dialog ui-widget ui-widget-content ui-corner-all ui-front "+this.options.dialogClass).hide().attr({tabIndex:-1,role:"dialog"}).appendTo(this._appendTo()),this._on(this.uiDialog,{keydown:function(t){if(this.options.closeOnEscape&&!t.isDefaultPrevented()&&t.keyCode&&t.keyCode===e.ui.keyCode.ESCAPE){t.preventDefault(),this.close(t);return}if(t.keyCode!==e.ui.keyCode.TAB)return;var n=this.uiDialog.find(":tabbable"),r=n.filter(":first"),i=n.filter(":last");t.target!==i[0]&&t.target!==this.uiDialog[0]||!!t.shiftKey?(t.target===r[0]||t.target===this.uiDialog[0])&&t.shiftKey&&(i.focus(1),t.preventDefault()):(r.focus(1),t.preventDefault())},mousedown:function(e){this._moveToTop(e)&&this._focusTabbable()}}),this.element.find("[aria-describedby]").length||this.uiDialog.attr({"aria-describedby":this.element.uniqueId().attr("id")})},_createTitlebar:function(){var t;this.uiDialogTitlebar=e("<div>").addClass("ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix").prependTo(this.uiDialog),this._on(this.uiDialogTitlebar,{mousedown:function(t){e(t.target).closest(".ui-dialog-titlebar-close")||this.uiDialog.focus()}}),this.uiDialogTitlebarClose=e("<button></button>").button({label:this.options.closeText,icons:{primary:"ui-icon-closethick"},text:!1}).addClass("ui-dialog-titlebar-close").appendTo(this.uiDialogTitlebar),this._on(this.uiDialogTitlebarClose,{click:function(e){e.preventDefault(),this.close(e)}}),t=e("<span>").uniqueId().addClass("ui-dialog-title").prependTo(this.uiDialogTitlebar),this._title(t),this.uiDialog.attr({"aria-labelledby":t.attr("id")})},_title:function(e){this.options.title||e.html(" "),e.text(this.options.title)},_createButtonPane:function(){this.uiDialogButtonPane=e("<div>").addClass("ui-dialog-buttonpane ui-widget-content ui-helper-clearfix"),this.uiButtonSet=e("<div>").addClass("ui-dialog-buttonset").appendTo(this.uiDialogButtonPane),this._createButtons()},_createButtons:function(){var t=this,n=this.options.buttons;this.uiDialogButtonPane.remove(),this.uiButtonSet.empty();if(e.isEmptyObject(n)){this.uiDialog.removeClass("ui-dialog-buttons");return}e.each(n,function(n,r){var i,s;r=e.isFunction(r)?{click:r,text:n}:r,r=e.extend({type:"button"},r),i=r.click,r.click=function(){i.apply(t.element[0],arguments)},s={icons:r.icons,text:r.showText},delete r.icons,delete r.showText,e("<button></button>",r).button(s).appendTo(t.uiButtonSet)}),this.uiDialog.addClass("ui-dialog-buttons"),this.uiDialogButtonPane.appendTo(this.uiDialog)},_makeDraggable:function(){function t(e){return{position:e.position,offset:e.offset}}var n=this,r=this.options;this.uiDialog.draggable({cancel:".ui-dialog-content, .ui-dialog-titlebar-close",handle:".ui-dialog-titlebar",containment:"document",start:function(r,i){e(this).addClass("ui-dialog-dragging"),n._trigger("dragStart",r,t(i))},drag:function(e,r){n._trigger("drag",e,t(r))},stop:function(i,s){r.position=[s.position.left-n.document.scrollLeft(),s.position.top-n.document.scrollTop()],e(this).removeClass("ui-dialog-dragging"),n._trigger("dragStop",i,t(s))}})},_makeResizable:function(){function t(e){return{originalPosition:e.originalPosition,originalSize:e.originalSize,position:e.position,size:e.size}}var n=this,r=this.options,i=r.resizable,s=this.uiDialog.css("position"),o=typeof i=="string"?i:"n,e,s,w,se,sw,ne,nw";this.uiDialog.resizable({cancel:".ui-dialog-content",containment:"document",alsoResize:this.element,maxWidth:r.maxWidth,maxHeight:r.maxHeight,minWidth:r.minWidth,minHeight:this._minHeight(),handles:o,start:function(r,i){e(this).addClass("ui-dialog-resizing"),n._trigger("resizeStart",r,t(i))},resize:function(e,r){n._trigger("resize",e,t(r))},stop:function(i,s){r.height=e(this).height(),r.width=e(this).width(),e(this).removeClass("ui-dialog-resizing"),n._trigger("resizeStop",i,t(s))}}).css("position",s)},_minHeight:function(){var e=this.options;return e.height==="auto"?e.minHeight:Math.min(e.minHeight,e.height)},_position:function(){var e=this.uiDialog.is(":visible");e||this.uiDialog.show(),this.uiDialog.position(this.options.position),e||this.uiDialog.hide()},_setOptions:function(t){var i=this,s=!1,o={};e.each(t,function(e,t){i._setOption(e,t),e in n&&(s=!0),e in r&&(o[e]=t)}),s&&(this._size(),this._position()),this.uiDialog.is(":data(ui-resizable)")&&this.uiDialog.resizable("option",o)},_setOption:function(e,t){var n,r,i=this.uiDialog;e==="dialogClass"&&i.removeClass(this.options.dialogClass).addClass(t);if(e==="disabled")return;this._super(e,t),e==="appendTo"&&this.uiDialog.appendTo(this._appendTo()),e==="buttons"&&this._createButtons(),e==="closeText"&&this.uiDialogTitlebarClose.button({label:""+t}),e==="draggable"&&(n=i.is(":data(ui-draggable)"),n&&!t&&i.draggable("destroy"),!n&&t&&this._makeDraggable()),e==="position"&&this._position(),e==="resizable"&&(r=i.is(":data(ui-resizable)"),r&&!t&&i.resizable("destroy"),r&&typeof t=="string"&&i.resizable("option","handles",t),!r&&t!==!1&&this._makeResizable()),e==="title"&&this._title(this.uiDialogTitlebar.find(".ui-dialog-title"))},_size:function(){var e,t,n,r=this.options;this.element.show().css({width:"auto",minHeight:0,maxHeight:"none",height:0}),r.minWidth>r.width&&(r.width=r.minWidth),e=this.uiDialog.css({height:"auto",width:r.width}).outerHeight(),t=Math.max(0,r.minHeight-e),n=typeof r.maxHeight=="number"?Math.max(0,r.maxHeight-e):"none",r.height==="auto"?this.element.css({minHeight:t,maxHeight:n,height:"auto"}):this.element.height(Math.max(0,r.height-e)),this.uiDialog.is(":data(ui-resizable)")&&this.uiDialog.resizable("option","minHeight",this._minHeight())},_createOverlay:function(){if(!this.options.modal)return;e.ui.dialog.overlayInstances||this._delay(function(){e.ui.dialog.overlayInstances&&this._on(this.document,{focusin:function(t){e(t.target).closest(".ui-dialog").length||(t.preventDefault(),e(".ui-dialog:visible:last .ui-dialog-content").data("ui-dialog")._focusTabbable())}})}),this.overlay=e("<div>").addClass("ui-widget-overlay ui-front").appendTo(this.document[0].body),this._on(this.overlay,{mousedown:"_keepFocus"}),e.ui.dialog.overlayInstances++},_destroyOverlay:function(){if(!this.options.modal)return;e.ui.dialog.overlayInstances--,e.ui.dialog.overlayInstances||this._off(this.document,"focusin"),this.overlay.remove()}}),e.ui.dialog.overlayInstances=0,e.uiBackCompat!==!1&&e.widget("ui.dialog",e.ui.dialog,{_position:function(){var t=this.options.position,n=[],r=[0,0],i;if(t){if(typeof t=="string"||typeof t=="object"&&"0"in t)n=t.split?t.split(" "):[t[0],t[1]],n.length===1&&(n[1]=n[0]),e.each(["left","top"],function(e,t){+n[e]===n[e]&&(r[e]=n[e],n[e]=t)}),t={my:n[0]+(r[0]<0?r[0]:"+"+r[0])+" "+n[1]+(r[1]<0?r[1]:"+"+r[1]),at:n.join(" ")};t=e.extend({},e.ui.dialog.prototype.options.position,t)}else t=e.ui.dialog.prototype.options.position;i=this.uiDialog.is(":visible"),i||this.uiDialog.show(),this.uiDialog.position(t),i||this.uiDialog.hide()}})})(jQuery);(function(e,t){e.widget("ui.menu",{version:"1.10.0",defaultElement:"<ul>",delay:300,options:{icons:{submenu:"ui-icon-carat-1-e"},menus:"ul",position:{my:"left top",at:"right top"},role:"menu",blur:null,focus:null,select:null},_create:function(){this.activeMenu=this.element,this.mouseHandled=!1,this.element.uniqueId().addClass("ui-menu ui-widget ui-widget-content ui-corner-all").toggleClass("ui-menu-icons",!!this.element.find(".ui-icon").length).attr({role:this.options.role,tabIndex:0}).bind("click"+this.eventNamespace,e.proxy(function(e){this.options.disabled&&e.preventDefault()},this)),this.options.disabled&&this.element.addClass("ui-state-disabled").attr("aria-disabled","true"),this._on({"mousedown .ui-menu-item > a":function(e){e.preventDefault()},"click .ui-state-disabled > a":function(e){e.preventDefault()},"click .ui-menu-item:has(a)":function(t){var n=e(t.target).closest(".ui-menu-item");!this.mouseHandled&&n.not(".ui-state-disabled").length&&(this.mouseHandled=!0,this.select(t),n.has(".ui-menu").length?this.expand(t):this.element.is(":focus")||(this.element.trigger("focus",[!0]),this.active&&this.active.parents(".ui-menu").length===1&&clearTimeout(this.timer)))},"mouseenter .ui-menu-item":function(t){var n=e(t.currentTarget);n.siblings().children(".ui-state-active").removeClass("ui-state-active"),this.focus(t,n)},mouseleave:"collapseAll","mouseleave .ui-menu":"collapseAll",focus:function(e,t){var n=this.active||this.element.children(".ui-menu-item").eq(0);t||this.focus(e,n)},blur:function(t){this._delay(function(){e.contains(this.element[0],this.document[0].activeElement)||this.collapseAll(t)})},keydown:"_keydown"}),this.refresh(),this._on(this.document,{click:function(t){e(t.target).closest(".ui-menu").length||this.collapseAll(t),this.mouseHandled=!1}})},_destroy:function(){this.element.removeAttr("aria-activedescendant").find(".ui-menu").addBack().removeClass("ui-menu ui-widget ui-widget-content ui-corner-all ui-menu-icons").removeAttr("role").removeAttr("tabIndex").removeAttr("aria-labelledby").removeAttr("aria-expanded").removeAttr("aria-hidden").removeAttr("aria-disabled").removeUniqueId().show(),this.element.find(".ui-menu-item").removeClass("ui-menu-item").removeAttr("role").removeAttr("aria-disabled").children("a").removeUniqueId().removeClass("ui-corner-all ui-state-hover").removeAttr("tabIndex").removeAttr("role").removeAttr("aria-haspopup").children().each(function(){var t=e(this);t.data("ui-menu-submenu-carat")&&t.remove()}),this.element.find(".ui-menu-divider").removeClass("ui-menu-divider ui-widget-content")},_keydown:function(t){function n(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}var r,i,s,o,u,a=!0;switch(t.keyCode){case e.ui.keyCode.PAGE_UP:this.previousPage(t);break;case e.ui.keyCode.PAGE_DOWN:this.nextPage(t);break;case e.ui.keyCode.HOME:this._move("first","first",t);break;case e.ui.keyCode.END:this._move("last","last",t);break;case e.ui.keyCode.UP:this.previous(t);break;case e.ui.keyCode.DOWN:this.next(t);break;case e.ui.keyCode.LEFT:this.collapse(t);break;case e.ui.keyCode.RIGHT:this.active&&!this.active.is(".ui-state-disabled")&&this.expand(t);break;case e.ui.keyCode.ENTER:case e.ui.keyCode.SPACE:this._activate(t);break;case e.ui.keyCode.ESCAPE:this.collapse(t);break;default:a=!1,i=this.previousFilter||"",s=String.fromCharCode(t.keyCode),o=!1,clearTimeout(this.filterTimer),s===i?o=!0:s=i+s,u=new RegExp("^"+n(s),"i"),r=this.activeMenu.children(".ui-menu-item").filter(function(){return u.test(e(this).children("a").text())}),r=o&&r.index(this.active.next())!==-1?this.active.nextAll(".ui-menu-item"):r,r.length||(s=String.fromCharCode(t.keyCode),u=new RegExp("^"+n(s),"i"),r=this.activeMenu.children(".ui-menu-item").filter(function(){return u.test(e(this).children("a").text())})),r.length?(this.focus(t,r),r.length>1?(this.previousFilter=s,this.filterTimer=this._delay(function(){delete this.previousFilter},1e3)):delete this.previousFilter):delete this.previousFilter}a&&t.preventDefault()},_activate:function(e){this.active.is(".ui-state-disabled")||(this.active.children("a[aria-haspopup='true']").length?this.expand(e):this.select(e))},refresh:function(){var t,n=this.options.icons.submenu,r=this.element.find(this.options.menus);r.filter(":not(.ui-menu)").addClass("ui-menu ui-widget ui-widget-content ui-corner-all").hide().attr({role:this.options.role,"aria-hidden":"true","aria-expanded":"false"}).each(function(){var t=e(this),r=t.prev("a"),i=e("<span>").addClass("ui-menu-icon ui-icon "+n).data("ui-menu-submenu-carat",!0);r.attr("aria-haspopup","true").prepend(i),t.attr("aria-labelledby",r.attr("id"))}),t=r.add(this.element),t.children(":not(.ui-menu-item):has(a)").addClass("ui-menu-item").attr("role","presentation").children("a").uniqueId().addClass("ui-corner-all").attr({tabIndex:-1,role:this._itemRole()}),t.children(":not(.ui-menu-item)").each(function(){var t=e(this);/[^\-—–\s]/.test(t.text())||t.addClass("ui-widget-content ui-menu-divider")}),t.children(".ui-state-disabled").attr("aria-disabled","true"),this.active&&!e.contains(this.element[0],this.active[0])&&this.blur()},_itemRole:function(){return{menu:"menuitem",listbox:"option"}[this.options.role]},_setOption:function(e,t){e==="icons"&&this.element.find(".ui-menu-icon").removeClass(this.options.icons.submenu).addClass(t.submenu),this._super(e,t)},focus:function(e,t){var n,r;this.blur(e,e&&e.type==="focus"),this._scrollIntoView(t),this.active=t.first(),r=this.active.children("a").addClass("ui-state-focus"),this.options.role&&this.element.attr("aria-activedescendant",r.attr("id")),this.active.parent().closest(".ui-menu-item").children("a:first").addClass("ui-state-active"),e&&e.type==="keydown"?this._close():this.timer=this._delay(function(){this._close()},this.delay),n=t.children(".ui-menu"),n.length&&/^mouse/.test(e.type)&&this._startOpening(n),this.activeMenu=t.parent(),this._trigger("focus",e,{item:t})},_scrollIntoView:function(t){var n,r,i,s,o,u;this._hasScroll()&&(n=parseFloat(e.css(this.activeMenu[0],"borderTopWidth"))||0,r=parseFloat(e.css(this.activeMenu[0],"paddingTop"))||0,i=t.offset().top-this.activeMenu.offset().top-n-r,s=this.activeMenu.scrollTop(),o=this.activeMenu.height(),u=t.height(),i<0?this.activeMenu.scrollTop(s+i):i+u>o&&this.activeMenu.scrollTop(s+i-o+u))},blur:function(e,t){t||clearTimeout(this.timer);if(!this.active)return;this.active.children("a").removeClass("ui-state-focus"),this.active=null,this._trigger("blur",e,{item:this.active})},_startOpening:function(e){clearTimeout(this.timer);if(e.attr("aria-hidden")!=="true")return;this.timer=this._delay(function(){this._close(),this._open(e)},this.delay)},_open:function(t){var n=e.extend({of:this.active},this.options.position);clearTimeout(this.timer),this.element.find(".ui-menu").not(t.parents(".ui-menu")).hide().attr("aria-hidden","true"),t.show().removeAttr("aria-hidden").attr("aria-expanded","true").position(n)},collapseAll:function(t,n){clearTimeout(this.timer),this.timer=this._delay(function(){var r=n?this.element:e(t&&t.target).closest(this.element.find(".ui-menu"));r.length||(r=this.element),this._close(r),this.blur(t),this.activeMenu=r},this.delay)},_close:function(e){e||(e=this.active?this.active.parent():this.element),e.find(".ui-menu").hide().attr("aria-hidden","true").attr("aria-expanded","false").end().find("a.ui-state-active").removeClass("ui-state-active")},collapse:function(e){var t=this.active&&this.active.parent().closest(".ui-menu-item",this.element);t&&t.length&&(this._close(),this.focus(e,t))},expand:function(e){var t=this.active&&this.active.children(".ui-menu ").children(".ui-menu-item").first();t&&t.length&&(this._open(t.parent()),this._delay(function(){this.focus(e,t)}))},next:function(e){this._move("next","first",e)},previous:function(e){this._move("prev","last",e)},isFirstItem:function(){return this.active&&!this.active.prevAll(".ui-menu-item").length},isLastItem:function(){return this.active&&!this.active.nextAll(".ui-menu-item").length},_move:function(e,t,n){var r;this.active&&(e==="first"||e==="last"?r=this.active[e==="first"?"prevAll":"nextAll"](".ui-menu-item").eq(-1):r=this.active[e+"All"](".ui-menu-item").eq(0));if(!r||!r.length||!this.active)r=this.activeMenu.children(".ui-menu-item")[t]();this.focus(n,r)},nextPage:function(t){var n,r,i;if(!this.active){this.next(t);return}if(this.isLastItem())return;this._hasScroll()?(r=this.active.offset().top,i=this.element.height(),this.active.nextAll(".ui-menu-item").each(function(){return n=e(this),n.offset().top-r-i<0}),this.focus(t,n)):this.focus(t,this.activeMenu.children(".ui-menu-item")[this.active?"last":"first"]())},previousPage:function(t){var n,r,i;if(!this.active){this.next(t);return}if(this.isFirstItem())return;this._hasScroll()?(r=this.active.offset().top,i=this.element.height(),this.active.prevAll(".ui-menu-item").each(function(){return n=e(this),n.offset().top-r+i>0}),this.focus(t,n)):this.focus(t,this.activeMenu.children(".ui-menu-item").first())},_hasScroll:function(){return this.element.outerHeight()<this.element.prop("scrollHeight")},select:function(t){this.active=this.active||e(t.target).closest(".ui-menu-item");var n={item:this.active};this.active.has(".ui-menu").length||this.collapseAll(t,!0),this._trigger("select",t,n)}})})(jQuery);(function(e,t){e.widget("ui.progressbar",{version:"1.10.0",options:{max:100,value:0,change:null,complete:null},min:0,_create:function(){this.oldValue=this.options.value=this._constrainedValue(),this.element.addClass("ui-progressbar ui-widget ui-widget-content ui-corner-all").attr({role:"progressbar","aria-valuemin":this.min}),this.valueDiv=e("<div class='ui-progressbar-value ui-widget-header ui-corner-left'></div>").appendTo(this.element),this._refreshValue()},_destroy:function(){this.element.removeClass("ui-progressbar ui-widget ui-widget-content ui-corner-all").removeAttr("role").removeAttr("aria-valuemin").removeAttr("aria-valuemax").removeAttr("aria-valuenow"),this.valueDiv.remove()},value:function(e){if(e===t)return this.options.value;this.options.value=this._constrainedValue(e),this._refreshValue()},_constrainedValue:function(e){return e===t&&(e=this.options.value),this.indeterminate=e===!1,typeof e!="number"&&(e=0),this.indeterminate?!1:Math.min(this.options.max,Math.max(this.min,e))},_setOptions:function(e){var t=e.value;delete e.value,this._super(e),this.options.value=this._constrainedValue(t),this._refreshValue()},_setOption:function(e,t){e==="max"&&(t=Math.max(this.min,t)),this._super(e,t)},_percentage:function(){return this.indeterminate?100:100*(this.options.value-this.min)/(this.options.max-this.min)},_refreshValue:function(){var t=this.options.value,n=this._percentage();this.valueDiv.toggle(this.indeterminate||t>this.min).toggleClass("ui-corner-right",t===this.options.max).width(n.toFixed(0)+"%"),this.element.toggleClass("ui-progressbar-indeterminate",this.indeterminate),this.indeterminate?(this.element.removeAttr("aria-valuenow"),this.overlayDiv||(this.overlayDiv=e("<div class='ui-progressbar-overlay'></div>").appendTo(this.valueDiv))):(this.element.attr({"aria-valuemax":this.options.max,"aria-valuenow":t}),this.overlayDiv&&(this.overlayDiv.remove(),this.overlayDiv=null)),this.oldValue!==t&&(this.oldValue=t,this._trigger("change")),t===this.options.max&&this._trigger("complete")}})})(jQuery);(function(e,t){var n=5;e.widget("ui.slider",e.ui.mouse,{version:"1.10.0",widgetEventPrefix:"slide",options:{animate:!1,distance:0,max:100,min:0,orientation:"horizontal",range:!1,step:1,value:0,values:null,change:null,slide:null,start:null,stop:null},_create:function(){var t,n,r=this.options,i=this.element.find(".ui-slider-handle").addClass("ui-state-default ui-corner-all"),s="<a class='ui-slider-handle ui-state-default ui-corner-all' href='#'></a>",o=[];this._keySliding=!1,this._mouseSliding=!1,this._animateOff=!0,this._handleIndex=null,this._detectOrientation(),this._mouseInit(),this.element.addClass("ui-slider ui-slider-"+this.orientation+" ui-widget"+" ui-widget-content"+" ui-corner-all"),this.range=e([]),r.range&&(r.range===!0&&(r.values?r.values.length&&r.values.length!==2?r.values=[r.values[0],r.values[0]]:e.isArray(r.values)&&(r.values=r.values.slice(0)):r.values=[this._valueMin(),this._valueMin()]),this.range=e("<div></div>").appendTo(this.element).addClass("ui-slider-range ui-widget-header"+(r.range==="min"||r.range==="max"?" ui-slider-range-"+r.range:""))),n=r.values&&r.values.length||1;for(t=i.length;t<n;t++)o.push(s);this.handles=i.add(e(o.join("")).appendTo(this.element)),this.handle=this.handles.eq(0),this.handles.add(this.range).filter("a").click(function(e){e.preventDefault()}).mouseenter(function(){r.disabled||e(this).addClass("ui-state-hover")}).mouseleave(function(){e(this).removeClass("ui-state-hover")}).focus(function(){r.disabled?e(this).blur():(e(".ui-slider .ui-state-focus").removeClass("ui-state-focus"),e(this).addClass("ui-state-focus"))}).blur(function(){e(this).removeClass("ui-state-focus")}),this.handles.each(function(t){e(this).data("ui-slider-handle-index",t)}),this._setOption("disabled",r.disabled),this._on(this.handles,this._handleEvents),this._refreshValue(),this._animateOff=!1},_destroy:function(){this.handles.remove(),this.range.remove(),this.element.removeClass("ui-slider ui-slider-horizontal ui-slider-vertical ui-widget ui-widget-content ui-corner-all"),this._mouseDestroy()},_mouseCapture:function(t){var n,r,i,s,o,u,a,f,l=this,c=this.options;return c.disabled?!1:(this.elementSize={width:this.element.outerWidth(),height:this.element.outerHeight()},this.elementOffset=this.element.offset(),n={x:t.pageX,y:t.pageY},r=this._normValueFromMouse(n),i=this._valueMax()-this._valueMin()+1,this.handles.each(function(t){var n=Math.abs(r-l.values(t));if(i>n||i===n&&(t===l._lastChangedValue||l.values(t)===c.min))i=n,s=e(this),o=t}),u=this._start(t,o),u===!1?!1:(this._mouseSliding=!0,this._handleIndex=o,s.addClass("ui-state-active").focus(),a=s.offset(),f=!e(t.target).parents().addBack().is(".ui-slider-handle"),this._clickOffset=f?{left:0,top:0}:{left:t.pageX-a.left-s.width()/2,top:t.pageY-a.top-s.height()/2-(parseInt(s.css("borderTopWidth"),10)||0)-(parseInt(s.css("borderBottomWidth"),10)||0)+(parseInt(s.css("marginTop"),10)||0)},this.handles.hasClass("ui-state-hover")||this._slide(t,o,r),this._animateOff=!0,!0))},_mouseStart:function(){return!0},_mouseDrag:function(e){var t={x:e.pageX,y:e.pageY},n=this._normValueFromMouse(t);return this._slide(e,this._handleIndex,n),!1},_mouseStop:function(e){return this.handles.removeClass("ui-state-active"),this._mouseSliding=!1,this._stop(e,this._handleIndex),this._change(e,this._handleIndex),this._handleIndex=null,this._clickOffset=null,this._animateOff=!1,!1},_detectOrientation:function(){this.orientation=this.options.orientation==="vertical"?"vertical":"horizontal"},_normValueFromMouse:function(e){var t,n,r,i,s;return this.orientation==="horizontal"?(t=this.elementSize.width,n=e.x-this.elementOffset.left-(this._clickOffset?this._clickOffset.left:0)):(t=this.elementSize.height,n=e.y-this.elementOffset.top-(this._clickOffset?this._clickOffset.top:0)),r=n/t,r>1&&(r=1),r<0&&(r=0),this.orientation==="vertical"&&(r=1-r),i=this._valueMax()-this._valueMin(),s=this._valueMin()+r*i,this._trimAlignValue(s)},_start:function(e,t){var n={handle:this.handles[t],value:this.value()};return this.options.values&&this.options.values.length&&(n.value=this.values(t),n.values=this.values()),this._trigger("start",e,n)},_slide:function(e,t,n){var r,i,s;this.options.values&&this.options.values.length?(r=this.values(t?0:1),this.options.values.length===2&&this.options.range===!0&&(t===0&&n>r||t===1&&n<r)&&(n=r),n!==this.values(t)&&(i=this.values(),i[t]=n,s=this._trigger("slide",e,{handle:this.handles[t],value:n,values:i}),r=this.values(t?0:1),s!==!1&&this.values(t,n,!0))):n!==this.value()&&(s=this._trigger("slide",e,{handle:this.handles[t],value:n}),s!==!1&&this.value(n))},_stop:function(e,t){var n={handle:this.handles[t],value:this.value()};this.options.values&&this.options.values.length&&(n.value=this.values(t),n.values=this.values()),this._trigger("stop",e,n)},_change:function(e,t){if(!this._keySliding&&!this._mouseSliding){var n={handle:this.handles[t],value:this.value()};this.options.values&&this.options.values.length&&(n.value=this.values(t),n.values=this.values()),this._lastChangedValue=t,this._trigger("change",e,n)}},value:function(e){if(arguments.length){this.options.value=this._trimAlignValue(e),this._refreshValue(),this._change(null,0);return}return this._value()},values:function(t,n){var r,i,s;if(arguments.length>1){this.options.values[t]=this._trimAlignValue(n),this._refreshValue(),this._change(null,t);return}if(!arguments.length)return this._values();if(!e.isArray(arguments[0]))return this.options.values&&this.options.values.length?this._values(t):this.value();r=this.options.values,i=arguments[0];for(s=0;s<r.length;s+=1)r[s]=this._trimAlignValue(i[s]),this._change(null,s);this._refreshValue()},_setOption:function(t,n){var r,i=0;e.isArray(this.options.values)&&(i=this.options.values.length),e.Widget.prototype._setOption.apply(this,arguments);switch(t){case"disabled":n?(this.handles.filter(".ui-state-focus").blur(),this.handles.removeClass("ui-state-hover"),this.handles.prop("disabled",!0)):this.handles.prop("disabled",!1);break;case"orientation":this._detectOrientation(),this.element.removeClass("ui-slider-horizontal ui-slider-vertical").addClass("ui-slider-"+this.orientation),this._refreshValue();break;case"value":this._animateOff=!0,this._refreshValue(),this._change(null,0),this._animateOff=!1;break;case"values":this._animateOff=!0,this._refreshValue();for(r=0;r<i;r+=1)this._change(null,r);this._animateOff=!1;break;case"min":case"max":this._animateOff=!0,this._refreshValue(),this._animateOff=!1}},_value:function(){var e=this.options.value;return e=this._trimAlignValue(e),e},_values:function(e){var t,n,r;if(arguments.length)return t=this.options.values[e],t=this._trimAlignValue(t),t;n=this.options.values.slice();for(r=0;r<n.length;r+=1)n[r]=this._trimAlignValue(n[r]);return n},_trimAlignValue:function(e){if(e<=this._valueMin())return this._valueMin();if(e>=this._valueMax())return this._valueMax();var t=this.options.step>0?this.options.step:1,n=(e-this._valueMin())%t,r=e-n;return Math.abs(n)*2>=t&&(r+=n>0?t:-t),parseFloat(r.toFixed(5))},_valueMin:function(){return this.options.min},_valueMax:function(){return this.options.max},_refreshValue:function(){var t,n,r,i,s,o=this.options.range,u=this.options,a=this,f=this._animateOff?!1:u.animate,l={};this.options.values&&this.options.values.length?this.handles.each(function(r){n=(a.values(r)-a._valueMin())/(a._valueMax()-a._valueMin())*100,l[a.orientation==="horizontal"?"left":"bottom"]=n+"%",e(this).stop(1,1)[f?"animate":"css"](l,u.animate),a.options.range===!0&&(a.orientation==="horizontal"?(r===0&&a.range.stop(1,1)[f?"animate":"css"]({left:n+"%"},u.animate),r===1&&a.range[f?"animate":"css"]({width:n-t+"%"},{queue:!1,duration:u.animate})):(r===0&&a.range.stop(1,1)[f?"animate":"css"]({bottom:n+"%"},u.animate),r===1&&a.range[f?"animate":"css"]({height:n-t+"%"},{queue:!1,duration:u.animate}))),t=n}):(r=this.value(),i=this._valueMin(),s=this._valueMax(),n=s!==i?(r-i)/(s-i)*100:0,l[this.orientation==="horizontal"?"left":"bottom"]=n+"%",this.handle.stop(1,1)[f?"animate":"css"](l,u.animate),o==="min"&&this.orientation==="horizontal"&&this.range.stop(1,1)[f?"animate":"css"]({width:n+"%"},u.animate),o==="max"&&this.orientation==="horizontal"&&this.range[f?"animate":"css"]({width:100-n+"%"},{queue:!1,duration:u.animate}),o==="min"&&this.orientation==="vertical"&&this.range.stop(1,1)[f?"animate":"css"]({height:n+"%"},u.animate),o==="max"&&this.orientation==="vertical"&&this.range[f?"animate":"css"]({height:100-n+"%"},{queue:!1,duration:u.animate}))},_handleEvents:{keydown:function(t){var r,i,s,o,u=e(t.target).data("ui-slider-handle-index");switch(t.keyCode){case e.ui.keyCode.HOME:case e.ui.keyCode.END:case e.ui.keyCode.PAGE_UP:case e.ui.keyCode.PAGE_DOWN:case e.ui.keyCode.UP:case e.ui.keyCode.RIGHT:case e.ui.keyCode.DOWN:case e.ui.keyCode.LEFT:t.preventDefault();if(!this._keySliding){this._keySliding=!0,e(t.target).addClass("ui-state-active"),r=this._start(t,u);if(r===!1)return}}o=this.options.step,this.options.values&&this.options.values.length?i=s=this.values(u):i=s=this.value();switch(t.keyCode){case e.ui.keyCode.HOME:s=this._valueMin();break;case e.ui.keyCode.END:s=this._valueMax();break;case e.ui.keyCode.PAGE_UP:s=this._trimAlignValue(i+(this._valueMax()-this._valueMin())/n);break;case e.ui.keyCode.PAGE_DOWN:s=this._trimAlignValue(i-(this._valueMax()-this._valueMin())/n);break;case e.ui.keyCode.UP:case e.ui.keyCode.RIGHT:if(i===this._valueMax())return;s=this._trimAlignValue(i+o);break;case e.ui.keyCode.DOWN:case e.ui.keyCode.LEFT:if(i===this._valueMin())return;s=this._trimAlignValue(i-o)}this._slide(t,u,s)},keyup:function(t){var n=e(t.target).data("ui-slider-handle-index");this._keySliding&&(this._keySliding=!1,this._stop(t,n),this._change(t,n),e(t.target).removeClass("ui-state-active"))}}})})(jQuery);(function(e){function t(e){return function(){var t=this.element.val();e.apply(this,arguments),this._refresh(),t!==this.element.val()&&this._trigger("change")}}e.widget("ui.spinner",{version:"1.10.0",defaultElement:"<input>",widgetEventPrefix:"spin",options:{culture:null,icons:{down:"ui-icon-triangle-1-s",up:"ui-icon-triangle-1-n"},incremental:!0,max:null,min:null,numberFormat:null,page:10,step:1,change:null,spin:null,start:null,stop:null},_create:function(){this._setOption("max",this.options.max),this._setOption("min",this.options.min),this._setOption("step",this.options.step),this._value(this.element.val(),!0),this._draw(),this._on(this._events),this._refresh(),this._on(this.window,{beforeunload:function(){this.element.removeAttr("autocomplete")}})},_getCreateOptions:function(){var t={},n=this.element;return e.each(["min","max","step"],function(e,r){var i=n.attr(r);i!==undefined&&i.length&&(t[r]=i)}),t},_events:{keydown:function(e){this._start(e)&&this._keydown(e)&&e.preventDefault()},keyup:"_stop",focus:function(){this.previous=this.element.val()},blur:function(e){if(this.cancelBlur){delete this.cancelBlur;return}this._refresh(),this.previous!==this.element.val()&&this._trigger("change",e)},mousewheel:function(e,t){if(!t)return;if(!this.spinning&&!this._start(e))return!1;this._spin((t>0?1:-1)*this.options.step,e),clearTimeout(this.mousewheelTimer),this.mousewheelTimer=this._delay(function(){this.spinning&&this._stop(e)},100),e.preventDefault()},"mousedown .ui-spinner-button":function(t){function n(){var e=this.element[0]===this.document[0].activeElement;e||(this.element.focus(),this.previous=r,this._delay(function(){this.previous=r}))}var r;r=this.element[0]===this.document[0].activeElement?this.previous:this.element.val(),t.preventDefault(),n.call(this),this.cancelBlur=!0,this._delay(function(){delete this.cancelBlur,n.call(this)});if(this._start(t)===!1)return;this._repeat(null,e(t.currentTarget).hasClass("ui-spinner-up")?1:-1,t)},"mouseup .ui-spinner-button":"_stop","mouseenter .ui-spinner-button":function(t){if(!e(t.currentTarget).hasClass("ui-state-active"))return;if(this._start(t)===!1)return!1;this._repeat(null,e(t.currentTarget).hasClass("ui-spinner-up")?1:-1,t)},"mouseleave .ui-spinner-button":"_stop"},_draw:function(){var e=this.uiSpinner=this.element.addClass("ui-spinner-input").attr("autocomplete","off").wrap(this._uiSpinnerHtml()).parent().append(this._buttonHtml());this.element.attr("role","spinbutton"),this.buttons=e.find(".ui-spinner-button").attr("tabIndex",-1).button().removeClass("ui-corner-all"),this.buttons.height()>Math.ceil(e.height()*.5)&&e.height()>0&&e.height(e.height()),this.options.disabled&&this.disable()},_keydown:function(t){var n=this.options,r=e.ui.keyCode;switch(t.keyCode){case r.UP:return this._repeat(null,1,t),!0;case r.DOWN:return this._repeat(null,-1,t),!0;case r.PAGE_UP:return this._repeat(null,n.page,t),!0;case r.PAGE_DOWN:return this._repeat(null,-n.page,t),!0}return!1},_uiSpinnerHtml:function(){return"<span class='ui-spinner ui-widget ui-widget-content ui-corner-all'></span>"},_buttonHtml:function(){return"<a class='ui-spinner-button ui-spinner-up ui-corner-tr'><span class='ui-icon "+this.options.icons.up+"'>▲</span>"+"</a>"+"<a class='ui-spinner-button ui-spinner-down ui-corner-br'>"+"<span class='ui-icon "+this.options.icons.down+"'>▼</span>"+"</a>"},_start:function(e){return!this.spinning&&this._trigger("start",e)===!1?!1:(this.counter||(this.counter=1),this.spinning=!0,!0)},_repeat:function(e,t,n){e=e||500,clearTimeout(this.timer),this.timer=this._delay(function(){this._repeat(40,t,n)},e),this._spin(t*this.options.step,n)},_spin:function(e,t){var n=this.value()||0;this.counter||(this.counter=1),n=this._adjustValue(n+e*this._increment(this.counter));if(!this.spinning||this._trigger("spin",t,{value:n})!==!1)this._value(n),this.counter++},_increment:function(t){var n=this.options.incremental;return n?e.isFunction(n)?n(t):Math.floor(t*t*t/5e4-t*t/500+17*t/200+1):1},_precision:function(){var e=this._precisionOf(this.options.step);return this.options.min!==null&&(e=Math.max(e,this._precisionOf(this.options.min))),e},_precisionOf:function(e){var t=e.toString(),n=t.indexOf(".");return n===-1?0:t.length-n-1},_adjustValue:function(e){var t,n,r=this.options;return t=r.min!==null?r.min:0,n=e-t,n=Math.round(n/r.step)*r.step,e=t+n,e=parseFloat(e.toFixed(this._precision())),r.max!==null&&e>r.max?r.max:r.min!==null&&e<r.min?r.min:e},_stop:function(e){if(!this.spinning)return;clearTimeout(this.timer),clearTimeout(this.mousewheelTimer),this.counter=0,this.spinning=!1,this._trigger("stop",e)},_setOption:function(e,t){if(e==="culture"||e==="numberFormat"){var n=this._parse(this.element.val());this.options[e]=t,this.element.val(this._format(n));return}(e==="max"||e==="min"||e==="step")&&typeof t=="string"&&(t=this._parse(t)),e==="icons"&&(this.buttons.first().find(".ui-icon").removeClass(this.options.icons.up).addClass(t.up),this.buttons.last().find(".ui-icon").removeClass(this.options.icons.down).addClass(t.down)),this._super(e,t),e==="disabled"&&(t?(this.element.prop("disabled",!0),this.buttons.button("disable")):(this.element.prop("disabled",!1),this.buttons.button("enable")))},_setOptions:t(function(e){this._super(e),this._value(this.element.val())}),_parse:function(e){return typeof e=="string"&&e!==""&&(e=window.Globalize&&this.options.numberFormat?Globalize.parseFloat(e,10,this.options.culture):+e),e===""||isNaN(e)?null:e},_format:function(e){return e===""?"":window.Globalize&&this.options.numberFormat?Globalize.format(e,this.options.numberFormat,this.options.culture):e},_refresh:function(){this.element.attr({"aria-valuemin":this.options.min,"aria-valuemax":this.options.max,"aria-valuenow":this._parse(this.element.val())})},_value:function(e,t){var n;e!==""&&(n=this._parse(e),n!==null&&(t||(n=this._adjustValue(n)),e=this._format(n))),this.element.val(e),this._refresh()},_destroy:function(){this.element.removeClass("ui-spinner-input").prop("disabled",!1).removeAttr("autocomplete").removeAttr("role").removeAttr("aria-valuemin").removeAttr("aria-valuemax").removeAttr("aria-valuenow"),this.uiSpinner.replaceWith(this.element)},stepUp:t(function(e){this._stepUp(e)}),_stepUp:function(e){this._start()&&(this._spin((e||1)*this.options.step),this._stop())},stepDown:t(function(e){this._stepDown(e)}),_stepDown:function(e){this._start()&&(this._spin((e||1)*-this.options.step),this._stop())},pageUp:t(function(e){this._stepUp((e||1)*this.options.page)}),pageDown:t(function(e){this._stepDown((e||1)*this.options.page)}),value:function(e){if(!arguments.length)return this._parse(this.element.val());t(this._value).call(this,e)},widget:function(){return this.uiSpinner}})})(jQuery);(function(e,t){function n(){return++i}function r(e){return e.hash.length>1&&decodeURIComponent(e.href.replace(s,""))===decodeURIComponent(location.href.replace(s,""))}var i=0,s=/#.*$/;e.widget("ui.tabs",{version:"1.10.0",delay:300,options:{active:null,collapsible:!1,event:"click",heightStyle:"content",hide:null,show:null,activate:null,beforeActivate:null,beforeLoad:null,load:null},_create:function(){var t=this,n=this.options;this.running=!1,this.element.addClass("ui-tabs ui-widget ui-widget-content ui-corner-all").toggleClass("ui-tabs-collapsible",n.collapsible).delegate(".ui-tabs-nav > li","mousedown"+this.eventNamespace,function(t){e(this).is(".ui-state-disabled")&&t.preventDefault()}).delegate(".ui-tabs-anchor","focus"+this.eventNamespace,function(){e(this).closest("li").is(".ui-state-disabled")&&this.blur()}),this._processTabs(),n.active=this._initialActive(),e.isArray(n.disabled)&&(n.disabled=e.unique(n.disabled.concat(e.map(this.tabs.filter(".ui-state-disabled"),function(e){return t.tabs.index(e)}))).sort()),this.options.active!==!1&&this.anchors.length?this.active=this._findActive(n.active):this.active=e(),this._refresh(),this.active.length&&this.load(n.active)},_initialActive:function(){var t=this.options.active,n=this.options.collapsible,r=location.hash.substring(1);if(t===null){r&&this.tabs.each(function(n,i){if(e(i).attr("aria-controls")===r)return t=n,!1}),t===null&&(t=this.tabs.index(this.tabs.filter(".ui-tabs-active")));if(t===null||t===-1)t=this.tabs.length?0:!1}return t!==!1&&(t=this.tabs.index(this.tabs.eq(t)),t===-1&&(t=n?!1:0)),!n&&t===!1&&this.anchors.length&&(t=0),t},_getCreateEventData:function(){return{tab:this.active,panel:this.active.length?this._getPanelForTab(this.active):e()}},_tabKeydown:function(t){var n=e(this.document[0].activeElement).closest("li"),r=this.tabs.index(n),i=!0;if(this._handlePageNav(t))return;switch(t.keyCode){case e.ui.keyCode.RIGHT:case e.ui.keyCode.DOWN:r++;break;case e.ui.keyCode.UP:case e.ui.keyCode.LEFT:i=!1,r--;break;case e.ui.keyCode.END:r=this.anchors.length-1;break;case e.ui.keyCode.HOME:r=0;break;case e.ui.keyCode.SPACE:t.preventDefault(),clearTimeout(this.activating),this._activate(r);return;case e.ui.keyCode.ENTER:t.preventDefault(),clearTimeout(this.activating),this._activate(r===this.options.active?!1:r);return;default:return}t.preventDefault(),clearTimeout(this.activating),r=this._focusNextTab(r,i),t.ctrlKey||(n.attr("aria-selected","false"),this.tabs.eq(r).attr("aria-selected","true"),this.activating=this._delay(function(){this.option("active",r)},this.delay))},_panelKeydown:function(t){if(this._handlePageNav(t))return;t.ctrlKey&&t.keyCode===e.ui.keyCode.UP&&(t.preventDefault(),this.active.focus())},_handlePageNav:function(t){if(t.altKey&&t.keyCode===e.ui.keyCode.PAGE_UP)return this._activate(this._focusNextTab(this.options.active-1,!1)),!0;if(t.altKey&&t.keyCode===e.ui.keyCode.PAGE_DOWN)return this._activate(this._focusNextTab(this.options.active+1,!0)),!0},_findNextTab:function(t,n){function r(){return t>i&&(t=0),t<0&&(t=i),t}var i=this.tabs.length-1;while(e.inArray(r(),this.options.disabled)!==-1)t=n?t+1:t-1;return t},_focusNextTab:function(e,t){return e=this._findNextTab(e,t),this.tabs.eq(e).focus(),e},_setOption:function(e,t){if(e==="active"){this._activate(t);return}if(e==="disabled"){this._setupDisabled(t);return}this._super(e,t),e==="collapsible"&&(this.element.toggleClass("ui-tabs-collapsible",t),!t&&this.options.active===!1&&this._activate(0)),e==="event"&&this._setupEvents(t),e==="heightStyle"&&this._setupHeightStyle(t)},_tabId:function(e){return e.attr("aria-controls")||"ui-tabs-"+n()},_sanitizeSelector:function(e){return e?e.replace(/[!"$%&'()*+,.\/:;<=>?@\[\]\^`{|}~]/g,"\\$&"):""},refresh:function(){var t=this.options,n=this.tablist.children(":has(a[href])");t.disabled=e.map(n.filter(".ui-state-disabled"),function(e){return n.index(e)}),this._processTabs(),t.active===!1||!this.anchors.length?(t.active=!1,this.active=e()):this.active.length&&!e.contains(this.tablist[0],this.active[0])?this.tabs.length===t.disabled.length?(t.active=!1,this.active=e()):this._activate(this._findNextTab(Math.max(0,t.active-1),!1)):t.active=this.tabs.index(this.active),this._refresh()},_refresh:function(){this._setupDisabled(this.options.disabled),this._setupEvents(this.options.event),this._setupHeightStyle(this.options.heightStyle),this.tabs.not(this.active).attr({"aria-selected":"false",tabIndex:-1}),this.panels.not(this._getPanelForTab(this.active)).hide().attr({"aria-expanded":"false","aria-hidden":"true"}),this.active.length?(this.active.addClass("ui-tabs-active ui-state-active").attr({"aria-selected":"true",tabIndex:0}),this._getPanelForTab(this.active).show().attr({"aria-expanded":"true","aria-hidden":"false"})):this.tabs.eq(0).attr("tabIndex",0)},_processTabs:function(){var t=this;this.tablist=this._getList().addClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all").attr("role","tablist"),this.tabs=this.tablist.find("> li:has(a[href])").addClass("ui-state-default ui-corner-top").attr({role:"tab",tabIndex:-1}),this.anchors=this.tabs.map(function(){return e("a",this)[0]}).addClass("ui-tabs-anchor").attr({role:"presentation",tabIndex:-1}),this.panels=e(),this.anchors.each(function(n,i){var s,o,u,a=e(i).uniqueId().attr("id"),f=e(i).closest("li"),l=f.attr("aria-controls");r(i)?(s=i.hash,o=t.element.find(t._sanitizeSelector(s))):(u=t._tabId(f),s="#"+u,o=t.element.find(s),o.length||(o=t._createPanel(u),o.insertAfter(t.panels[n-1]||t.tablist)),o.attr("aria-live","polite")),o.length&&(t.panels=t.panels.add(o)),l&&f.data("ui-tabs-aria-controls",l),f.attr({"aria-controls":s.substring(1),"aria-labelledby":a}),o.attr("aria-labelledby",a)}),this.panels.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").attr("role","tabpanel")},_getList:function(){return this.element.find("ol,ul").eq(0)},_createPanel:function(t){return e("<div>").attr("id",t).addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").data("ui-tabs-destroy",!0)},_setupDisabled:function(t){e.isArray(t)&&(t.length?t.length===this.anchors.length&&(t=!0):t=!1);for(var n=0,r;r=this.tabs[n];n++)t===!0||e.inArray(n,t)!==-1?e(r).addClass("ui-state-disabled").attr("aria-disabled","true"):e(r).removeClass("ui-state-disabled").removeAttr("aria-disabled");this.options.disabled=t},_setupEvents:function(t){var n={click:function(e){e.preventDefault()}};t&&e.each(t.split(" "),function(e,t){n[t]="_eventHandler"}),this._off(this.anchors.add(this.tabs).add(this.panels)),this._on(this.anchors,n),this._on(this.tabs,{keydown:"_tabKeydown"}),this._on(this.panels,{keydown:"_panelKeydown"}),this._focusable(this.tabs),this._hoverable(this.tabs)},_setupHeightStyle:function(t){var n,r=this.element.parent();t==="fill"?(n=r.height(),n-=this.element.outerHeight()-this.element.height(),this.element.siblings(":visible").each(function(){var t=e(this),r=t.css("position");if(r==="absolute"||r==="fixed")return;n-=t.outerHeight(!0)}),this.element.children().not(this.panels).each(function(){n-=e(this).outerHeight(!0)}),this.panels.each(function(){e(this).height(Math.max(0,n-e(this).innerHeight()+e(this).height()))}).css("overflow","auto")):t==="auto"&&(n=0,this.panels.each(function(){n=Math.max(n,e(this).height("").height())}).height(n))},_eventHandler:function(t){var n=this.options,r=this.active,i=e(t.currentTarget),s=i.closest("li"),o=s[0]===r[0],u=o&&n.collapsible,a=u?e():this._getPanelForTab(s),f=r.length?this._getPanelForTab(r):e(),l={oldTab:r,oldPanel:f,newTab:u?e():s,newPanel:a};t.preventDefault();if(s.hasClass("ui-state-disabled")||s.hasClass("ui-tabs-loading")||this.running||o&&!n.collapsible||this._trigger("beforeActivate",t,l)===!1)return;n.active=u?!1:this.tabs.index(s),this.active=o?e():s,this.xhr&&this.xhr.abort(),!f.length&&!a.length&&e.error("jQuery UI Tabs: Mismatching fragment identifier."),a.length&&this.load(this.tabs.index(s),t),this._toggle(t,l)},_toggle:function(t,n){function r(){s.running=!1,s._trigger("activate",t,n)}function i(){n.newTab.closest("li").addClass("ui-tabs-active ui-state-active"),o.length&&s.options.show?s._show(o,s.options.show,r):(o.show(),r())}var s=this,o=n.newPanel,u=n.oldPanel;this.running=!0,u.length&&this.options.hide?this._hide(u,this.options.hide,function(){n.oldTab.closest("li").removeClass("ui-tabs-active ui-state-active"),i()}):(n.oldTab.closest("li").removeClass("ui-tabs-active ui-state-active"),u.hide(),i()),u.attr({"aria-expanded":"false","aria-hidden":"true"}),n.oldTab.attr("aria-selected","false"),o.length&&u.length?n.oldTab.attr("tabIndex",-1):o.length&&this.tabs.filter(function(){return e(this).attr("tabIndex")===0}).attr("tabIndex",-1),o.attr({"aria-expanded":"true","aria-hidden":"false"}),n.newTab.attr({"aria-selected":"true",tabIndex:0})},_activate:function(t){var n,r=this._findActive(t);if(r[0]===this.active[0])return;r.length||(r=this.active),n=r.find(".ui-tabs-anchor")[0],this._eventHandler({target:n,currentTarget:n,preventDefault:e.noop})},_findActive:function(t){return t===!1?e():this.tabs.eq(t)},_getIndex:function(e){return typeof e=="string"&&(e=this.anchors.index(this.anchors.filter("[href$='"+e+"']"))),e},_destroy:function(){this.xhr&&this.xhr.abort(),this.element.removeClass("ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible"),this.tablist.removeClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all").removeAttr("role"),this.anchors.removeClass("ui-tabs-anchor").removeAttr("role").removeAttr("tabIndex").removeUniqueId(),this.tabs.add(this.panels).each(function(){e.data(this,"ui-tabs-destroy")?e(this).remove():e(this).removeClass("ui-state-default ui-state-active ui-state-disabled ui-corner-top ui-corner-bottom ui-widget-content ui-tabs-active ui-tabs-panel").removeAttr("tabIndex").removeAttr("aria-live").removeAttr("aria-busy").removeAttr("aria-selected").removeAttr("aria-labelledby").removeAttr("aria-hidden").removeAttr("aria-expanded").removeAttr("role")}),this.tabs.each(function(){var t=e(this),n=t.data("ui-tabs-aria-controls");n?t.attr("aria-controls",n).removeData("ui-tabs-aria-controls"):t.removeAttr("aria-controls")}),this.panels.show(),this.options.heightStyle!=="content"&&this.panels.css("height","")},enable:function(n){var r=this.options.disabled;if(r===!1)return;n===t?r=!1:(n=this._getIndex(n),e.isArray(r)?r=e.map(r,function(e){return e!==n?e:null}):r=e.map(this.tabs,function(e,t){return t!==n?t:null})),this._setupDisabled(r)},disable:function(n){var r=this.options.disabled;if(r===!0)return;if(n===t)r=!0;else{n=this._getIndex(n);if(e.inArray(n,r)!==-1)return;e.isArray(r)?r=e.merge([n],r).sort():r=[n]}this._setupDisabled(r)},load:function(t,n){t=this._getIndex(t);var i=this,s=this.tabs.eq(t),o=s.find(".ui-tabs-anchor"),u=this._getPanelForTab(s),a={tab:s,panel:u};if(r(o[0]))return;this.xhr=e.ajax(this._ajaxSettings(o,n,a)),this.xhr&&this.xhr.statusText!=="canceled"&&(s.addClass("ui-tabs-loading"),u.attr("aria-busy","true"),this.xhr.success(function(e){setTimeout(function(){u.html(e),i._trigger("load",n,a)},1)}).complete(function(e,t){setTimeout(function(){t==="abort"&&i.panels.stop(!1,!0),s.removeClass("ui-tabs-loading"),u.removeAttr("aria-busy"),e===i.xhr&&delete i.xhr},1)}))},_ajaxSettings:function(t,n,r){var i=this;return{url:t.attr("href"),beforeSend:function(t,s){return i._trigger("beforeLoad",n,e.extend({jqXHR:t,ajaxSettings:s},r))}}},_getPanelForTab:function(t){var n=e(t).attr("aria-controls");return this.element.find(this._sanitizeSelector("#"+n))}})})(jQuery);(function(e){function t(t,n){var r=(t.attr("aria-describedby")||"").split(/\s+/);r.push(n),t.data("ui-tooltip-id",n).attr("aria-describedby",e.trim(r.join(" ")))}function n(t){var n=t.data("ui-tooltip-id"),r=(t.attr("aria-describedby")||"").split(/\s+/),i=e.inArray(n,r);i!==-1&&r.splice(i,1),t.removeData("ui-tooltip-id"),r=e.trim(r.join(" ")),r?t.attr("aria-describedby",r):t.removeAttr("aria-describedby")}var r=0;e.widget("ui.tooltip",{version:"1.10.0",options:{content:function(){var t=e(this).attr("title")||"";return e("<a>").text(t).html()},hide:!0,items:"[title]:not([disabled])",position:{my:"left top+15",at:"left bottom",collision:"flipfit flip"},show:!0,tooltipClass:null,track:!1,close:null,open:null},_create:function(){this._on({mouseover:"open",focusin:"open"}),this.tooltips={},this.parents={},this.options.disabled&&this._disable()},_setOption:function(t,n){var r=this;if(t==="disabled"){this[n?"_disable":"_enable"](),this.options[t]=n;return}this._super(t,n),t==="content"&&e.each(this.tooltips,function(e,t){r._updateContent(t)})},_disable:function(){var t=this;e.each(this.tooltips,function(n,r){var i=e.Event("blur");i.target=i.currentTarget=r[0],t.close(i,!0)}),this.element.find(this.options.items).addBack().each(function(){var t=e(this);t.is("[title]")&&t.data("ui-tooltip-title",t.attr("title")).attr("title","")})},_enable:function(){this.element.find(this.options.items).addBack().each(function(){var t=e(this);t.data("ui-tooltip-title")&&t.attr("title",t.data("ui-tooltip-title"))})},open:function(t){var n=this,r=e(t?t.target:this.element).closest(this.options.items);if(!r.length||r.data("ui-tooltip-id"))return;r.attr("title")&&r.data("ui-tooltip-title",r.attr("title")),r.data("ui-tooltip-open",!0),t&&t.type==="mouseover"&&r.parents().each(function(){var t=e(this),r;t.data("ui-tooltip-open")&&(r=e.Event("blur"),r.target=r.currentTarget=this,n.close(r,!0)),t.attr("title")&&(t.uniqueId(),n.parents[this.id]={element:this,title:t.attr("title")},t.attr("title",""))}),this._updateContent(r,t)},_updateContent:function(e,t){var n,r=this.options.content,i=this,s=t?t.type:null;if(typeof r=="string")return this._open(t,e,r);n=r.call(e[0],function(n){if(!e.data("ui-tooltip-open"))return;i._delay(function(){t&&(t.type=s),this._open(t,e,n)})}),n&&this._open(t,e,n)},_open:function(n,r,i){function s(e){f.of=e;if(o.is(":hidden"))return;o.position(f)}var o,u,a,f=e.extend({},this.options.position);if(!i)return;o=this._find(r);if(o.length){o.find(".ui-tooltip-content").html(i);return}r.is("[title]")&&(n&&n.type==="mouseover"?r.attr("title",""):r.removeAttr("title")),o=this._tooltip(r),t(r,o.attr("id")),o.find(".ui-tooltip-content").html(i),this.options.track&&n&&/^mouse/.test(n.type)?(this._on(this.document,{mousemove:s}),s(n)):o.position(e.extend({of:r},this.options.position)),o.hide(),this._show(o,this.options.show),this.options.show&&this.options.show.delay&&(a=this.delayedShow=setInterval(function(){o.is(":visible")&&(s(f.of),clearInterval(a))},e.fx.interval)),this._trigger("open",n,{tooltip:o}),u={keyup:function(t){if(t.keyCode===e.ui.keyCode.ESCAPE){var n=e.Event(t);n.currentTarget=r[0],this.close(n,!0)}},remove:function(){this._removeTooltip(o)}};if(!n||n.type==="mouseover")u.mouseleave="close";if(!n||n.type==="focusin")u.focusout="close";this._on(!0,r,u)},close:function(t){var r=this,i=e(t?t.currentTarget:this.element),s=this._find(i);if(this.closing)return;clearInterval(this.delayedShow),i.data("ui-tooltip-title")&&i.attr("title",i.data("ui-tooltip-title")),n(i),s.stop(!0),this._hide(s,this.options.hide,function(){r._removeTooltip(e(this))}),i.removeData("ui-tooltip-open"),this._off(i,"mouseleave focusout keyup"),i[0]!==this.element[0]&&this._off(i,"remove"),this._off(this.document,"mousemove"),t&&t.type==="mouseleave"&&e.each(this.parents,function(t,n){e(n.element).attr("title",n.title),delete r.parents[t]}),this.closing=!0,this._trigger("close",t,{tooltip:s}),this.closing=!1},_tooltip:function(t){var n="ui-tooltip-"+r++,i=e("<div>").attr({id:n,role:"tooltip"}).addClass("ui-tooltip ui-widget ui-corner-all ui-widget-content "+(this.options.tooltipClass||""));return e("<div>").addClass("ui-tooltip-content").appendTo(i),i.appendTo(this.document[0].body),this.tooltips[n]=t,i},_find:function(t){var n=t.data("ui-tooltip-id");return n?e("#"+n):e()},_removeTooltip:function(e){e.remove(),delete this.tooltips[e.attr("id")]},_destroy:function(){var t=this;e.each(this.tooltips,function(n,r){var i=e.Event("blur");i.target=i.currentTarget=r[0],t.close(i,!0),e("#"+n).remove(),r.data("ui-tooltip-title")&&(r.attr("title",r.data("ui-tooltip-title")),r.removeData("ui-tooltip-title"))})}})})(jQuery);jQuery.effects||function(e,t){var n="ui-effects-";e.effects={effect:{}},function(e,t){function n(e,t,n){var r=l[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 r(t){var n=a(),r=n._rgba=[];return t=t.toLowerCase(),d(u,function(e,i){var s,o=i.re.exec(t),u=o&&i.parse(o),a=i.space||"rgba";if(u)return s=n[a](u),n[f[a].cache]=s[f[a].cache],r=n._rgba=s._rgba,!1}),r.length?(r.join()==="0,0,0,0"&&e.extend(r,p.transparent),n):p[t]}function i(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 s="backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor",o=/^([\-+])=\s*(\d+\.?\d*)/,u=[{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]]}}],a=e.Color=function(t,n,r,i){return new e.Color.fn.parse(t,n,r,i)},f={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"}}}},l={"byte":{floor:!0,max:255},percent:{max:1},degrees:{mod:360,floor:!0}},c=a.support={},h=e("<p>")[0],p,d=e.each;h.style.cssText="background-color:rgba(1,1,1,.5)",c.rgba=h.style.backgroundColor.indexOf("rgba")>-1,d(f,function(e,t){t.cache="_"+e,t.props.alpha={idx:3,type:"percent",def:1}}),a.fn=e.extend(a.prototype,{parse:function(i,s,o,u){if(i===t)return this._rgba=[null,null,null,null],this;if(i.jquery||i.nodeType)i=e(i).css(s),s=t;var l=this,c=e.type(i),h=this._rgba=[];s!==t&&(i=[i,s,o,u],c="array");if(c==="string")return this.parse(r(i)||p._default);if(c==="array")return d(f.rgba.props,function(e,t){h[t.idx]=n(i[t.idx],t)}),this;if(c==="object")return i instanceof a?d(f,function(e,t){i[t.cache]&&(l[t.cache]=i[t.cache].slice())}):d(f,function(t,r){var s=r.cache;d(r.props,function(e,t){if(!l[s]&&r.to){if(e==="alpha"||i[e]==null)return;l[s]=r.to(l._rgba)}l[s][t.idx]=n(i[e],t,!0)}),l[s]&&e.inArray(null,l[s].slice(0,3))<0&&(l[s][3]=1,r.from&&(l._rgba=r.from(l[s])))}),this},is:function(e){var t=a(e),n=!0,r=this;return d(f,function(e,i){var s,o=t[i.cache];return o&&(s=r[i.cache]||i.to&&i.to(r._rgba)||[],d(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 d(f,function(n,r){t[r.cache]&&e.push(n)}),e.pop()},transition:function(e,t){var r=a(e),i=r._space(),s=f[i],o=this.alpha()===0?a("transparent"):this,u=o[s.cache]||s.to(o._rgba),c=u.slice();return r=r[s.cache],d(s.props,function(e,i){var s=i.idx,o=u[s],a=r[s],f=l[i.type]||{};if(a===null)return;o===null?c[s]=a:(f.mod&&(a-o>f.mod/2?o+=f.mod:o-a>f.mod/2&&(o-=f.mod)),c[s]=n((a-o)*t+o,i))}),this[i](c)},blend:function(t){if(this._rgba[3]===1)return this;var n=this._rgba.slice(),r=n.pop(),i=a(t)._rgba;return a(e.map(n,function(e,t){return(1-r)*i[t]+r*e}))},toRgbaString:function(){var t="rgba(",n=e.map(this._rgba,function(e,t){return e==null?t>2?1:0:e});return n[3]===1&&(n.pop(),t="rgb("),t+n.join()+")"},toHslaString:function(){var t="hsla(",n=e.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(),t="hsl("),t+n.join()+")"},toHexString:function(t){var n=this._rgba.slice(),r=n.pop();return t&&n.push(~~(r*255)),"#"+e.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()}}),a.fn.parse.prototype=a.fn,f.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,u===0?c=0:f<=.5?c=u/a:c=u/(2-a),[Math.round(l)%360,c,f,i==null?1:i]},f.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],s=e[3],o=r<=.5?r*(1+n):r+n-r*n,u=2*r-o;return[Math.round(i(u,o,t+1/3)*255),Math.round(i(u,o,t)*255),Math.round(i(u,o,t-1/3)*255),s]},d(f,function(r,i){var s=i.props,u=i.cache,f=i.to,l=i.from;a.fn[r]=function(r){f&&!this[u]&&(this[u]=f(this._rgba));if(r===t)return this[u].slice();var i,o=e.type(r),c=o==="array"||o==="object"?r:arguments,h=this[u].slice();return d(s,function(e,t){var r=c[o==="object"?e:t.idx];r==null&&(r=h[t.idx]),h[t.idx]=n(r,t)}),l?(i=a(l(h)),i[u]=h,i):a(h)},d(s,function(t,n){if(a.fn[t])return;a.fn[t]=function(i){var s=e.type(i),u=t==="alpha"?this._hsla?"hsla":"rgba":r,a=this[u](),f=a[n.idx],l;return s==="undefined"?f:(s==="function"&&(i=i.call(this,f),s=e.type(i)),i==null&&n.empty?this:(s==="string"&&(l=o.exec(i),l&&(i=f+parseFloat(l[2])*(l[1]==="+"?1:-1))),a[n.idx]=i,this[u](a)))}})}),a.hook=function(t){var n=t.split(" ");d(n,function(t,n){e.cssHooks[n]={set:function(t,i){var s,o,u="";if(i!=="transparent"&&(e.type(i)!=="string"||(s=r(i)))){i=a(s||i);if(!c.rgba&&i._rgba[3]!==1){o=n==="backgroundColor"?t.parentNode:t;while((u===""||u==="transparent")&&o&&o.style)try{u=e.css(o,"backgroundColor"),o=o.parentNode}catch(f){}i=i.blend(u&&u!=="transparent"?u:"_default")}i=i.toRgbaString()}try{t.style[n]=i}catch(f){}}},e.fx.step[n]=function(t){t.colorInit||(t.start=a(t.elem,n),t.end=a(t.end),t.colorInit=!0),e.cssHooks[n].set(t.elem,t.start.transition(t.end,t.pos))}})},a.hook(s),e.cssHooks.borderColor={expand:function(e){var t={};return d(["Top","Right","Bottom","Left"],function(n,r){t["border"+r+"Color"]=e}),t}},p=e.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(t){var n,r,i=t.ownerDocument.defaultView?t.ownerDocument.defaultView.getComputedStyle(t,null):t.currentStyle,s={};if(i&&i.length&&i[0]&&i[i[0]]){r=i.length;while(r--)n=i[r],typeof i[n]=="string"&&(s[e.camelCase(n)]=i[n])}else for(n in i)typeof i[n]=="string"&&(s[n]=i[n]);return s}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.fn.addBack||(e.fn.addBack=function(e){return this.add(e==null?this.prevObject:this.prevObject.filter(e))}),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("*").addBack():s;f=f.map(function(){var t=e(this);return{el:t,start:n(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(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=e.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 r(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 i(t){return!t||typeof t=="number"||e.fx.speeds[t]?!0:typeof t=="string"&&!e.effects.effect[t]}e.extend(e.effects,{version:"1.10.0",save:function(e,t){for(var r=0;r<t.length;r++)t[r]!==null&&e.data(n+t[r],e[0].style[t[r]])},restore:function(e,r){var i,s;for(s=0;s<r.length;s++)r[s]!==null&&(i=e.data(n+r[s]),i===t&&(i=""),e.css(r[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 r(){e.isFunction(s)&&s.call(i[0]),e.isFunction(t)&&t()}var i=e(this),s=n.complete,u=n.mode;(i.is(":hidden")?u==="hide":u==="show")?r():o.call(i[0],n,r)}var n=r.apply(this,arguments),i=n.mode,s=n.queue,o=e.effects.effect[n.effect];return e.fx.off||!o?i?this[i](n.duration,n.complete):this.each(function(){n.complete&&n.complete.call(this)}):s===!1?this.each(t):this.queue(s||"fx",t)},_show:e.fn.show,show:function(e){if(i(e))return this._show.apply(this,arguments);var t=r.apply(this,arguments);return t.mode="show",this.effect.call(this,t)},_hide:e.fn.hide,hide:function(e){if(i(e))return this._hide.apply(this,arguments);var t=r.apply(this,arguments);return t.mode="hide",this.effect.call(this,t)},__toggle:e.fn.toggle,toggle:function(t){if(i(t)||typeof t=="boolean"||e.isFunction(t))return this.__toggle.apply(this,arguments);var n=r.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)
|
/Css/jquery_002.js
|
no_license
|
Aadil25/mvcphp
|
R
| true | true | 324,398 |
js
|
(function(e,t){function u(e){var t=o[e]={},n,r;e=e.split(/\s+/);for(n=0,r=e.length;n<r;n++){t[e[n]]=true}return t}function c(e,n,r){if(r===t&&e.nodeType===1){var i="data-"+n.replace(l,"-$1").toLowerCase();r=e.getAttribute(i);if(typeof r==="string"){try{r=r==="true"?true:r==="false"?false:r==="null"?null:s.isNumeric(r)?+r:f.test(r)?s.parseJSON(r):r}catch(o){}s.data(e,n,r)}else{r=t}}return r}function h(e){for(var t in e){if(t==="data"&&s.isEmptyObject(e[t])){continue}if(t!=="toJSON"){return false}}return true}function p(e,t,n){var r=t+"defer",i=t+"queue",o=t+"mark",u=s._data(e,r);if(u&&(n==="queue"||!s._data(e,i))&&(n==="mark"||!s._data(e,o))){setTimeout(function(){if(!s._data(e,i)&&!s._data(e,o)){s.removeData(e,r,true);u.fire()}},0)}}function H(){return false}function B(){return true}function W(e){return!e||!e.parentNode||e.parentNode.nodeType===11}function X(e,t,n){t=t||0;if(s.isFunction(t)){return s.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n})}else if(t.nodeType){return s.grep(e,function(e,r){return e===t===n})}else if(typeof t==="string"){var r=s.grep(e,function(e){return e.nodeType===1});if(q.test(t)){return s.filter(t,r,!n)}else{t=s.filter(t,r)}}return s.grep(e,function(e,r){return s.inArray(e,t)>=0===n})}function V(e){var t=$.split("|"),n=e.createDocumentFragment();if(n.createElement){while(t.length){n.createElement(t.pop())}}return n}function at(e,t){return s.nodeName(e,"table")?e.getElementsByTagName("tbody")[0]||e.appendChild(e.ownerDocument.createElement("tbody")):e}function ft(e,t){if(t.nodeType!==1||!s.hasData(e)){return}var n,r,i,o=s._data(e),u=s._data(t,o),a=o.events;if(a){delete u.handle;u.events={};for(n in a){for(r=0,i=a[n].length;r<i;r++){s.event.add(t,n,a[n][r])}}}if(u.data){u.data=s.extend({},u.data)}}function lt(e,t){var n;if(t.nodeType!==1){return}if(t.clearAttributes){t.clearAttributes()}if(t.mergeAttributes){t.mergeAttributes(e)}n=t.nodeName.toLowerCase();if(n==="object"){t.outerHTML=e.outerHTML}else if(n==="input"&&(e.type==="checkbox"||e.type==="radio")){if(e.checked){t.defaultChecked=t.checked=e.checked}if(t.value!==e.value){t.value=e.value}}else if(n==="option"){t.selected=e.defaultSelected}else if(n==="input"||n==="textarea"){t.defaultValue=e.defaultValue}else if(n==="script"&&t.text!==e.text){t.text=e.text}t.removeAttribute(s.expando);t.removeAttribute("_submit_attached");t.removeAttribute("_change_attached")}function ct(e){if(typeof e.getElementsByTagName!=="undefined"){return e.getElementsByTagName("*")}else if(typeof e.querySelectorAll!=="undefined"){return e.querySelectorAll("*")}else{return[]}}function ht(e){if(e.type==="checkbox"||e.type==="radio"){e.defaultChecked=e.checked}}function pt(e){var t=(e.nodeName||"").toLowerCase();if(t==="input"){ht(e)}else if(t!=="script"&&typeof e.getElementsByTagName!=="undefined"){s.grep(e.getElementsByTagName("input"),ht)}}function dt(e){var t=n.createElement("div");ut.appendChild(t);t.innerHTML=e.outerHTML;return t.firstChild}function kt(e,t,n){var r=t==="width"?e.offsetWidth:e.offsetHeight,i=t==="width"?1:0,o=4;if(r>0){if(n!=="border"){for(;i<o;i+=2){if(!n){r-=parseFloat(s.css(e,"padding"+xt[i]))||0}if(n==="margin"){r+=parseFloat(s.css(e,n+xt[i]))||0}else{r-=parseFloat(s.css(e,"border"+xt[i]+"Width"))||0}}}return r+"px"}r=Tt(e,t);if(r<0||r==null){r=e.style[t]}if(bt.test(r)){return r}r=parseFloat(r)||0;if(n){for(;i<o;i+=2){r+=parseFloat(s.css(e,"padding"+xt[i]))||0;if(n!=="padding"){r+=parseFloat(s.css(e,"border"+xt[i]+"Width"))||0}if(n==="margin"){r+=parseFloat(s.css(e,n+xt[i]))||0}}}return r+"px"}function Qt(e){return function(t,n){if(typeof t!=="string"){n=t;t="*"}if(s.isFunction(n)){var r=t.toLowerCase().split(qt),i=0,o=r.length,u,a,f;for(;i<o;i++){u=r[i];f=/^\+/.test(u);if(f){u=u.substr(1)||"*"}a=e[u]=e[u]||[];a[f?"unshift":"push"](n)}}}}function Gt(e,n,r,i,s,o){s=s||n.dataTypes[0];o=o||{};o[s]=true;var u=e[s],a=0,f=u?u.length:0,l=e===Wt,c;for(;a<f&&(l||!c);a++){c=u[a](n,r,i);if(typeof c==="string"){if(!l||o[c]){c=t}else{n.dataTypes.unshift(c);c=Gt(e,n,r,i,c,o)}}}if((l||!c)&&!o["*"]){c=Gt(e,n,r,i,"*",o)}return c}function Yt(e,n){var r,i,o=s.ajaxSettings.flatOptions||{};for(r in n){if(n[r]!==t){(o[r]?e:i||(i={}))[r]=n[r]}}if(i){s.extend(true,e,i)}}function Zt(e,t,n,r){if(s.isArray(t)){s.each(t,function(t,i){if(n||At.test(e)){r(e,i)}else{Zt(e+"["+(typeof i==="object"?t:"")+"]",i,n,r)}})}else if(!n&&s.type(t)==="object"){for(var i in t){Zt(e+"["+i+"]",t[i],n,r)}}else{r(e,t)}}function en(e,n,r){var i=e.contents,s=e.dataTypes,o=e.responseFields,u,a,f,l;for(a in o){if(a in r){n[o[a]]=r[a]}}while(s[0]==="*"){s.shift();if(u===t){u=e.mimeType||n.getResponseHeader("content-type")}}if(u){for(a in i){if(i[a]&&i[a].test(u)){s.unshift(a);break}}}if(s[0]in r){f=s[0]}else{for(a in r){if(!s[0]||e.converters[a+" "+s[0]]){f=a;break}if(!l){l=a}}f=f||l}if(f){if(f!==s[0]){s.unshift(f)}return r[f]}}function tn(e,n){if(e.dataFilter){n=e.dataFilter(n,e.dataType)}var r=e.dataTypes,i={},o,u,a=r.length,f,l=r[0],c,h,p,d,v;for(o=1;o<a;o++){if(o===1){for(u in e.converters){if(typeof u==="string"){i[u.toLowerCase()]=e.converters[u]}}}c=l;l=r[o];if(l==="*"){l=c}else if(c!=="*"&&c!==l){h=c+" "+l;p=i[h]||i["* "+l];if(!p){v=t;for(d in i){f=d.split(" ");if(f[0]===c||f[0]==="*"){v=i[f[1]+" "+l];if(v){d=i[d];if(d===true){p=v}else if(v===true){p=d}break}}}}if(!(p||v)){s.error("No conversion from "+h.replace(" "," to "))}if(p!==true){n=p?p(n):v(d(n))}}}return n}function an(){try{return new e.XMLHttpRequest}catch(t){}}function fn(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}function yn(){setTimeout(bn,0);return gn=s.now()}function bn(){gn=t}function wn(e,t){var n={};s.each(mn.concat.apply([],mn.slice(0,t)),function(){n[this]=e});return n}function En(e){if(!ln[e]){var t=n.body,r=s("<"+e+">").appendTo(t),i=r.css("display");r.remove();if(i==="none"||i===""){if(!cn){cn=n.createElement("iframe");cn.frameBorder=cn.width=cn.height=0}t.appendChild(cn);if(!hn||!cn.createElement){hn=(cn.contentWindow||cn.contentDocument).document;hn.write((s.support.boxModel?"<!doctype html>":"")+"<html><body>");hn.close()}r=hn.createElement(e);hn.body.appendChild(r);i=s.css(r,"display");t.removeChild(cn)}ln[e]=i}return ln[e]}function Nn(e){return s.isWindow(e)?e:e.nodeType===9?e.defaultView||e.parentWindow:false}var n=e.document,r=e.navigator,i=e.location;var s=function(){function H(){if(i.isReady){return}try{n.documentElement.doScroll("left")}catch(e){setTimeout(H,1);return}i.ready()}var i=function(e,t){return new i.fn.init(e,t,u)},s=e.jQuery,o=e.$,u,a=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,f=/\S/,l=/^\s+/,c=/\s+$/,h=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,p=/^[\],:{}\s]*$/,d=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,v=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,m=/(?:^|:|,)(?:\s*\[)+/g,g=/(webkit)[ \/]([\w.]+)/,y=/(opera)(?:.*version)?[ \/]([\w.]+)/,b=/(msie) ([\w.]+)/,w=/(mozilla)(?:.*? rv:([\w.]+))?/,E=/-([a-z]|[0-9])/ig,S=/^-ms-/,x=function(e,t){return(t+"").toUpperCase()},T=r.userAgent,N,C,k,L=Object.prototype.toString,A=Object.prototype.hasOwnProperty,O=Array.prototype.push,M=Array.prototype.slice,_=String.prototype.trim,D=Array.prototype.indexOf,P={};i.fn=i.prototype={constructor:i,init:function(e,r,s){var o,u,f,l;if(!e){return this}if(e.nodeType){this.context=this[0]=e;this.length=1;return this}if(e==="body"&&!r&&n.body){this.context=n;this[0]=n.body;this.selector=e;this.length=1;return this}if(typeof e==="string"){if(e.charAt(0)==="<"&&e.charAt(e.length-1)===">"&&e.length>=3){o=[null,e,null]}else{o=a.exec(e)}if(o&&(o[1]||!r)){if(o[1]){r=r instanceof i?r[0]:r;l=r?r.ownerDocument||r:n;f=h.exec(e);if(f){if(i.isPlainObject(r)){e=[n.createElement(f[1])];i.fn.attr.call(e,r,true)}else{e=[l.createElement(f[1])]}}else{f=i.buildFragment([o[1]],[l]);e=(f.cacheable?i.clone(f.fragment):f.fragment).childNodes}return i.merge(this,e)}else{u=n.getElementById(o[2]);if(u&&u.parentNode){if(u.id!==o[2]){return s.find(e)}this.length=1;this[0]=u}this.context=n;this.selector=e;return this}}else if(!r||r.jquery){return(r||s).find(e)}else{return this.constructor(r).find(e)}}else if(i.isFunction(e)){return s.ready(e)}if(e.selector!==t){this.selector=e.selector;this.context=e.context}return i.makeArray(e,this)},selector:"",jquery:"1.7.2",length:0,size:function(){return this.length},toArray:function(){return M.call(this,0)},get:function(e){return e==null?this.toArray():e<0?this[this.length+e]:this[e]},pushStack:function(e,t,n){var r=this.constructor();if(i.isArray(e)){O.apply(r,e)}else{i.merge(r,e)}r.prevObject=this;r.context=this.context;if(t==="find"){r.selector=this.selector+(this.selector?" ":"")+n}else if(t){r.selector=this.selector+"."+t+"("+n+")"}return r},each:function(e,t){return i.each(this,e,t)},ready:function(e){i.bindReady();C.add(e);return this},eq:function(e){e=+e;return 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(M.apply(this,arguments),"slice",M.call(arguments).join(","))},map:function(e){return this.pushStack(i.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:O,sort:[].sort,splice:[].splice};i.fn.init.prototype=i.fn;i.extend=i.fn.extend=function(){var e,n,r,s,o,u,a=arguments[0]||{},f=1,l=arguments.length,c=false;if(typeof a==="boolean"){c=a;a=arguments[1]||{};f=2}if(typeof a!=="object"&&!i.isFunction(a)){a={}}if(l===f){a=this;--f}for(;f<l;f++){if((e=arguments[f])!=null){for(n in e){r=a[n];s=e[n];if(a===s){continue}if(c&&s&&(i.isPlainObject(s)||(o=i.isArray(s)))){if(o){o=false;u=r&&i.isArray(r)?r:[]}else{u=r&&i.isPlainObject(r)?r:{}}a[n]=i.extend(c,u,s)}else if(s!==t){a[n]=s}}}}return a};i.extend({noConflict:function(t){if(e.$===i){e.$=o}if(t&&e.jQuery===i){e.jQuery=s}return i},isReady:false,readyWait:1,holdReady:function(e){if(e){i.readyWait++}else{i.ready(true)}},ready:function(e){if(e===true&&!--i.readyWait||e!==true&&!i.isReady){if(!n.body){return setTimeout(i.ready,1)}i.isReady=true;if(e!==true&&--i.readyWait>0){return}C.fireWith(n,[i]);if(i.fn.trigger){i(n).trigger("ready").off("ready")}}},bindReady:function(){if(C){return}C=i.Callbacks("once memory");if(n.readyState==="complete"){return setTimeout(i.ready,1)}if(n.addEventListener){n.addEventListener("DOMContentLoaded",k,false);e.addEventListener("load",i.ready,false)}else if(n.attachEvent){n.attachEvent("onreadystatechange",k);e.attachEvent("onload",i.ready);var t=false;try{t=e.frameElement==null}catch(r){}if(n.documentElement.doScroll&&t){H()}}},isFunction:function(e){return i.type(e)==="function"},isArray:Array.isArray||function(e){return i.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):P[L.call(e)]||"object"},isPlainObject:function(e){if(!e||i.type(e)!=="object"||e.nodeType||i.isWindow(e)){return false}try{if(e.constructor&&!A.call(e,"constructor")&&!A.call(e.constructor.prototype,"isPrototypeOf")){return false}}catch(n){return false}var r;for(r in e){}return r===t||A.call(e,r)},isEmptyObject:function(e){for(var t in e){return false}return true},error:function(e){throw new Error(e)},parseJSON:function(t){if(typeof t!=="string"||!t){return null}t=i.trim(t);if(e.JSON&&e.JSON.parse){return e.JSON.parse(t)}if(p.test(t.replace(d,"@").replace(v,"]").replace(m,""))){return(new Function("return "+t))()}i.error("Invalid JSON: "+t)},parseXML:function(n){if(typeof n!=="string"||!n){return null}var r,s;try{if(e.DOMParser){s=new DOMParser;r=s.parseFromString(n,"text/xml")}else{r=new ActiveXObject("Microsoft.XMLDOM");r.async="false";r.loadXML(n)}}catch(o){r=t}if(!r||!r.documentElement||r.getElementsByTagName("parsererror").length){i.error("Invalid XML: "+n)}return r},noop:function(){},globalEval:function(t){if(t&&f.test(t)){(e.execScript||function(t){e["eval"].call(e,t)})(t)}},camelCase:function(e){return e.replace(S,"ms-").replace(E,x)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toUpperCase()===t.toUpperCase()},each:function(e,n,r){var s,o=0,u=e.length,a=u===t||i.isFunction(e);if(r){if(a){for(s in e){if(n.apply(e[s],r)===false){break}}}else{for(;o<u;){if(n.apply(e[o++],r)===false){break}}}}else{if(a){for(s in e){if(n.call(e[s],s,e[s])===false){break}}}else{for(;o<u;){if(n.call(e[o],o,e[o++])===false){break}}}}return e},trim:_?function(e){return e==null?"":_.call(e)}:function(e){return e==null?"":e.toString().replace(l,"").replace(c,"")},makeArray:function(e,t){var n=t||[];if(e!=null){var r=i.type(e);if(e.length==null||r==="string"||r==="function"||r==="regexp"||i.isWindow(e)){O.call(n,e)}else{i.merge(n,e)}}return n},inArray:function(e,t,n){var r;if(t){if(D){return D.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=e.length,i=0;if(typeof n.length==="number"){for(var s=n.length;i<s;i++){e[r++]=n[i]}}else{while(n[i]!==t){e[r++]=n[i++]}}e.length=r;return e},grep:function(e,t,n){var r=[],i;n=!!n;for(var s=0,o=e.length;s<o;s++){i=!!t(e[s],s);if(n!==i){r.push(e[s])}}return r},map:function(e,n,r){var s,o,u=[],a=0,f=e.length,l=e instanceof i||f!==t&&typeof f==="number"&&(f>0&&e[0]&&e[f-1]||f===0||i.isArray(e));if(l){for(;a<f;a++){s=n(e[a],a,r);if(s!=null){u[u.length]=s}}}else{for(o in e){s=n(e[o],o,r);if(s!=null){u[u.length]=s}}}return u.concat.apply([],u)},guid:1,proxy:function(e,n){if(typeof n==="string"){var r=e[n];n=e;e=r}if(!i.isFunction(e)){return t}var s=M.call(arguments,2),o=function(){return e.apply(n,s.concat(M.call(arguments)))};o.guid=e.guid=e.guid||o.guid||i.guid++;return o},access:function(e,n,r,s,o,u,a){var f,l=r==null,c=0,h=e.length;if(r&&typeof r==="object"){for(c in r){i.access(e,n,c,r[c],1,u,s)}o=1}else if(s!==t){f=a===t&&i.isFunction(s);if(l){if(f){f=n;n=function(e,t,n){return f.call(i(e),n)}}else{n.call(e,s);n=null}}if(n){for(;c<h;c++){n(e[c],r,f?s.call(e[c],c,n(e[c],r)):s,a)}}o=1}return o?e:l?n.call(e):h?n(e[0],r):u},now:function(){return(new Date).getTime()},uaMatch:function(e){e=e.toLowerCase();var t=g.exec(e)||y.exec(e)||b.exec(e)||e.indexOf("compatible")<0&&w.exec(e)||[];return{browser:t[1]||"",version:t[2]||"0"}},sub:function(){function e(t,n){return new e.fn.init(t,n)}i.extend(true,e,this);e.superclass=this;e.fn=e.prototype=this();e.fn.constructor=e;e.sub=this.sub;e.fn.init=function(r,s){if(s&&s instanceof i&&!(s instanceof e)){s=e(s)}return i.fn.init.call(this,r,s,t)};e.fn.init.prototype=e.fn;var t=e(n);return e},browser:{}});i.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(e,t){P["[object "+t+"]"]=t.toLowerCase()});N=i.uaMatch(T);if(N.browser){i.browser[N.browser]=true;i.browser.version=N.version}if(i.browser.webkit){i.browser.safari=true}if(f.test(" ")){l=/^[\s\xA0]+/;c=/[\s\xA0]+$/}u=i(n);if(n.addEventListener){k=function(){n.removeEventListener("DOMContentLoaded",k,false);i.ready()}}else if(n.attachEvent){k=function(){if(n.readyState==="complete"){n.detachEvent("onreadystatechange",k);i.ready()}}}return i}();var o={};s.Callbacks=function(e){e=e?o[e]||u(e):{};var n=[],r=[],i,a,f,l,c,h,p=function(t){var r,i,o,u,a;for(r=0,i=t.length;r<i;r++){o=t[r];u=s.type(o);if(u==="array"){p(o)}else if(u==="function"){if(!e.unique||!v.has(o)){n.push(o)}}}},d=function(t,s){s=s||[];i=!e.memory||[t,s];a=true;f=true;h=l||0;l=0;c=n.length;for(;n&&h<c;h++){if(n[h].apply(t,s)===false&&e.stopOnFalse){i=true;break}}f=false;if(n){if(!e.once){if(r&&r.length){i=r.shift();v.fireWith(i[0],i[1])}}else if(i===true){v.disable()}else{n=[]}}},v={add:function(){if(n){var e=n.length;p(arguments);if(f){c=n.length}else if(i&&i!==true){l=e;d(i[0],i[1])}}return this},remove:function(){if(n){var t=arguments,r=0,i=t.length;for(;r<i;r++){for(var s=0;s<n.length;s++){if(t[r]===n[s]){if(f){if(s<=c){c--;if(s<=h){h--}}}n.splice(s--,1);if(e.unique){break}}}}}return this},has:function(e){if(n){var t=0,r=n.length;for(;t<r;t++){if(e===n[t]){return true}}}return false},empty:function(){n=[];return this},disable:function(){n=r=i=t;return this},disabled:function(){return!n},lock:function(){r=t;if(!i||i===true){v.disable()}return this},locked:function(){return!r},fireWith:function(t,n){if(r){if(f){if(!e.once){r.push([t,n])}}else if(!(e.once&&i)){d(t,n)}}return this},fire:function(){v.fireWith(this,arguments);return this},fired:function(){return!!a}};return v};var a=[].slice;s.extend({Deferred:function(e){var t=s.Callbacks("once memory"),n=s.Callbacks("once memory"),r=s.Callbacks("memory"),i="pending",o={resolve:t,reject:n,notify:r},u={done:t.add,fail:n.add,progress:r.add,state:function(){return i},isResolved:t.fired,isRejected:n.fired,then:function(e,t,n){a.done(e).fail(t).progress(n);return this},always:function(){a.done.apply(a,arguments).fail.apply(a,arguments);return this},pipe:function(e,t,n){return s.Deferred(function(r){s.each({done:[e,"resolve"],fail:[t,"reject"],progress:[n,"notify"]},function(e,t){var n=t[0],i=t[1],o;if(s.isFunction(n)){a[e](function(){o=n.apply(this,arguments);if(o&&s.isFunction(o.promise)){o.promise().then(r.resolve,r.reject,r.notify)}else{r[i+"With"](this===a?r:this,[o])}})}else{a[e](r[i])}})}).promise()},promise:function(e){if(e==null){e=u}else{for(var t in u){e[t]=u[t]}}return e}},a=u.promise({}),f;for(f in o){a[f]=o[f].fire;a[f+"With"]=o[f].fireWith}a.done(function(){i="resolved"},n.disable,r.lock).fail(function(){i="rejected"},t.disable,r.lock);if(e){e.call(a,a)}return a},when:function(e){function c(e){return function(n){t[e]=arguments.length>1?a.call(arguments,0):n;if(!--o){f.resolveWith(f,t)}}}function h(e){return function(t){i[e]=arguments.length>1?a.call(arguments,0):t;f.notifyWith(l,i)}}var t=a.call(arguments,0),n=0,r=t.length,i=new Array(r),o=r,u=r,f=r<=1&&e&&s.isFunction(e.promise)?e:s.Deferred(),l=f.promise();if(r>1){for(;n<r;n++){if(t[n]&&t[n].promise&&s.isFunction(t[n].promise)){t[n].promise().then(c(n),f.reject,h(n))}else{--o}}if(!o){f.resolveWith(f,t)}}else if(f!==e){f.resolveWith(f,r?[e]:[])}return l}});s.support=function(){var t,r,i,o,u,a,f,l,c,h,p,d,v=n.createElement("div"),m=n.documentElement;v.setAttribute("className","t");v.innerHTML=" <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>";r=v.getElementsByTagName("*");i=v.getElementsByTagName("a")[0];if(!r||!r.length||!i){return{}}o=n.createElement("select");u=o.appendChild(n.createElement("option"));a=v.getElementsByTagName("input")[0];t={leadingWhitespace:v.firstChild.nodeType===3,tbody:!v.getElementsByTagName("tbody").length,htmlSerialize:!!v.getElementsByTagName("link").length,style:/top/.test(i.getAttribute("style")),hrefNormalized:i.getAttribute("href")==="/a",opacity:/^0.55/.test(i.style.opacity),cssFloat:!!i.style.cssFloat,checkOn:a.value==="on",optSelected:u.selected,getSetAttribute:v.className!=="t",enctype:!!n.createElement("form").enctype,html5Clone:n.createElement("nav").cloneNode(true).outerHTML!=="<:nav></:nav>",submitBubbles:true,changeBubbles:true,focusinBubbles:false,deleteExpando:true,noCloneEvent:true,inlineBlockNeedsLayout:false,shrinkWrapBlocks:false,reliableMarginRight:true,pixelMargin:true};s.boxModel=t.boxModel=n.compatMode==="CSS1Compat";a.checked=true;t.noCloneChecked=a.cloneNode(true).checked;o.disabled=true;t.optDisabled=!u.disabled;try{delete v.test}catch(g){t.deleteExpando=false}if(!v.addEventListener&&v.attachEvent&&v.fireEvent){v.attachEvent("onclick",function(){t.noCloneEvent=false});v.cloneNode(true).fireEvent("onclick")}a=n.createElement("input");a.value="t";a.setAttribute("type","radio");t.radioValue=a.value==="t";a.setAttribute("checked","checked");a.setAttribute("name","t");v.appendChild(a);f=n.createDocumentFragment();f.appendChild(v.lastChild);t.checkClone=f.cloneNode(true).cloneNode(true).lastChild.checked;t.appendChecked=a.checked;f.removeChild(a);f.appendChild(v);if(v.attachEvent){for(p in{submit:1,change:1,focusin:1}){h="on"+p;d=h in v;if(!d){v.setAttribute(h,"return;");d=typeof v[h]==="function"}t[p+"Bubbles"]=d}}f.removeChild(v);f=o=u=v=a=null;s(function(){var r,i,o,u,a,f,c,h,p,m,g,y,b,w=n.getElementsByTagName("body")[0];if(!w){return}h=1;b="padding:0;margin:0;border:";g="position:absolute;top:0;left:0;width:1px;height:1px;";y=b+"0;visibility:hidden;";p="style='"+g+b+"5px solid #000;";m="<div "+p+"display:block;'><div style='"+b+"0;display:block;overflow:hidden;'></div></div>"+"<table "+p+"' cellpadding='0' cellspacing='0'>"+"<tr><td></td></tr></table>";r=n.createElement("div");r.style.cssText=y+"width:0;height:0;position:static;top:0;margin-top:"+h+"px";w.insertBefore(r,w.firstChild);v=n.createElement("div");r.appendChild(v);v.innerHTML="<table><tr><td style='"+b+"0;display:none'></td><td>t</td></tr></table>";l=v.getElementsByTagName("td");d=l[0].offsetHeight===0;l[0].style.display="";l[1].style.display="none";t.reliableHiddenOffsets=d&&l[0].offsetHeight===0;if(e.getComputedStyle){v.innerHTML="";c=n.createElement("div");c.style.width="0";c.style.marginRight="0";v.style.width="2px";v.appendChild(c);t.reliableMarginRight=(parseInt((e.getComputedStyle(c,null)||{marginRight:0}).marginRight,10)||0)===0}if(typeof v.style.zoom!=="undefined"){v.innerHTML="";v.style.width=v.style.padding="1px";v.style.border=0;v.style.overflow="hidden";v.style.display="inline";v.style.zoom=1;t.inlineBlockNeedsLayout=v.offsetWidth===3;v.style.display="block";v.style.overflow="visible";v.innerHTML="<div style='width:5px;'></div>";t.shrinkWrapBlocks=v.offsetWidth!==3}v.style.cssText=g+y;v.innerHTML=m;i=v.firstChild;o=i.firstChild;a=i.nextSibling.firstChild.firstChild;f={doesNotAddBorder:o.offsetTop!==5,doesAddBorderForTableAndCells:a.offsetTop===5};o.style.position="fixed";o.style.top="20px";f.fixedPosition=o.offsetTop===20||o.offsetTop===15;o.style.position=o.style.top="";i.style.overflow="hidden";i.style.position="relative";f.subtractsBorderForOverflowNotVisible=o.offsetTop===-5;f.doesNotIncludeMarginInBodyOffset=w.offsetTop!==h;if(e.getComputedStyle){v.style.marginTop="1%";t.pixelMargin=(e.getComputedStyle(v,null)||{marginTop:0}).marginTop!=="1%"}if(typeof r.style.zoom!=="undefined"){r.style.zoom=1}w.removeChild(r);c=v=r=null;s.extend(t,f)});return t}();var f=/^(?:\{.*\}|\[.*\])$/,l=/([A-Z])/g;s.extend({cache:{},uuid:0,expando:"jQuery"+(s.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:true,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:true},hasData:function(e){e=e.nodeType?s.cache[e[s.expando]]:e[s.expando];return!!e&&!h(e)},data:function(e,n,r,i){if(!s.acceptData(e)){return}var o,u,a,f=s.expando,l=typeof n==="string",c=e.nodeType,h=c?s.cache:e,p=c?e[f]:e[f]&&f,d=n==="events";if((!p||!h[p]||!d&&!i&&!h[p].data)&&l&&r===t){return}if(!p){if(c){e[f]=p=++s.uuid}else{p=f}}if(!h[p]){h[p]={};if(!c){h[p].toJSON=s.noop}}if(typeof n==="object"||typeof n==="function"){if(i){h[p]=s.extend(h[p],n)}else{h[p].data=s.extend(h[p].data,n)}}o=u=h[p];if(!i){if(!u.data){u.data={}}u=u.data}if(r!==t){u[s.camelCase(n)]=r}if(d&&!u[n]){return o.events}if(l){a=u[n];if(a==null){a=u[s.camelCase(n)]}}else{a=u}return a},removeData:function(e,t,n){if(!s.acceptData(e)){return}var r,i,o,u=s.expando,a=e.nodeType,f=a?s.cache:e,l=a?e[u]:u;if(!f[l]){return}if(t){r=n?f[l]:f[l].data;if(r){if(!s.isArray(t)){if(t in r){t=[t]}else{t=s.camelCase(t);if(t in r){t=[t]}else{t=t.split(" ")}}}for(i=0,o=t.length;i<o;i++){delete r[t[i]]}if(!(n?h:s.isEmptyObject)(r)){return}}}if(!n){delete f[l].data;if(!h(f[l])){return}}if(s.support.deleteExpando||!f.setInterval){delete f[l]}else{f[l]=null}if(a){if(s.support.deleteExpando){delete e[u]}else if(e.removeAttribute){e.removeAttribute(u)}else{e[u]=null}}},_data:function(e,t,n){return s.data(e,t,n,true)},acceptData:function(e){if(e.nodeName){var t=s.noData[e.nodeName.toLowerCase()];if(t){return!(t===true||e.getAttribute("classid")!==t)}}return true}});s.fn.extend({data:function(e,n){var r,i,o,u,a,f=this[0],l=0,h=null;if(e===t){if(this.length){h=s.data(f);if(f.nodeType===1&&!s._data(f,"parsedAttrs")){o=f.attributes;for(a=o.length;l<a;l++){u=o[l].name;if(u.indexOf("data-")===0){u=s.camelCase(u.substring(5));c(f,u,h[u])}}s._data(f,"parsedAttrs",true)}}return h}if(typeof e==="object"){return this.each(function(){s.data(this,e)})}r=e.split(".",2);r[1]=r[1]?"."+r[1]:"";i=r[1]+"!";return s.access(this,function(n){if(n===t){h=this.triggerHandler("getData"+i,[r[0]]);if(h===t&&f){h=s.data(f,e);h=c(f,e,h)}return h===t&&r[1]?this.data(r[0]):h}r[1]=n;this.each(function(){var t=s(this);t.triggerHandler("setData"+i,r);s.data(this,e,n);t.triggerHandler("changeData"+i,r)})},null,n,arguments.length>1,null,false)},removeData:function(e){return this.each(function(){s.removeData(this,e)})}});s.extend({_mark:function(e,t){if(e){t=(t||"fx")+"mark";s._data(e,t,(s._data(e,t)||0)+1)}},_unmark:function(e,t,n){if(e!==true){n=t;t=e;e=false}if(t){n=n||"fx";var r=n+"mark",i=e?0:(s._data(t,r)||1)-1;if(i){s._data(t,r,i)}else{s.removeData(t,r,true);p(t,n,"mark")}}},queue:function(e,t,n){var r;if(e){t=(t||"fx")+"queue";r=s._data(e,t);if(n){if(!r||s.isArray(n)){r=s._data(e,t,s.makeArray(n))}else{r.push(n)}}return r||[]}},dequeue:function(e,t){t=t||"fx";var n=s.queue(e,t),r=n.shift(),i={};if(r==="inprogress"){r=n.shift()}if(r){if(t==="fx"){n.unshift("inprogress")}s._data(e,t+".run",i);r.call(e,function(){s.dequeue(e,t)},i)}if(!n.length){s.removeData(e,t+"queue "+t+".run",true);p(e,t,"queue")}}});s.fn.extend({queue:function(e,n){var r=2;if(typeof e!=="string"){n=e;e="fx";r--}if(arguments.length<r){return s.queue(this[0],e)}return n===t?this:this.each(function(){var t=s.queue(this,e,n);if(e==="fx"&&t[0]!=="inprogress"){s.dequeue(this,e)}})},dequeue:function(e){return this.each(function(){s.dequeue(this,e)})},delay:function(e,t){e=s.fx?s.fx.speeds[e]||e:e;t=t||"fx";return 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){function h(){if(!--u){r.resolveWith(i,[i])}}if(typeof e!=="string"){n=e;e=t}e=e||"fx";var r=s.Deferred(),i=this,o=i.length,u=1,a=e+"defer",f=e+"queue",l=e+"mark",c;while(o--){if(c=s.data(i[o],a,t,true)||(s.data(i[o],f,t,true)||s.data(i[o],l,t,true))&&s.data(i[o],a,s.Callbacks("once memory"),true)){u++;c.add(h)}}h();return r.promise(n)}});var d=/[\n\t\r]/g,v=/\s+/,m=/\r/g,g=/^(?:button|input)$/i,y=/^(?:button|input|object|select|textarea)$/i,b=/^a(?:rea)?$/i,w=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,E=s.support.getSetAttribute,S,x,T;s.fn.extend({attr:function(e,t){return s.access(this,s.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){s.removeAttr(this,e)})},prop:function(e,t){return s.access(this,s.prop,e,t,arguments.length>1)},removeProp:function(e){e=s.propFix[e]||e;return this.each(function(){try{this[e]=t;delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,o,u,a;if(s.isFunction(e)){return this.each(function(t){s(this).addClass(e.call(this,t,this.className))})}if(e&&typeof e==="string"){t=e.split(v);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{o=" "+i.className+" ";for(u=0,a=t.length;u<a;u++){if(!~o.indexOf(" "+t[u]+" ")){o+=t[u]+" "}}i.className=s.trim(o)}}}}return this},removeClass:function(e){var n,r,i,o,u,a,f;if(s.isFunction(e)){return this.each(function(t){s(this).removeClass(e.call(this,t,this.className))})}if(e&&typeof e==="string"||e===t){n=(e||"").split(v);for(r=0,i=this.length;r<i;r++){o=this[r];if(o.nodeType===1&&o.className){if(e){u=(" "+o.className+" ").replace(d," ");for(a=0,f=n.length;a<f;a++){u=u.replace(" "+n[a]+" "," ")}o.className=s.trim(u)}else{o.className=""}}}}return this},toggleClass:function(e,t){var n=typeof e,r=typeof t==="boolean";if(s.isFunction(e)){return this.each(function(n){s(this).toggleClass(e.call(this,n,this.className,t),t)})}return this.each(function(){if(n==="string"){var i,o=0,u=s(this),a=t,f=e.split(v);while(i=f[o++]){a=r?a:!u.hasClass(i);u[a?"addClass":"removeClass"](i)}}else if(n==="undefined"||n==="boolean"){if(this.className){s._data(this,"__className__",this.className)}this.className=this.className||e===false?"":s._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(d," ").indexOf(t)>-1){return true}}return false},val:function(e){var n,r,i,o=this[0];if(!arguments.length){if(o){n=s.valHooks[o.type]||s.valHooks[o.nodeName.toLowerCase()];if(n&&"get"in n&&(r=n.get(o,"value"))!==t){return r}r=o.value;return typeof r==="string"?r.replace(m,""):r==null?"":r}return}i=s.isFunction(e);return this.each(function(r){var o=s(this),u;if(this.nodeType!==1){return}if(i){u=e.call(this,r,o.val())}else{u=e}if(u==null){u=""}else if(typeof u==="number"){u+=""}else if(s.isArray(u)){u=s.map(u,function(e){return e==null?"":e+""})}n=s.valHooks[this.type]||s.valHooks[this.nodeName.toLowerCase()];if(!n||!("set"in n)||n.set(this,u,"value")===t){this.value=u}})}});s.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,o=e.selectedIndex,u=[],a=e.options,f=e.type==="select-one";if(o<0){return null}n=f?o:0;r=f?o+1:a.length;for(;n<r;n++){i=a[n];if(i.selected&&(s.support.optDisabled?!i.disabled:i.getAttribute("disabled")===null)&&(!i.parentNode.disabled||!s.nodeName(i.parentNode,"optgroup"))){t=s(i).val();if(f){return t}u.push(t)}}if(f&&!u.length&&a.length){return s(a[o]).val()}return u},set:function(e,t){var n=s.makeArray(t);s(e).find("option").each(function(){this.selected=s.inArray(s(this).val(),n)>=0});if(!n.length){e.selectedIndex=-1}return n}}},attrFn:{val:true,css:true,html:true,text:true,data:true,width:true,height:true,offset:true},attr:function(e,n,r,i){var o,u,a,f=e.nodeType;if(!e||f===3||f===8||f===2){return}if(i&&n in s.attrFn){return s(e)[n](r)}if(typeof e.getAttribute==="undefined"){return s.prop(e,n,r)}a=f!==1||!s.isXMLDoc(e);if(a){n=n.toLowerCase();u=s.attrHooks[n]||(w.test(n)?x:S)}if(r!==t){if(r===null){s.removeAttr(e,n);return}else if(u&&"set"in u&&a&&(o=u.set(e,r,n))!==t){return o}else{e.setAttribute(n,""+r);return r}}else if(u&&"get"in u&&a&&(o=u.get(e,n))!==null){return o}else{o=e.getAttribute(n);return o===null?t:o}},removeAttr:function(e,t){var n,r,i,o,u,a=0;if(t&&e.nodeType===1){r=t.toLowerCase().split(v);o=r.length;for(;a<o;a++){i=r[a];if(i){n=s.propFix[i]||i;u=w.test(i);if(!u){s.attr(e,i,"")}e.removeAttribute(E?i:n);if(u&&n in e){e[n]=false}}}}},attrHooks:{type:{set:function(e,t){if(g.test(e.nodeName)&&e.parentNode){s.error("type property can't be changed")}else if(!s.support.radioValue&&t==="radio"&&s.nodeName(e,"input")){var n=e.value;e.setAttribute("type",t);if(n){e.value=n}return t}}},value:{get:function(e,t){if(S&&s.nodeName(e,"button")){return S.get(e,t)}return t in e?e.value:null},set:function(e,t,n){if(S&&s.nodeName(e,"button")){return S.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,o,u,a=e.nodeType;if(!e||a===3||a===8||a===2){return}u=a!==1||!s.isXMLDoc(e);if(u){n=s.propFix[n]||n;o=s.propHooks[n]}if(r!==t){if(o&&"set"in o&&(i=o.set(e,r,n))!==t){return i}else{return e[n]=r}}else{if(o&&"get"in o&&(i=o.get(e,n))!==null){return i}else{return e[n]}}},propHooks:{tabIndex:{get:function(e){var n=e.getAttributeNode("tabindex");return n&&n.specified?parseInt(n.value,10):y.test(e.nodeName)||b.test(e.nodeName)&&e.href?0:t}}}});s.attrHooks.tabindex=s.propHooks.tabIndex;x={get:function(e,n){var r,i=s.prop(e,n);return i===true||typeof i!=="boolean"&&(r=e.getAttributeNode(n))&&r.nodeValue!==false?n.toLowerCase():t},set:function(e,t,n){var r;if(t===false){s.removeAttr(e,n)}else{r=s.propFix[n]||n;if(r in e){e[r]=true}e.setAttribute(n,n.toLowerCase())}return n}};if(!E){T={name:true,id:true,coords:true};S=s.valHooks.button={get:function(e,n){var r;r=e.getAttributeNode(n);return r&&(T[n]?r.nodeValue!=="":r.specified)?r.nodeValue:t},set:function(e,t,r){var i=e.getAttributeNode(r);if(!i){i=n.createAttribute(r);e.setAttributeNode(i)}return i.nodeValue=t+""}};s.attrHooks.tabindex.set=S.set;s.each(["width","height"],function(e,t){s.attrHooks[t]=s.extend(s.attrHooks[t],{set:function(e,n){if(n===""){e.setAttribute(t,"auto");return n}}})});s.attrHooks.contenteditable={get:S.get,set:function(e,t,n){if(t===""){t="false"}S.set(e,t,n)}}}if(!s.support.hrefNormalized){s.each(["href","src","width","height"],function(e,n){s.attrHooks[n]=s.extend(s.attrHooks[n],{get:function(e){var r=e.getAttribute(n,2);return r===null?t:r}})})}if(!s.support.style){s.attrHooks.style={get:function(e){return e.style.cssText.toLowerCase()||t},set:function(e,t){return e.style.cssText=""+t}}}if(!s.support.optSelected){s.propHooks.selected=s.extend(s.propHooks.selected,{get:function(e){var t=e.parentNode;if(t){t.selectedIndex;if(t.parentNode){t.parentNode.selectedIndex}}return null}})}if(!s.support.enctype){s.propFix.enctype="encoding"}if(!s.support.checkOn){s.each(["radio","checkbox"],function(){s.valHooks[this]={get:function(e){return e.getAttribute("value")===null?"on":e.value}}})}s.each(["radio","checkbox"],function(){s.valHooks[this]=s.extend(s.valHooks[this],{set:function(e,t){if(s.isArray(t)){return e.checked=s.inArray(s(e).val(),t)>=0}}})});var N=/^(?:textarea|input|select)$/i,C=/^([^\.]*)?(?:\.(.+))?$/,k=/(?:^|\s)hover(\.\S+)?\b/,L=/^key/,A=/^(?:mouse|contextmenu)|click/,O=/^(?:focusinfocus|focusoutblur)$/,M=/^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,_=function(e){var t=M.exec(e);if(t){t[1]=(t[1]||"").toLowerCase();t[3]=t[3]&&new RegExp("(?:^|\\s)"+t[3]+"(?:\\s|$)")}return t},D=function(e,t){var n=e.attributes||{};return(!t[1]||e.nodeName.toLowerCase()===t[1])&&(!t[2]||(n.id||{}).value===t[2])&&(!t[3]||t[3].test((n["class"]||{}).value))},P=function(e){return s.event.special.hover?e:e.replace(k,"mouseenter$1 mouseleave$1")};s.event={add:function(e,n,r,i,o){var u,a,f,l,c,h,p,d,v,m,g,y;if(e.nodeType===3||e.nodeType===8||!n||!r||!(u=s._data(e))){return}if(r.handler){v=r;r=v.handler;o=v.selector}if(!r.guid){r.guid=s.guid++}f=u.events;if(!f){u.events=f={}}a=u.handle;if(!a){u.handle=a=function(e){return typeof s!=="undefined"&&(!e||s.event.triggered!==e.type)?s.event.dispatch.apply(a.elem,arguments):t};a.elem=e}n=s.trim(P(n)).split(" ");for(l=0;l<n.length;l++){c=C.exec(n[l])||[];h=c[1];p=(c[2]||"").split(".").sort();y=s.event.special[h]||{};h=(o?y.delegateType:y.bindType)||h;y=s.event.special[h]||{};d=s.extend({type:h,origType:c[1],data:i,handler:r,guid:r.guid,selector:o,quick:o&&_(o),namespace:p.join(".")},v);g=f[h];if(!g){g=f[h]=[];g.delegateCount=0;if(!y.setup||y.setup.call(e,i,p,a)===false){if(e.addEventListener){e.addEventListener(h,a,false)}else if(e.attachEvent){e.attachEvent("on"+h,a)}}}if(y.add){y.add.call(e,d);if(!d.handler.guid){d.handler.guid=r.guid}}if(o){g.splice(g.delegateCount++,0,d)}else{g.push(d)}s.event.global[h]=true}e=null},global:{},remove:function(e,t,n,r,i){var o=s.hasData(e)&&s._data(e),u,a,f,l,c,h,p,d,v,m,g,y;if(!o||!(d=o.events)){return}t=s.trim(P(t||"")).split(" ");for(u=0;u<t.length;u++){a=C.exec(t[u])||[];f=l=a[1];c=a[2];if(!f){for(f in d){s.event.remove(e,f+t[u],n,r,true)}continue}v=s.event.special[f]||{};f=(r?v.delegateType:v.bindType)||f;g=d[f]||[];h=g.length;c=c?new RegExp("(^|\\.)"+c.split(".").sort().join("\\.(?:.*\\.)?")+"(\\.|$)"):null;for(p=0;p<g.length;p++){y=g[p];if((i||l===y.origType)&&(!n||n.guid===y.guid)&&(!c||c.test(y.namespace))&&(!r||r===y.selector||r==="**"&&y.selector)){g.splice(p--,1);if(y.selector){g.delegateCount--}if(v.remove){v.remove.call(e,y)}}}if(g.length===0&&h!==g.length){if(!v.teardown||v.teardown.call(e,c)===false){s.removeEvent(e,f,o.handle)}delete d[f]}}if(s.isEmptyObject(d)){m=o.handle;if(m){m.elem=null}s.removeData(e,["events","handle"],true)}},customEvent:{getData:true,setData:true,changeData:true},trigger:function(n,r,i,o){if(i&&(i.nodeType===3||i.nodeType===8)){return}var u=n.type||n,a=[],f,l,c,h,p,d,v,m,g,y;if(O.test(u+s.event.triggered)){return}if(u.indexOf("!")>=0){u=u.slice(0,-1);l=true}if(u.indexOf(".")>=0){a=u.split(".");u=a.shift();a.sort()}if((!i||s.event.customEvent[u])&&!s.event.global[u]){return}n=typeof n==="object"?n[s.expando]?n:new s.Event(u,n):new s.Event(u);n.type=u;n.isTrigger=true;n.exclusive=l;n.namespace=a.join(".");n.namespace_re=n.namespace?new RegExp("(^|\\.)"+a.join("\\.(?:.*\\.)?")+"(\\.|$)"):null;d=u.indexOf(":")<0?"on"+u:"";if(!i){f=s.cache;for(c in f){if(f[c].events&&f[c].events[u]){s.event.trigger(n,r,f[c].handle.elem,true)}}return}n.result=t;if(!n.target){n.target=i}r=r!=null?s.makeArray(r):[];r.unshift(n);v=s.event.special[u]||{};if(v.trigger&&v.trigger.apply(i,r)===false){return}g=[[i,v.bindType||u]];if(!o&&!v.noBubble&&!s.isWindow(i)){y=v.delegateType||u;h=O.test(y+u)?i:i.parentNode;p=null;for(;h;h=h.parentNode){g.push([h,y]);p=h}if(p&&p===i.ownerDocument){g.push([p.defaultView||p.parentWindow||e,y])}}for(c=0;c<g.length&&!n.isPropagationStopped();c++){h=g[c][0];n.type=g[c][1];m=(s._data(h,"events")||{})[n.type]&&s._data(h,"handle");if(m){m.apply(h,r)}m=d&&h[d];if(m&&s.acceptData(h)&&m.apply(h,r)===false){n.preventDefault()}}n.type=u;if(!o&&!n.isDefaultPrevented()){if((!v._default||v._default.apply(i.ownerDocument,r)===false)&&!(u==="click"&&s.nodeName(i,"a"))&&s.acceptData(i)){if(d&&i[u]&&(u!=="focus"&&u!=="blur"||n.target.offsetWidth!==0)&&!s.isWindow(i)){p=i[d];if(p){i[d]=null}s.event.triggered=u;i[u]();s.event.triggered=t;if(p){i[d]=p}}}}return n.result},dispatch:function(n){n=s.event.fix(n||e.event);var r=(s._data(this,"events")||{})[n.type]||[],i=r.delegateCount,o=[].slice.call(arguments,0),u=!n.exclusive&&!n.namespace,a=s.event.special[n.type]||{},f=[],l,c,h,p,d,v,m,g,y,b,w;o[0]=n;n.delegateTarget=this;if(a.preDispatch&&a.preDispatch.call(this,n)===false){return}if(i&&!(n.button&&n.type==="click")){p=s(this);p.context=this.ownerDocument||this;for(h=n.target;h!=this;h=h.parentNode||this){if(h.disabled!==true){v={};g=[];p[0]=h;for(l=0;l<i;l++){y=r[l];b=y.selector;if(v[b]===t){v[b]=y.quick?D(h,y.quick):p.is(b)}if(v[b]){g.push(y)}}if(g.length){f.push({elem:h,matches:g})}}}}if(r.length>i){f.push({elem:this,matches:r.slice(i)})}for(l=0;l<f.length&&!n.isPropagationStopped();l++){m=f[l];n.currentTarget=m.elem;for(c=0;c<m.matches.length&&!n.isImmediatePropagationStopped();c++){y=m.matches[c];if(u||!n.namespace&&!y.namespace||n.namespace_re&&n.namespace_re.test(y.namespace)){n.data=y.data;n.handleObj=y;d=((s.event.special[y.origType]||{}).handle||y.handler).apply(m.elem,o);if(d!==t){n.result=d;if(d===false){n.preventDefault();n.stopPropagation()}}}}}if(a.postDispatch){a.postDispatch.call(this,n)}return 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){if(e.which==null){e.which=t.charCode!=null?t.charCode:t.keyCode}return e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,r){var i,s,o,u=r.button,a=r.fromElement;if(e.pageX==null&&r.clientX!=null){i=e.target.ownerDocument||n;s=i.documentElement;o=i.body;e.pageX=r.clientX+(s&&s.scrollLeft||o&&o.scrollLeft||0)-(s&&s.clientLeft||o&&o.clientLeft||0);e.pageY=r.clientY+(s&&s.scrollTop||o&&o.scrollTop||0)-(s&&s.clientTop||o&&o.clientTop||0)}if(!e.relatedTarget&&a){e.relatedTarget=a===e.target?r.toElement:a}if(!e.which&&u!==t){e.which=u&1?1:u&2?3:u&4?2:0}return e}},fix:function(e){if(e[s.expando]){return e}var r,i,o=e,u=s.event.fixHooks[e.type]||{},a=u.props?this.props.concat(u.props):this.props;e=s.Event(o);for(r=a.length;r;){i=a[--r];e[i]=o[i]}if(!e.target){e.target=o.srcElement||n}if(e.target.nodeType===3){e.target=e.target.parentNode}if(e.metaKey===t){e.metaKey=e.ctrlKey}return u.filter?u.filter(e,o):e},special:{ready:{setup:s.bindReady},load:{noBubble:true},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(e,t,n){if(s.isWindow(this)){this.onbeforeunload=n}},teardown:function(e,t){if(this.onbeforeunload===t){this.onbeforeunload=null}}}},simulate:function(e,t,n,r){var i=s.extend(new s.Event,n,{type:e,isSimulated:true,originalEvent:{}});if(r){s.event.trigger(i,null,t)}else{s.event.dispatch.call(t,i)}if(i.isDefaultPrevented()){n.preventDefault()}}};s.event.handle=s.event.dispatch;s.removeEvent=n.removeEventListener?function(e,t,n){if(e.removeEventListener){e.removeEventListener(t,n,false)}}:function(e,t,n){if(e.detachEvent){e.detachEvent("on"+t,n)}};s.Event=function(e,t){if(!(this instanceof s.Event)){return new s.Event(e,t)}if(e&&e.type){this.originalEvent=e;this.type=e.type;this.isDefaultPrevented=e.defaultPrevented||e.returnValue===false||e.getPreventDefault&&e.defaultPrevented?B:H}else{this.type=e}if(t){s.extend(this,t)}this.timeStamp=e&&e.timeStamp||s.now();this[s.expando]=true};s.Event.prototype={preventDefault:function(){this.isDefaultPrevented=B;var e=this.originalEvent;if(!e){return}if(e.preventDefault){e.preventDefault()}else{e.returnValue=false}},stopPropagation:function(){this.isPropagationStopped=B;var e=this.originalEvent;if(!e){return}if(e.stopPropagation){e.stopPropagation()}e.cancelBubble=true},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=B;this.stopPropagation()},isDefaultPrevented:H,isPropagationStopped:H,isImmediatePropagationStopped:H};s.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){s.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n=this,r=e.relatedTarget,i=e.handleObj,o=i.selector,u;if(!r||r!==n&&!s.contains(n,r)){e.type=i.origType;u=i.handler.apply(this,arguments);e.type=t}return u}}});if(!s.support.submitBubbles){s.event.special.submit={setup:function(){if(s.nodeName(this,"form")){return false}s.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=s.nodeName(n,"input")||s.nodeName(n,"button")?n.form:t;if(r&&!r._submit_attached){s.event.add(r,"submit._submit",function(e){e._submit_bubble=true});r._submit_attached=true}})},postDispatch:function(e){if(e._submit_bubble){delete e._submit_bubble;if(this.parentNode&&!e.isTrigger){s.event.simulate("submit",this.parentNode,e,true)}}},teardown:function(){if(s.nodeName(this,"form")){return false}s.event.remove(this,"._submit")}}}if(!s.support.changeBubbles){s.event.special.change={setup:function(){if(N.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio"){s.event.add(this,"propertychange._change",function(e){if(e.originalEvent.propertyName==="checked"){this._just_changed=true}});s.event.add(this,"click._change",function(e){if(this._just_changed&&!e.isTrigger){this._just_changed=false;s.event.simulate("change",this,e,true)}})}return false}s.event.add(this,"beforeactivate._change",function(e){var t=e.target;if(N.test(t.nodeName)&&!t._change_attached){s.event.add(t,"change._change",function(e){if(this.parentNode&&!e.isSimulated&&!e.isTrigger){s.event.simulate("change",this.parentNode,e,true)}});t._change_attached=true}})},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(){s.event.remove(this,"._change");return N.test(this.nodeName)}}}if(!s.support.focusinBubbles){s.each({focus:"focusin",blur:"focusout"},function(e,t){var r=0,i=function(e){s.event.simulate(t,e.target,s.event.fix(e),true)};s.event.special[t]={setup:function(){if(r++===0){n.addEventListener(e,i,true)}},teardown:function(){if(--r===0){n.removeEventListener(e,i,true)}}}})}s.fn.extend({on:function(e,n,r,i,o){var u,a;if(typeof e==="object"){if(typeof n!=="string"){r=r||n;n=t}for(a in e){this.on(a,n,r,e[a],o)}return this}if(r==null&&i==null){i=n;r=n=t}else if(i==null){if(typeof n==="string"){i=r;r=t}else{i=r;r=n;n=t}}if(i===false){i=H}else if(!i){return this}if(o===1){u=i;i=function(e){s().off(e);return u.apply(this,arguments)};i.guid=u.guid||(u.guid=s.guid++)}return this.each(function(){s.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){if(e&&e.preventDefault&&e.handleObj){var i=e.handleObj;s(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler);return this}if(typeof e==="object"){for(var o in e){this.off(o,n,e[o])}return this}if(n===false||typeof n==="function"){r=n;n=t}if(r===false){r=H}return this.each(function(){s.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){s(this.context).on(e,this.selector,t,n);return this},die:function(e,t){s(this.context).off(e,this.selector||"**",t);return 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(){s.event.trigger(e,t,this)})},triggerHandler:function(e,t){if(this[0]){return s.event.trigger(e,t,this[0],true)}},toggle:function(e){var t=arguments,n=e.guid||s.guid++,r=0,i=function(n){var i=(s._data(this,"lastToggle"+e.guid)||0)%r;s._data(this,"lastToggle"+e.guid,i+1);n.preventDefault();return t[i].apply(this,arguments)||false};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)}});s.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){s.fn[t]=function(e,n){if(n==null){n=e;e=null}return arguments.length>0?this.on(t,null,e,n):this.trigger(t)};if(s.attrFn){s.attrFn[t]=true}if(L.test(t)){s.event.fixHooks[t]=s.event.keyHooks}if(A.test(t)){s.event.fixHooks[t]=s.event.mouseHooks}});(function(){function S(e,t,n,i,s,o){for(var u=0,a=i.length;u<a;u++){var f=i[u];if(f){var l=false;f=f[e];while(f){if(f[r]===n){l=i[f.sizset];break}if(f.nodeType===1&&!o){f[r]=n;f.sizset=u}if(f.nodeName.toLowerCase()===t){l=f;break}f=f[e]}i[u]=l}}}function x(e,t,n,i,s,o){for(var u=0,a=i.length;u<a;u++){var f=i[u];if(f){var l=false;f=f[e];while(f){if(f[r]===n){l=i[f.sizset];break}if(f.nodeType===1){if(!o){f[r]=n;f.sizset=u}if(typeof t!=="string"){if(f===t){l=true;break}}else if(h.filter(t,[f]).length>0){l=f;break}}f=f[e]}i[u]=l}}}var e=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,r="sizcache"+(Math.random()+"").replace(".",""),i=0,o=Object.prototype.toString,u=false,a=true,f=/\\/g,l=/\r\n/g,c=/\W/;[0,0].sort(function(){a=false;return 0});var h=function(t,r,i,s){i=i||[];r=r||n;var u=r;if(r.nodeType!==1&&r.nodeType!==9){return[]}if(!t||typeof t!=="string"){return i}var a,f,l,c,p,m,g,b,w=true,E=h.isXML(r),S=[],x=t;do{e.exec("");a=e.exec(x);if(a){x=a[3];S.push(a[1]);if(a[2]){c=a[3];break}}}while(a);if(S.length>1&&v.exec(t)){if(S.length===2&&d.relative[S[0]]){f=T(S[0]+S[1],r,s)}else{f=d.relative[S[0]]?[r]:h(S.shift(),r);while(S.length){t=S.shift();if(d.relative[t]){t+=S.shift()}f=T(t,f,s)}}}else{if(!s&&S.length>1&&r.nodeType===9&&!E&&d.match.ID.test(S[0])&&!d.match.ID.test(S[S.length-1])){p=h.find(S.shift(),r,E);r=p.expr?h.filter(p.expr,p.set)[0]:p.set[0]}if(r){p=s?{expr:S.pop(),set:y(s)}:h.find(S.pop(),S.length===1&&(S[0]==="~"||S[0]==="+")&&r.parentNode?r.parentNode:r,E);f=p.expr?h.filter(p.expr,p.set):p.set;if(S.length>0){l=y(f)}else{w=false}while(S.length){m=S.pop();g=m;if(!d.relative[m]){m=""}else{g=S.pop()}if(g==null){g=r}d.relative[m](l,g,E)}}else{l=S=[]}}if(!l){l=f}if(!l){h.error(m||t)}if(o.call(l)==="[object Array]"){if(!w){i.push.apply(i,l)}else if(r&&r.nodeType===1){for(b=0;l[b]!=null;b++){if(l[b]&&(l[b]===true||l[b].nodeType===1&&h.contains(r,l[b]))){i.push(f[b])}}}else{for(b=0;l[b]!=null;b++){if(l[b]&&l[b].nodeType===1){i.push(f[b])}}}}else{y(l,i)}if(c){h(c,u,i,s);h.uniqueSort(i)}return i};h.uniqueSort=function(e){if(w){u=a;e.sort(w);if(u){for(var t=1;t<e.length;t++){if(e[t]===e[t-1]){e.splice(t--,1)}}}}return e};h.matches=function(e,t){return h(e,null,null,t)};h.matchesSelector=function(e,t){return h(t,null,null,[e]).length>0};h.find=function(e,t,n){var r,i,s,o,u,a;if(!e){return[]}for(i=0,s=d.order.length;i<s;i++){u=d.order[i];if(o=d.leftMatch[u].exec(e)){a=o[1];o.splice(1,1);if(a.substr(a.length-1)!=="\\"){o[1]=(o[1]||"").replace(f,"");r=d.find[u](o,t,n);if(r!=null){e=e.replace(d.match[u],"");break}}}}if(!r){r=typeof t.getElementsByTagName!=="undefined"?t.getElementsByTagName("*"):[]}return{set:r,expr:e}};h.filter=function(e,n,r,i){var s,o,u,a,f,l,c,p,v,m=e,g=[],y=n,b=n&&n[0]&&h.isXML(n[0]);while(e&&n.length){for(u in d.filter){if((s=d.leftMatch[u].exec(e))!=null&&s[2]){l=d.filter[u];c=s[1];o=false;s.splice(1,1);if(c.substr(c.length-1)==="\\"){continue}if(y===g){g=[]}if(d.preFilter[u]){s=d.preFilter[u](s,y,r,g,i,b);if(!s){o=a=true}else if(s===true){continue}}if(s){for(p=0;(f=y[p])!=null;p++){if(f){a=l(f,s,p,y);v=i^a;if(r&&a!=null){if(v){o=true}else{y[p]=false}}else if(v){g.push(f);o=true}}}}if(a!==t){if(!r){y=g}e=e.replace(d.match[u],"");if(!o){return[]}break}}}if(e===m){if(o==null){h.error(e)}else{break}}m=e}return y};h.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)};var p=h.getText=function(e){var t,n,r=e.nodeType,i="";if(r){if(r===1||r===9||r===11){if(typeof e.textContent==="string"){return e.textContent}else if(typeof e.innerText==="string"){return e.innerText.replace(l,"")}else{for(e=e.firstChild;e;e=e.nextSibling){i+=p(e)}}}else if(r===3||r===4){return e.nodeValue}}else{for(t=0;n=e[t];t++){if(n.nodeType!==8){i+=p(n)}}}return i};var d=h.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(e){return e.getAttribute("href")},type:function(e){return e.getAttribute("type")}},relative:{"+":function(e,t){var n=typeof t==="string",r=n&&!c.test(t),i=n&&!r;if(r){t=t.toLowerCase()}for(var s=0,o=e.length,u;s<o;s++){if(u=e[s]){while((u=u.previousSibling)&&u.nodeType!==1){}e[s]=i||u&&u.nodeName.toLowerCase()===t?u||false:u===t}}if(i){h.filter(t,e,true)}},">":function(e,t){var n,r=typeof t==="string",i=0,s=e.length;if(r&&!c.test(t)){t=t.toLowerCase();for(;i<s;i++){n=e[i];if(n){var o=n.parentNode;e[i]=o.nodeName.toLowerCase()===t?o:false}}}else{for(;i<s;i++){n=e[i];if(n){e[i]=r?n.parentNode:n.parentNode===t}}if(r){h.filter(t,e,true)}}},"":function(e,t,n){var r,s=i++,o=x;if(typeof t==="string"&&!c.test(t)){t=t.toLowerCase();r=t;o=S}o("parentNode",t,s,e,r,n)},"~":function(e,t,n){var r,s=i++,o=x;if(typeof t==="string"&&!c.test(t)){t=t.toLowerCase();r=t;o=S}o("previousSibling",t,s,e,r,n)}},find:{ID:function(e,t,n){if(typeof t.getElementById!=="undefined"&&!n){var r=t.getElementById(e[1]);return r&&r.parentNode?[r]:[]}},NAME:function(e,t){if(typeof t.getElementsByName!=="undefined"){var n=[],r=t.getElementsByName(e[1]);for(var i=0,s=r.length;i<s;i++){if(r[i].getAttribute("name")===e[1]){n.push(r[i])}}return n.length===0?null:n}},TAG:function(e,t){if(typeof t.getElementsByTagName!=="undefined"){return t.getElementsByTagName(e[1])}}},preFilter:{CLASS:function(e,t,n,r,i,s){e=" "+e[1].replace(f,"")+" ";if(s){return e}for(var o=0,u;(u=t[o])!=null;o++){if(u){if(i^(u.className&&(" "+u.className+" ").replace(/[\t\n\r]/g," ").indexOf(e)>=0)){if(!n){r.push(u)}}else if(n){t[o]=false}}}return false},ID:function(e){return e[1].replace(f,"")},TAG:function(e,t){return e[1].replace(f,"").toLowerCase()},CHILD:function(e){if(e[1]==="nth"){if(!e[2]){h.error(e[0])}e[2]=e[2].replace(/^\+|\s*/g,"");var t=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(e[2]==="even"&&"2n"||e[2]==="odd"&&"2n+1"||!/\D/.test(e[2])&&"0n+"+e[2]||e[2]);e[2]=t[1]+(t[2]||1)-0;e[3]=t[3]-0}else if(e[2]){h.error(e[0])}e[0]=i++;return e},ATTR:function(e,t,n,r,i,s){var o=e[1]=e[1].replace(f,"");if(!s&&d.attrMap[o]){e[1]=d.attrMap[o]}e[4]=(e[4]||e[5]||"").replace(f,"");if(e[2]==="~="){e[4]=" "+e[4]+" "}return e},PSEUDO:function(t,n,r,i,s){if(t[1]==="not"){if((e.exec(t[3])||"").length>1||/^\w/.test(t[3])){t[3]=h(t[3],null,null,n)}else{var o=h.filter(t[3],n,r,true^s);if(!r){i.push.apply(i,o)}return false}}else if(d.match.POS.test(t[0])||d.match.CHILD.test(t[0])){return true}return t},POS:function(e){e.unshift(true);return e}},filters:{enabled:function(e){return e.disabled===false&&e.type!=="hidden"},disabled:function(e){return e.disabled===true},checked:function(e){return e.checked===true},selected:function(e){if(e.parentNode){e.parentNode.selectedIndex}return e.selected===true},parent:function(e){return!!e.firstChild},empty:function(e){return!e.firstChild},has:function(e,t,n){return!!h(n[3],e).length},header:function(e){return/h\d/i.test(e.nodeName)},text:function(e){var t=e.getAttribute("type"),n=e.type;return e.nodeName.toLowerCase()==="input"&&"text"===n&&(t===n||t===null)},radio:function(e){return e.nodeName.toLowerCase()==="input"&&"radio"===e.type},checkbox:function(e){return e.nodeName.toLowerCase()==="input"&&"checkbox"===e.type},file:function(e){return e.nodeName.toLowerCase()==="input"&&"file"===e.type},password:function(e){return e.nodeName.toLowerCase()==="input"&&"password"===e.type},submit:function(e){var t=e.nodeName.toLowerCase();return(t==="input"||t==="button")&&"submit"===e.type},image:function(e){return e.nodeName.toLowerCase()==="input"&&"image"===e.type},reset:function(e){var t=e.nodeName.toLowerCase();return(t==="input"||t==="button")&&"reset"===e.type},button:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&"button"===e.type||t==="button"},input:function(e){return/input|select|textarea|button/i.test(e.nodeName)},focus:function(e){return e===e.ownerDocument.activeElement}},setFilters:{first:function(e,t){return t===0},last:function(e,t,n,r){return t===r.length-1},even:function(e,t){return t%2===0},odd:function(e,t){return t%2===1},lt:function(e,t,n){return t<n[3]-0},gt:function(e,t,n){return t>n[3]-0},nth:function(e,t,n){return n[3]-0===t},eq:function(e,t,n){return n[3]-0===t}},filter:{PSEUDO:function(e,t,n,r){var i=t[1],s=d.filters[i];if(s){return s(e,n,t,r)}else if(i==="contains"){return(e.textContent||e.innerText||p([e])||"").indexOf(t[3])>=0}else if(i==="not"){var o=t[3];for(var u=0,a=o.length;u<a;u++){if(o[u]===e){return false}}return true}else{h.error(i)}},CHILD:function(e,t){var n,i,s,o,u,a,f,l=t[1],c=e;switch(l){case"only":case"first":while(c=c.previousSibling){if(c.nodeType===1){return false}}if(l==="first"){return true}c=e;case"last":while(c=c.nextSibling){if(c.nodeType===1){return false}}return true;case"nth":n=t[2];i=t[3];if(n===1&&i===0){return true}s=t[0];o=e.parentNode;if(o&&(o[r]!==s||!e.nodeIndex)){a=0;for(c=o.firstChild;c;c=c.nextSibling){if(c.nodeType===1){c.nodeIndex=++a}}o[r]=s}f=e.nodeIndex-i;if(n===0){return f===0}else{return f%n===0&&f/n>=0}}},ID:function(e,t){return e.nodeType===1&&e.getAttribute("id")===t},TAG:function(e,t){return t==="*"&&e.nodeType===1||!!e.nodeName&&e.nodeName.toLowerCase()===t},CLASS:function(e,t){return(" "+(e.className||e.getAttribute("class"))+" ").indexOf(t)>-1},ATTR:function(e,t){var n=t[1],r=h.attr?h.attr(e,n):d.attrHandle[n]?d.attrHandle[n](e):e[n]!=null?e[n]:e.getAttribute(n),i=r+"",s=t[2],o=t[4];return r==null?s==="!=":!s&&h.attr?r!=null:s==="="?i===o:s==="*="?i.indexOf(o)>=0:s==="~="?(" "+i+" ").indexOf(o)>=0:!o?i&&r!==false:s==="!="?i!==o:s==="^="?i.indexOf(o)===0:s==="$="?i.substr(i.length-o.length)===o:s==="|="?i===o||i.substr(0,o.length+1)===o+"-":false},POS:function(e,t,n,r){var i=t[2],s=d.setFilters[i];if(s){return s(e,n,t,r)}}}};var v=d.match.POS,m=function(e,t){return"\\"+(t-0+1)};for(var g in d.match){d.match[g]=new RegExp(d.match[g].source+/(?![^\[]*\])(?![^\(]*\))/.source);d.leftMatch[g]=new RegExp(/(^(?:.|\r|\n)*?)/.source+d.match[g].source.replace(/\\(\d+)/g,m))}d.match.globalPOS=v;var y=function(e,t){e=Array.prototype.slice.call(e,0);if(t){t.push.apply(t,e);return t}return e};try{Array.prototype.slice.call(n.documentElement.childNodes,0)[0].nodeType}catch(b){y=function(e,t){var n=0,r=t||[];if(o.call(e)==="[object Array]"){Array.prototype.push.apply(r,e)}else{if(typeof e.length==="number"){for(var i=e.length;n<i;n++){r.push(e[n])}}else{for(;e[n];n++){r.push(e[n])}}}return r}}var w,E;if(n.documentElement.compareDocumentPosition){w=function(e,t){if(e===t){u=true;return 0}if(!e.compareDocumentPosition||!t.compareDocumentPosition){return e.compareDocumentPosition?-1:1}return e.compareDocumentPosition(t)&4?-1:1}}else{w=function(e,t){if(e===t){u=true;return 0}else if(e.sourceIndex&&t.sourceIndex){return e.sourceIndex-t.sourceIndex}var n,r,i=[],s=[],o=e.parentNode,a=t.parentNode,f=o;if(o===a){return E(e,t)}else if(!o){return-1}else if(!a){return 1}while(f){i.unshift(f);f=f.parentNode}f=a;while(f){s.unshift(f);f=f.parentNode}n=i.length;r=s.length;for(var l=0;l<n&&l<r;l++){if(i[l]!==s[l]){return E(i[l],s[l])}}return l===n?E(e,s[l],-1):E(i[l],t,1)};E=function(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(){var e=n.createElement("div"),r="script"+(new Date).getTime(),i=n.documentElement;e.innerHTML="<a name='"+r+"'/>";i.insertBefore(e,i.firstChild);if(n.getElementById(r)){d.find.ID=function(e,n,r){if(typeof n.getElementById!=="undefined"&&!r){var i=n.getElementById(e[1]);return i?i.id===e[1]||typeof i.getAttributeNode!=="undefined"&&i.getAttributeNode("id").nodeValue===e[1]?[i]:t:[]}};d.filter.ID=function(e,t){var n=typeof e.getAttributeNode!=="undefined"&&e.getAttributeNode("id");return e.nodeType===1&&n&&n.nodeValue===t}}i.removeChild(e);i=e=null})();(function(){var e=n.createElement("div");e.appendChild(n.createComment(""));if(e.getElementsByTagName("*").length>0){d.find.TAG=function(e,t){var n=t.getElementsByTagName(e[1]);if(e[1]==="*"){var r=[];for(var i=0;n[i];i++){if(n[i].nodeType===1){r.push(n[i])}}n=r}return n}}e.innerHTML="<a href='#'></a>";if(e.firstChild&&typeof e.firstChild.getAttribute!=="undefined"&&e.firstChild.getAttribute("href")!=="#"){d.attrHandle.href=function(e){return e.getAttribute("href",2)}}e=null})();if(n.querySelectorAll){(function(){var e=h,t=n.createElement("div"),r="__sizzle__";t.innerHTML="<p class='TEST'></p>";if(t.querySelectorAll&&t.querySelectorAll(".TEST").length===0){return}h=function(t,i,s,o){i=i||n;if(!o&&!h.isXML(i)){var u=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(t);if(u&&(i.nodeType===1||i.nodeType===9)){if(u[1]){return y(i.getElementsByTagName(t),s)}else if(u[2]&&d.find.CLASS&&i.getElementsByClassName){return y(i.getElementsByClassName(u[2]),s)}}if(i.nodeType===9){if(t==="body"&&i.body){return y([i.body],s)}else if(u&&u[3]){var a=i.getElementById(u[3]);if(a&&a.parentNode){if(a.id===u[3]){return y([a],s)}}else{return y([],s)}}try{return y(i.querySelectorAll(t),s)}catch(f){}}else if(i.nodeType===1&&i.nodeName.toLowerCase()!=="object"){var l=i,c=i.getAttribute("id"),p=c||r,v=i.parentNode,m=/^\s*[+~]/.test(t);if(!c){i.setAttribute("id",p)}else{p=p.replace(/'/g,"\\$&")}if(m&&v){i=i.parentNode}try{if(!m||v){return y(i.querySelectorAll("[id='"+p+"'] "+t),s)}}catch(g){}finally{if(!c){l.removeAttribute("id")}}}}return e(t,i,s,o)};for(var i in e){h[i]=e[i]}t=null})()}(function(){var e=n.documentElement,t=e.matchesSelector||e.mozMatchesSelector||e.webkitMatchesSelector||e.msMatchesSelector;if(t){var r=!t.call(n.createElement("div"),"div"),i=false;try{t.call(n.documentElement,"[test!='']:sizzle")}catch(s){i=true}h.matchesSelector=function(e,n){n=n.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!h.isXML(e)){try{if(i||!d.match.PSEUDO.test(n)&&!/!=/.test(n)){var s=t.call(e,n);if(s||!r||e.document&&e.document.nodeType!==11){return s}}}catch(o){}}return h(n,null,null,[e]).length>0}}})();(function(){var e=n.createElement("div");e.innerHTML="<div class='test e'></div><div class='test'></div>";if(!e.getElementsByClassName||e.getElementsByClassName("e").length===0){return}e.lastChild.className="e";if(e.getElementsByClassName("e").length===1){return}d.order.splice(1,0,"CLASS");d.find.CLASS=function(e,t,n){if(typeof t.getElementsByClassName!=="undefined"&&!n){return t.getElementsByClassName(e[1])}};e=null})();if(n.documentElement.contains){h.contains=function(e,t){return e!==t&&(e.contains?e.contains(t):true)}}else if(n.documentElement.compareDocumentPosition){h.contains=function(e,t){return!!(e.compareDocumentPosition(t)&16)}}else{h.contains=function(){return false}}h.isXML=function(e){var t=(e?e.ownerDocument||e:0).documentElement;return t?t.nodeName!=="HTML":false};var T=function(e,t,n){var r,i=[],s="",o=t.nodeType?[t]:t;while(r=d.match.PSEUDO.exec(e)){s+=r[0];e=e.replace(d.match.PSEUDO,"")}e=d.relative[e]?e+"*":e;for(var u=0,a=o.length;u<a;u++){h(e,o[u],i,n)}return h.filter(s,i)};h.attr=s.attr;h.selectors.attrMap={};s.find=h;s.expr=h.selectors;s.expr[":"]=s.expr.filters;s.unique=h.uniqueSort;s.text=h.getText;s.isXMLDoc=h.isXML;s.contains=h.contains})();var j=/Until$/,F=/^(?:parents|prevUntil|prevAll)/,I=/,/,q=/^.[^:#\[\.,]*$/,R=Array.prototype.slice,U=s.expr.match.globalPOS,z={children:true,contents:true,next:true,prev:true};s.fn.extend({find:function(e){var t=this,n,r;if(typeof e!=="string"){return s(e).filter(function(){for(n=0,r=t.length;n<r;n++){if(s.contains(t[n],this)){return true}}})}var i=this.pushStack("","find",e),o,u,a;for(n=0,r=this.length;n<r;n++){o=i.length;s.find(e,this[n],i);if(n>0){for(u=o;u<i.length;u++){for(a=0;a<o;a++){if(i[a]===i[u]){i.splice(u--,1);break}}}}}return i},has:function(e){var t=s(e);return this.filter(function(){for(var e=0,n=t.length;e<n;e++){if(s.contains(this,t[e])){return true}}})},not:function(e){return this.pushStack(X(this,e,false),"not",e)},filter:function(e){return this.pushStack(X(this,e,true),"filter",e)},is:function(e){return!!e&&(typeof e==="string"?U.test(e)?s(e,this.context).index(this[0])>=0:s.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n=[],r,i,o=this[0];if(s.isArray(e)){var u=1;while(o&&o.ownerDocument&&o!==t){for(r=0;r<e.length;r++){if(s(o).is(e[r])){n.push({selector:e[r],elem:o,level:u})}}o=o.parentNode;u++}return n}var a=U.test(e)||typeof e!=="string"?s(e,t||this.context):0;for(r=0,i=this.length;r<i;r++){o=this[r];while(o){if(a?a.index(o)>-1:s.find.matchesSelector(o,e)){n.push(o);break}else{o=o.parentNode;if(!o||!o.ownerDocument||o===t||o.nodeType===11){break}}}}n=n.length>1?s.unique(n):n;return this.pushStack(n,"closest",e)},index:function(e){if(!e){return this[0]&&this[0].parentNode?this.prevAll().length:-1}if(typeof e==="string"){return s.inArray(this[0],s(e))}return s.inArray(e.jquery?e[0]:e,this)},add:function(e,t){var n=typeof e==="string"?s(e,t):s.makeArray(e&&e.nodeType?[e]:e),r=s.merge(this.get(),n);return this.pushStack(W(n[0])||W(r[0])?r:s.unique(r))},andSelf:function(){return this.add(this.prevObject)}});s.each({parent:function(e){var t=e.parentNode;return t&&t.nodeType!==11?t:null},parents:function(e){return s.dir(e,"parentNode")},parentsUntil:function(e,t,n){return s.dir(e,"parentNode",n)},next:function(e){return s.nth(e,2,"nextSibling")},prev:function(e){return s.nth(e,2,"previousSibling")},nextAll:function(e){return s.dir(e,"nextSibling")},prevAll:function(e){return s.dir(e,"previousSibling")},nextUntil:function(e,t,n){return s.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return s.dir(e,"previousSibling",n)},siblings:function(e){return s.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return s.sibling(e.firstChild)},contents:function(e){return s.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:s.makeArray(e.childNodes)}},function(e,t){s.fn[e]=function(n,r){var i=s.map(this,t,n);if(!j.test(e)){r=n}if(r&&typeof r==="string"){i=s.filter(r,i)}i=this.length>1&&!z[e]?s.unique(i):i;if((this.length>1||I.test(r))&&F.test(e)){i=i.reverse()}return this.pushStack(i,e,R.call(arguments).join(","))}});s.extend({filter:function(e,t,n){if(n){e=":not("+e+")"}return t.length===1?s.find.matchesSelector(t[0],e)?[t[0]]:[]:s.find.matches(e,t)},dir:function(e,n,r){var i=[],o=e[n];while(o&&o.nodeType!==9&&(r===t||o.nodeType!==1||!s(o).is(r))){if(o.nodeType===1){i.push(o)}o=o[n]}return i},nth:function(e,t,n,r){t=t||1;var i=0;for(;e;e=e[n]){if(e.nodeType===1&&++i===t){break}}return e},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling){if(e.nodeType===1&&e!==t){n.push(e)}}return n}});var $="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|"+"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",J=/ jQuery\d+="(?:\d+|null)"/g,K=/^\s+/,Q=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,G=/<([\w:]+)/,Y=/<tbody/i,Z=/<|&#?\w+;/,et=/<(?:script|style)/i,tt=/<(?:script|object|embed|option|style)/i,nt=new RegExp("<(?:"+$+")[\\s/>]","i"),rt=/checked\s*(?:[^=]|=\s*.checked.)/i,it=/\/(java|ecma)script/i,st=/^\s*<!(?:\[CDATA\[|\-\-)/,ot={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,"",""]},ut=V(n);ot.optgroup=ot.option;ot.tbody=ot.tfoot=ot.colgroup=ot.caption=ot.thead;ot.th=ot.td;if(!s.support.htmlSerialize){ot._default=[1,"div<div>","</div>"]}s.fn.extend({text:function(e){return s.access(this,function(e){return e===t?s.text(this):this.empty().append((this[0]&&this[0].ownerDocument||n).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(s.isFunction(e)){return this.each(function(t){s(this).wrapAll(e.call(this,t))})}if(this[0]){var t=s(e,this[0].ownerDocument).eq(0).clone(true);if(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){if(s.isFunction(e)){return this.each(function(t){s(this).wrapInner(e.call(this,t))})}return this.each(function(){var t=s(this),n=t.contents();if(n.length){n.wrapAll(e)}else{t.append(e)}})},wrap:function(e){var t=s.isFunction(e);return this.each(function(n){s(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){if(!s.nodeName(this,"body")){s(this).replaceWith(this.childNodes)}}).end()},append:function(){return this.domManip(arguments,true,function(e){if(this.nodeType===1){this.appendChild(e)}})},prepend:function(){return this.domManip(arguments,true,function(e){if(this.nodeType===1){this.insertBefore(e,this.firstChild)}})},before:function(){if(this[0]&&this[0].parentNode){return this.domManip(arguments,false,function(e){this.parentNode.insertBefore(e,this)})}else if(arguments.length){var e=s.clean(arguments);e.push.apply(e,this.toArray());return this.pushStack(e,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode){return this.domManip(arguments,false,function(e){this.parentNode.insertBefore(e,this.nextSibling)})}else if(arguments.length){var e=this.pushStack(this,"after",arguments);e.push.apply(e,s.clean(arguments));return e}},remove:function(e,t){for(var n=0,r;(r=this[n])!=null;n++){if(!e||s.filter(e,[r]).length){if(!t&&r.nodeType===1){s.cleanData(r.getElementsByTagName("*"));s.cleanData([r])}if(r.parentNode){r.parentNode.removeChild(r)}}}return this},empty:function(){for(var e=0,t;(t=this[e])!=null;e++){if(t.nodeType===1){s.cleanData(t.getElementsByTagName("*"))}while(t.firstChild){t.removeChild(t.firstChild)}}return this},clone:function(e,t){e=e==null?false:e;t=t==null?e:t;return this.map(function(){return s.clone(this,e,t)})},html:function(e){return s.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t){return n.nodeType===1?n.innerHTML.replace(J,""):null}if(typeof e==="string"&&!et.test(e)&&(s.support.leadingWhitespace||!K.test(e))&&!ot[(G.exec(e)||["",""])[1].toLowerCase()]){e=e.replace(Q,"<$1></$2>");try{for(;r<i;r++){n=this[r]||{};if(n.nodeType===1){s.cleanData(n.getElementsByTagName("*"));n.innerHTML=e}}n=0}catch(o){}}if(n){this.empty().append(e)}},null,e,arguments.length)},replaceWith:function(e){if(this[0]&&this[0].parentNode){if(s.isFunction(e)){return this.each(function(t){var n=s(this),r=n.html();n.replaceWith(e.call(this,t,r))})}if(typeof e!=="string"){e=s(e).detach()}return this.each(function(){var t=this.nextSibling,n=this.parentNode;s(this).remove();if(t){s(t).before(e)}else{s(n).append(e)}})}else{return this.length?this.pushStack(s(s.isFunction(e)?e():e),"replaceWith",e):this}},detach:function(e){return this.remove(e,true)},domManip:function(e,n,r){var i,o,u,a,f=e[0],l=[];if(!s.support.checkClone&&arguments.length===3&&typeof f==="string"&&rt.test(f)){return this.each(function(){s(this).domManip(e,n,r,true)})}if(s.isFunction(f)){return this.each(function(i){var o=s(this);e[0]=f.call(this,i,n?o.html():t);o.domManip(e,n,r)})}if(this[0]){a=f&&f.parentNode;if(s.support.parentNode&&a&&a.nodeType===11&&a.childNodes.length===this.length){i={fragment:a}}else{i=s.buildFragment(e,this,l)}u=i.fragment;if(u.childNodes.length===1){o=u=u.firstChild}else{o=u.firstChild}if(o){n=n&&s.nodeName(o,"tr");for(var c=0,h=this.length,p=h-1;c<h;c++){r.call(n?at(this[c],o):this[c],i.cacheable||h>1&&c<p?s.clone(u,true,true):u)}}if(l.length){s.each(l,function(e,t){if(t.src){s.ajax({type:"GET",global:false,url:t.src,async:false,dataType:"script"})}else{s.globalEval((t.text||t.textContent||t.innerHTML||"").replace(st,"/*$0*/"))}if(t.parentNode){t.parentNode.removeChild(t)}})}}return this}});s.buildFragment=function(e,t,r){var i,o,u,a,f=e[0];if(t&&t[0]){a=t[0].ownerDocument||t[0]}if(!a.createDocumentFragment){a=n}if(e.length===1&&typeof f==="string"&&f.length<512&&a===n&&f.charAt(0)==="<"&&!tt.test(f)&&(s.support.checkClone||!rt.test(f))&&(s.support.html5Clone||!nt.test(f))){o=true;u=s.fragments[f];if(u&&u!==1){i=u}}if(!i){i=a.createDocumentFragment();s.clean(e,a,i,r)}if(o){s.fragments[f]=u?i:1}return{fragment:i,cacheable:o}};s.fragments={};s.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){s.fn[e]=function(n){var r=[],i=s(n),o=this.length===1&&this[0].parentNode;if(o&&o.nodeType===11&&o.childNodes.length===1&&i.length===1){i[t](this[0]);return this}else{for(var u=0,a=i.length;u<a;u++){var f=(u>0?this.clone(true):this).get();s(i[u])[t](f);r=r.concat(f)}return this.pushStack(r,e,i.selector)}}});s.extend({clone:function(e,t,n){var r,i,o,u=s.support.html5Clone||s.isXMLDoc(e)||!nt.test("<"+e.nodeName+">")?e.cloneNode(true):dt(e);if((!s.support.noCloneEvent||!s.support.noCloneChecked)&&(e.nodeType===1||e.nodeType===11)&&!s.isXMLDoc(e)){lt(e,u);r=ct(e);i=ct(u);for(o=0;r[o];++o){if(i[o]){lt(r[o],i[o])}}}if(t){ft(e,u);if(n){r=ct(e);i=ct(u);for(o=0;r[o];++o){ft(r[o],i[o])}}}r=i=null;return u},clean:function(e,t,r,i){var o,u,a,f=[];t=t||n;if(typeof t.createElement==="undefined"){t=t.ownerDocument||t[0]&&t[0].ownerDocument||n}for(var l=0,c;(c=e[l])!=null;l++){if(typeof c==="number"){c+=""}if(!c){continue}if(typeof c==="string"){if(!Z.test(c)){c=t.createTextNode(c)}else{c=c.replace(Q,"<$1></$2>");var h=(G.exec(c)||["",""])[1].toLowerCase(),p=ot[h]||ot._default,d=p[0],v=t.createElement("div"),m=ut.childNodes,g;if(t===n){ut.appendChild(v)}else{V(t).appendChild(v)}v.innerHTML=p[1]+c+p[2];while(d--){v=v.lastChild}if(!s.support.tbody){var y=Y.test(c),b=h==="table"&&!y?v.firstChild&&v.firstChild.childNodes:p[1]==="<table>"&&!y?v.childNodes:[];for(a=b.length-1;a>=0;--a){if(s.nodeName(b[a],"tbody")&&!b[a].childNodes.length){b[a].parentNode.removeChild(b[a])}}}if(!s.support.leadingWhitespace&&K.test(c)){v.insertBefore(t.createTextNode(K.exec(c)[0]),v.firstChild)}c=v.childNodes;if(v){v.parentNode.removeChild(v);if(m.length>0){g=m[m.length-1];if(g&&g.parentNode){g.parentNode.removeChild(g)}}}}}var w;if(!s.support.appendChecked){if(c[0]&&typeof (w=c.length)==="number"){for(a=0;a<w;a++){pt(c[a])}}else{pt(c)}}if(c.nodeType){f.push(c)}else{f=s.merge(f,c)}}if(r){o=function(e){return!e.type||it.test(e.type)};for(l=0;f[l];l++){u=f[l];if(i&&s.nodeName(u,"script")&&(!u.type||it.test(u.type))){i.push(u.parentNode?u.parentNode.removeChild(u):u)}else{if(u.nodeType===1){var E=s.grep(u.getElementsByTagName("script"),o);f.splice.apply(f,[l+1,0].concat(E))}r.appendChild(u)}}}return f},cleanData:function(e){var t,n,r=s.cache,i=s.event.special,o=s.support.deleteExpando;for(var u=0,a;(a=e[u])!=null;u++){if(a.nodeName&&s.noData[a.nodeName.toLowerCase()]){continue}n=a[s.expando];if(n){t=r[n];if(t&&t.events){for(var f in t.events){if(i[f]){s.event.remove(a,f)}else{s.removeEvent(a,f,t.handle)}}if(t.handle){t.handle.elem=null}}if(o){delete a[s.expando]}else if(a.removeAttribute){a.removeAttribute(s.expando)}delete r[n]}}}});var vt=/alpha\([^)]*\)/i,mt=/opacity=([^)]*)/,gt=/([A-Z]|^ms)/g,yt=/^[\-+]?(?:\d*\.)?\d+$/i,bt=/^-?(?:\d*\.)?\d+(?!px)[^\d\s]+$/i,wt=/^([\-+])=([\-+.\de]+)/,Et=/^margin/,St={position:"absolute",visibility:"hidden",display:"block"},xt=["Top","Right","Bottom","Left"],Tt,Nt,Ct;s.fn.css=function(e,n){return s.access(this,function(e,n,r){return r!==t?s.style(e,n,r):s.css(e,n)},e,n,arguments.length>1)};s.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Tt(e,"opacity");return n===""?"1":n}else{return e.style.opacity}}}},cssNumber:{fillOpacity:true,fontWeight:true,lineHeight:true,opacity:true,orphans:true,widows:true,zIndex:true,zoom:true},cssProps:{"float":s.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(!e||e.nodeType===3||e.nodeType===8||!e.style){return}var o,u,a=s.camelCase(n),f=e.style,l=s.cssHooks[a];n=s.cssProps[a]||a;if(r!==t){u=typeof r;if(u==="string"&&(o=wt.exec(r))){r=+(o[1]+1)*+o[2]+parseFloat(s.css(e,n));u="number"}if(r==null||u==="number"&&isNaN(r)){return}if(u==="number"&&!s.cssNumber[a]){r+="px"}if(!l||!("set"in l)||(r=l.set(e,r))!==t){try{f[n]=r}catch(c){}}}else{if(l&&"get"in l&&(o=l.get(e,false,i))!==t){return o}return f[n]}},css:function(e,n,r){var i,o;n=s.camelCase(n);o=s.cssHooks[n];n=s.cssProps[n]||n;if(n==="cssFloat"){n="float"}if(o&&"get"in o&&(i=o.get(e,true,r))!==t){return i}else if(Tt){return Tt(e,n)}},swap:function(e,t,n){var r={},i,s;for(s in t){r[s]=e.style[s];e.style[s]=t[s]}i=n.call(e);for(s in t){e.style[s]=r[s]}return i}});s.curCSS=s.css;if(n.defaultView&&n.defaultView.getComputedStyle){Nt=function(e,t){var n,r,i,o,u=e.style;t=t.replace(gt,"-$1").toLowerCase();if((r=e.ownerDocument.defaultView)&&(i=r.getComputedStyle(e,null))){n=i.getPropertyValue(t);if(n===""&&!s.contains(e.ownerDocument.documentElement,e)){n=s.style(e,t)}}if(!s.support.pixelMargin&&i&&Et.test(t)&&bt.test(n)){o=u.width;u.width=n;n=i.width;u.width=o}return n}}if(n.documentElement.currentStyle){Ct=function(e,t){var n,r,i,s=e.currentStyle&&e.currentStyle[t],o=e.style;if(s==null&&o&&(i=o[t])){s=i}if(bt.test(s)){n=o.left;r=e.runtimeStyle&&e.runtimeStyle.left;if(r){e.runtimeStyle.left=e.currentStyle.left}o.left=t==="fontSize"?"1em":s;s=o.pixelLeft+"px";o.left=n;if(r){e.runtimeStyle.left=r}}return s===""?"auto":s}}Tt=Nt||Ct;s.each(["height","width"],function(e,t){s.cssHooks[t]={get:function(e,n,r){if(n){if(e.offsetWidth!==0){return kt(e,t,r)}else{return s.swap(e,St,function(){return kt(e,t,r)})}}},set:function(e,t){return yt.test(t)?t+"px":t}}});if(!s.support.opacity){s.cssHooks.opacity={get:function(e,t){return mt.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?parseFloat(RegExp.$1)/100+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=s.isNumeric(t)?"alpha(opacity="+t*100+")":"",o=r&&r.filter||n.filter||"";n.zoom=1;if(t>=1&&s.trim(o.replace(vt,""))===""){n.removeAttribute("filter");if(r&&!r.filter){return}}n.filter=vt.test(o)?o.replace(vt,i):o+" "+i}}}s(function(){if(!s.support.reliableMarginRight){s.cssHooks.marginRight={get:function(e,t){return s.swap(e,{display:"inline-block"},function(){if(t){return Tt(e,"margin-right")}else{return e.style.marginRight}})}}}});if(s.expr&&s.expr.filters){s.expr.filters.hidden=function(e){var t=e.offsetWidth,n=e.offsetHeight;return t===0&&n===0||!s.support.reliableHiddenOffsets&&(e.style&&e.style.display||s.css(e,"display"))==="none"};s.expr.filters.visible=function(e){return!s.expr.filters.hidden(e)}}s.each({margin:"",padding:"",border:"Width"},function(e,t){s.cssHooks[e+t]={expand:function(n){var r,i=typeof n==="string"?n.split(" "):[n],s={};for(r=0;r<4;r++){s[e+xt[r]+t]=i[r]||i[r-2]||i[0]}return s}}});var Lt=/%20/g,At=/\[\]$/,Ot=/\r?\n/g,Mt=/#.*$/,_t=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,Dt=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,Pt=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,Ht=/^(?:GET|HEAD)$/,Bt=/^\/\//,jt=/\?/,Ft=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,It=/^(?:select|textarea)/i,qt=/\s+/,Rt=/([?&])_=[^&]*/,Ut=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,zt=s.fn.load,Wt={},Xt={},Vt,$t,Jt=["*/"]+["*"];try{Vt=i.href}catch(Kt){Vt=n.createElement("a");Vt.href="";Vt=Vt.href}$t=Ut.exec(Vt.toLowerCase())||[];s.fn.extend({load:function(e,n,r){if(typeof e!=="string"&&zt){return zt.apply(this,arguments)}else if(!this.length){return this}var i=e.indexOf(" ");if(i>=0){var o=e.slice(i,e.length);e=e.slice(0,i)}var u="GET";if(n){if(s.isFunction(n)){r=n;n=t}else if(typeof n==="object"){n=s.param(n,s.ajaxSettings.traditional);u="POST"}}var a=this;s.ajax({url:e,type:u,dataType:"html",data:n,complete:function(e,t,n){n=e.responseText;if(e.isResolved()){e.done(function(e){n=e});a.html(o?s("<div>").append(n.replace(Ft,"")).find(o):n)}if(r){a.each(r,[n,t,e])}}});return this},serialize:function(){return s.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?s.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||It.test(this.nodeName)||Dt.test(this.type))}).map(function(e,t){var n=s(this).val();return n==null?null:s.isArray(n)?s.map(n,function(e,n){return{name:t.name,value:e.replace(Ot,"\r\n")}}):{name:t.name,value:n.replace(Ot,"\r\n")}}).get()}});s.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(e,t){s.fn[t]=function(e){return this.on(t,e)}});s.each(["get","post"],function(e,n){s[n]=function(e,r,i,o){if(s.isFunction(r)){o=o||i;i=r;r=t}return s.ajax({type:n,url:e,data:r,success:i,dataType:o})}});s.extend({getScript:function(e,n){return s.get(e,t,n,"script")},getJSON:function(e,t,n){return s.get(e,t,n,"json")},ajaxSetup:function(e,t){if(t){Yt(e,s.ajaxSettings)}else{t=e;e=s.ajaxSettings}Yt(e,t);return e},ajaxSettings:{url:Vt,isLocal:Pt.test($t[1]),global:true,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:true,async:true,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":Jt},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":e.String,"text html":true,"text json":s.parseJSON,"text xml":s.parseXML},flatOptions:{context:true,url:true}},ajaxPrefilter:Qt(Wt),ajaxTransport:Qt(Xt),ajax:function(e,n){function S(e,n,c,h){if(y===2){return}y=2;if(m){clearTimeout(m)}v=t;p=h||"";E.readyState=e>0?4:0;var d,g,w,S=n,x=c?en(r,E,c):t,T,N;if(e>=200&&e<300||e===304){if(r.ifModified){if(T=E.getResponseHeader("Last-Modified")){s.lastModified[l]=T}if(N=E.getResponseHeader("Etag")){s.etag[l]=N}}if(e===304){S="notmodified";d=true}else{try{g=tn(r,x);S="success";d=true}catch(C){S="parsererror";w=C}}}else{w=S;if(!S||e){S="error";if(e<0){e=0}}}E.status=e;E.statusText=""+(n||S);if(d){u.resolveWith(i,[g,S,E])}else{u.rejectWith(i,[E,S,w])}E.statusCode(f);f=t;if(b){o.trigger("ajax"+(d?"Success":"Error"),[E,r,d?g:w])}a.fireWith(i,[E,S]);if(b){o.trigger("ajaxComplete",[E,r]);if(!--s.active){s.event.trigger("ajaxStop")}}}if(typeof e==="object"){n=e;e=t}n=n||{};var r=s.ajaxSetup({},n),i=r.context||r,o=i!==r&&(i.nodeType||i instanceof s)?s(i):s.event,u=s.Deferred(),a=s.Callbacks("once memory"),f=r.statusCode||{},l,c={},h={},p,d,v,m,g,y=0,b,w,E={readyState:0,setRequestHeader:function(e,t){if(!y){var n=e.toLowerCase();e=h[n]=h[n]||e;c[e]=t}return this},getAllResponseHeaders:function(){return y===2?p:null},getResponseHeader:function(e){var n;if(y===2){if(!d){d={};while(n=_t.exec(p)){d[n[1].toLowerCase()]=n[2]}}n=d[e.toLowerCase()]}return n===t?null:n},overrideMimeType:function(e){if(!y){r.mimeType=e}return this},abort:function(e){e=e||"abort";if(v){v.abort(e)}S(0,e);return this}};u.promise(E);E.success=E.done;E.error=E.fail;E.complete=a.add;E.statusCode=function(e){if(e){var t;if(y<2){for(t in e){f[t]=[f[t],e[t]]}}else{t=e[E.status];E.then(t,t)}}return this};r.url=((e||r.url)+"").replace(Mt,"").replace(Bt,$t[1]+"//");r.dataTypes=s.trim(r.dataType||"*").toLowerCase().split(qt);if(r.crossDomain==null){g=Ut.exec(r.url.toLowerCase());r.crossDomain=!!(g&&(g[1]!=$t[1]||g[2]!=$t[2]||(g[3]||(g[1]==="http:"?80:443))!=($t[3]||($t[1]==="http:"?80:443))))}if(r.data&&r.processData&&typeof r.data!=="string"){r.data=s.param(r.data,r.traditional)}Gt(Wt,r,n,E);if(y===2){return false}b=r.global;r.type=r.type.toUpperCase();r.hasContent=!Ht.test(r.type);if(b&&s.active++===0){s.event.trigger("ajaxStart")}if(!r.hasContent){if(r.data){r.url+=(jt.test(r.url)?"&":"?")+r.data;delete r.data}l=r.url;if(r.cache===false){var x=s.now(),T=r.url.replace(Rt,"$1_="+x);r.url=T+(T===r.url?(jt.test(r.url)?"&":"?")+"_="+x:"")}}if(r.data&&r.hasContent&&r.contentType!==false||n.contentType){E.setRequestHeader("Content-Type",r.contentType)}if(r.ifModified){l=l||r.url;if(s.lastModified[l]){E.setRequestHeader("If-Modified-Since",s.lastModified[l])}if(s.etag[l]){E.setRequestHeader("If-None-Match",s.etag[l])}}E.setRequestHeader("Accept",r.dataTypes[0]&&r.accepts[r.dataTypes[0]]?r.accepts[r.dataTypes[0]]+(r.dataTypes[0]!=="*"?", "+Jt+"; q=0.01":""):r.accepts["*"]);for(w in r.headers){E.setRequestHeader(w,r.headers[w])}if(r.beforeSend&&(r.beforeSend.call(i,E,r)===false||y===2)){E.abort();return false}for(w in{success:1,error:1,complete:1}){E[w](r[w])}v=Gt(Xt,r,n,E);if(!v){S(-1,"No Transport")}else{E.readyState=1;if(b){o.trigger("ajaxSend",[E,r])}if(r.async&&r.timeout>0){m=setTimeout(function(){E.abort("timeout")},r.timeout)}try{y=1;v.send(c,S)}catch(N){if(y<2){S(-1,N)}else{throw N}}}return E},param:function(e,n){var r=[],i=function(e,t){t=s.isFunction(t)?t():t;r[r.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(n===t){n=s.ajaxSettings.traditional}if(s.isArray(e)||e.jquery&&!s.isPlainObject(e)){s.each(e,function(){i(this.name,this.value)})}else{for(var o in e){Zt(o,e[o],n,i)}}return r.join("&").replace(Lt,"+")}});s.extend({active:0,lastModified:{},etag:{}});var nn=s.now(),rn=/(\=)\?(&|$)|\?\?/i;s.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return s.expando+"_"+nn++}});s.ajaxPrefilter("json jsonp",function(t,n,r){var i=typeof t.data==="string"&&/^application\/x\-www\-form\-urlencoded/.test(t.contentType);if(t.dataTypes[0]==="jsonp"||t.jsonp!==false&&(rn.test(t.url)||i&&rn.test(t.data))){var o,u=t.jsonpCallback=s.isFunction(t.jsonpCallback)?t.jsonpCallback():t.jsonpCallback,a=e[u],f=t.url,l=t.data,c="$1"+u+"$2";if(t.jsonp!==false){f=f.replace(rn,c);if(t.url===f){if(i){l=l.replace(rn,c)}if(t.data===l){f+=(/\?/.test(f)?"&":"?")+t.jsonp+"="+u}}}t.url=f;t.data=l;e[u]=function(e){o=[e]};r.always(function(){e[u]=a;if(o&&s.isFunction(a)){e[u](o[0])}});t.converters["script json"]=function(){if(!o){s.error(u+" was not called")}return o[0]};t.dataTypes[0]="json";return"script"}});s.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(e){s.globalEval(e);return e}}});s.ajaxPrefilter("script",function(e){if(e.cache===t){e.cache=false}if(e.crossDomain){e.type="GET";e.global=false}});s.ajaxTransport("script",function(e){if(e.crossDomain){var r,i=n.head||n.getElementsByTagName("head")[0]||n.documentElement;return{send:function(s,o){r=n.createElement("script");r.async="async";if(e.scriptCharset){r.charset=e.scriptCharset}r.src=e.url;r.onload=r.onreadystatechange=function(e,n){if(n||!r.readyState||/loaded|complete/.test(r.readyState)){r.onload=r.onreadystatechange=null;if(i&&r.parentNode){i.removeChild(r)}r=t;if(!n){o(200,"success")}}};i.insertBefore(r,i.firstChild)},abort:function(){if(r){r.onload(0,1)}}}}});var sn=e.ActiveXObject?function(){for(var e in un){un[e](0,1)}}:false,on=0,un;s.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&an()||fn()}:an;(function(e){s.extend(s.support,{ajax:!!e,cors:!!e&&"withCredentials"in e})})(s.ajaxSettings.xhr());if(s.support.ajax){s.ajaxTransport(function(n){if(!n.crossDomain||s.support.cors){var r;return{send:function(i,o){var u=n.xhr(),a,f;if(n.username){u.open(n.type,n.url,n.async,n.username,n.password)}else{u.open(n.type,n.url,n.async)}if(n.xhrFields){for(f in n.xhrFields){u[f]=n.xhrFields[f]}}if(n.mimeType&&u.overrideMimeType){u.overrideMimeType(n.mimeType)}if(!n.crossDomain&&!i["X-Requested-With"]){i["X-Requested-With"]="XMLHttpRequest"}try{for(f in i){u.setRequestHeader(f,i[f])}}catch(l){}u.send(n.hasContent&&n.data||null);r=function(e,i){var f,l,c,h,p;try{if(r&&(i||u.readyState===4)){r=t;if(a){u.onreadystatechange=s.noop;if(sn){delete un[a]}}if(i){if(u.readyState!==4){u.abort()}}else{f=u.status;c=u.getAllResponseHeaders();h={};p=u.responseXML;if(p&&p.documentElement){h.xml=p}try{h.text=u.responseText}catch(e){}try{l=u.statusText}catch(d){l=""}if(!f&&n.isLocal&&!n.crossDomain){f=h.text?200:404}else if(f===1223){f=204}}}}catch(v){if(!i){o(-1,v)}}if(h){o(f,l,h,c)}};if(!n.async||u.readyState===4){r()}else{a=++on;if(sn){if(!un){un={};s(e).unload(sn)}un[a]=r}u.onreadystatechange=r}},abort:function(){if(r){r(0,1)}}}}})}var ln={},cn,hn,pn=/^(?:toggle|show|hide)$/,dn=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,vn,mn=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]],gn;s.fn.extend({show:function(e,t,n){var r,i;if(e||e===0){return this.animate(wn("show",3),e,t,n)}else{for(var o=0,u=this.length;o<u;o++){r=this[o];if(r.style){i=r.style.display;if(!s._data(r,"olddisplay")&&i==="none"){i=r.style.display=""}if(i===""&&s.css(r,"display")==="none"||!s.contains(r.ownerDocument.documentElement,r)){s._data(r,"olddisplay",En(r.nodeName))}}}for(o=0;o<u;o++){r=this[o];if(r.style){i=r.style.display;if(i===""||i==="none"){r.style.display=s._data(r,"olddisplay")||""}}}return this}},hide:function(e,t,n){if(e||e===0){return this.animate(wn("hide",3),e,t,n)}else{var r,i,o=0,u=this.length;for(;o<u;o++){r=this[o];if(r.style){i=s.css(r,"display");if(i!=="none"&&!s._data(r,"olddisplay")){s._data(r,"olddisplay",i)}}}for(o=0;o<u;o++){if(this[o].style){this[o].style.display="none"}}return this}},_toggle:s.fn.toggle,toggle:function(e,t,n){var r=typeof e==="boolean";if(s.isFunction(e)&&s.isFunction(t)){this._toggle.apply(this,arguments)}else if(e==null||r){this.each(function(){var t=r?e:s(this).is(":hidden");s(this)[t?"show":"hide"]()})}else{this.animate(wn("toggle",3),e,t,n)}return this},fadeTo:function(e,t,n,r){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){function o(){if(i.queue===false){s._mark(this)}var t=s.extend({},i),n=this.nodeType===1,r=n&&s(this).is(":hidden"),o,u,a,f,l,c,h,p,d,v,m;t.animatedProperties={};for(a in e){o=s.camelCase(a);if(a!==o){e[o]=e[a];delete e[a]}if((l=s.cssHooks[o])&&"expand"in l){c=l.expand(e[o]);delete e[o];for(a in c){if(!(a in e)){e[a]=c[a]}}}}for(o in e){u=e[o];if(s.isArray(u)){t.animatedProperties[o]=u[1];u=e[o]=u[0]}else{t.animatedProperties[o]=t.specialEasing&&t.specialEasing[o]||t.easing||"swing"}if(u==="hide"&&r||u==="show"&&!r){return t.complete.call(this)}if(n&&(o==="height"||o==="width")){t.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY];if(s.css(this,"display")==="inline"&&s.css(this,"float")==="none"){if(!s.support.inlineBlockNeedsLayout||En(this.nodeName)==="inline"){this.style.display="inline-block"}else{this.style.zoom=1}}}}if(t.overflow!=null){this.style.overflow="hidden"}for(a in e){f=new s.fx(this,t,a);u=e[a];if(pn.test(u)){m=s._data(this,"toggle"+a)||(u==="toggle"?r?"show":"hide":0);if(m){s._data(this,"toggle"+a,m==="show"?"hide":"show");f[m]()}else{f[u]()}}else{h=dn.exec(u);p=f.cur();if(h){d=parseFloat(h[2]);v=h[3]||(s.cssNumber[a]?"":"px");if(v!=="px"){s.style(this,a,(d||1)+v);p=(d||1)/f.cur()*p;s.style(this,a,p+v)}if(h[1]){d=(h[1]==="-="?-1:1)*d+p}f.custom(p,d,v)}else{f.custom(p,u,"")}}}return true}var i=s.speed(t,n,r);if(s.isEmptyObject(e)){return this.each(i.complete,[false])}e=s.extend({},e);return i.queue===false?this.each(o):this.queue(i.queue,o)},stop:function(e,n,r){if(typeof e!=="string"){r=n;n=e;e=t}if(n&&e!==false){this.queue(e||"fx",[])}return this.each(function(){function u(e,t,n){var i=t[n];s.removeData(e,n,true);i.stop(r)}var t,n=false,i=s.timers,o=s._data(this);if(!r){s._unmark(true,this)}if(e==null){for(t in o){if(o[t]&&o[t].stop&&t.indexOf(".run")===t.length-4){u(this,o,t)}}}else if(o[t=e+".run"]&&o[t].stop){u(this,o,t)}for(t=i.length;t--;){if(i[t].elem===this&&(e==null||i[t].queue===e)){if(r){i[t](true)}else{i[t].saveState()}n=true;i.splice(t,1)}}if(!(r&&n)){s.dequeue(this,e)}})}});s.each({slideDown:wn("show",1),slideUp:wn("hide",1),slideToggle:wn("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){s.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}});s.extend({speed:function(e,t,n){var r=e&&typeof e==="object"?s.extend({},e):{complete:n||!n&&t||s.isFunction(e)&&e,duration:e,easing:n&&t||t&&!s.isFunction(t)&&t};r.duration=s.fx.off?0:typeof r.duration==="number"?r.duration:r.duration in s.fx.speeds?s.fx.speeds[r.duration]:s.fx.speeds._default;if(r.queue==null||r.queue===true){r.queue="fx"}r.old=r.complete;r.complete=function(e){if(s.isFunction(r.old)){r.old.call(this)}if(r.queue){s.dequeue(this,r.queue)}else if(e!==false){s._unmark(this)}};return r},easing:{linear:function(e){return e},swing:function(e){return-Math.cos(e*Math.PI)/2+.5}},timers:[],fx:function(e,t,n){this.options=t;this.elem=e;this.prop=n;t.orig=t.orig||{}}});s.fx.prototype={update:function(){if(this.options.step){this.options.step.call(this.elem,this.now,this)}(s.fx.step[this.prop]||s.fx.step._default)(this)},cur:function(){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null)){return this.elem[this.prop]}var e,t=s.css(this.elem,this.prop);return isNaN(e=parseFloat(t))?!t||t==="auto"?0:t:e},custom:function(e,n,r){function u(e){return i.step(e)}var i=this,o=s.fx;this.startTime=gn||yn();this.end=n;this.now=this.start=e;this.pos=this.state=0;this.unit=r||this.unit||(s.cssNumber[this.prop]?"":"px");u.queue=this.options.queue;u.elem=this.elem;u.saveState=function(){if(s._data(i.elem,"fxshow"+i.prop)===t){if(i.options.hide){s._data(i.elem,"fxshow"+i.prop,i.start)}else if(i.options.show){s._data(i.elem,"fxshow"+i.prop,i.end)}}};if(u()&&s.timers.push(u)&&!vn){vn=setInterval(o.tick,o.interval)}},show:function(){var e=s._data(this.elem,"fxshow"+this.prop);this.options.orig[this.prop]=e||s.style(this.elem,this.prop);this.options.show=true;if(e!==t){this.custom(this.cur(),e)}else{this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur())}s(this.elem).show()},hide:function(){this.options.orig[this.prop]=s._data(this.elem,"fxshow"+this.prop)||s.style(this.elem,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(e){var t,n,r,i=gn||yn(),o=true,u=this.elem,a=this.options;if(e||i>=a.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();a.animatedProperties[this.prop]=true;for(t in a.animatedProperties){if(a.animatedProperties[t]!==true){o=false}}if(o){if(a.overflow!=null&&!s.support.shrinkWrapBlocks){s.each(["","X","Y"],function(e,t){u.style["overflow"+t]=a.overflow[e]})}if(a.hide){s(u).hide()}if(a.hide||a.show){for(t in a.animatedProperties){s.style(u,t,a.orig[t]);s.removeData(u,"fxshow"+t,true);s.removeData(u,"toggle"+t,true)}}r=a.complete;if(r){a.complete=false;r.call(u)}}return false}else{if(a.duration==Infinity){this.now=i}else{n=i-this.startTime;this.state=n/a.duration;this.pos=s.easing[a.animatedProperties[this.prop]](this.state,n,0,1,a.duration);this.now=this.start+(this.end-this.start)*this.pos}this.update()}return true}};s.extend(s.fx,{tick:function(){var e,t=s.timers,n=0;for(;n<t.length;n++){e=t[n];if(!e()&&t[n]===e){t.splice(n--,1)}}if(!t.length){s.fx.stop()}},interval:13,stop:function(){clearInterval(vn);vn=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(e){s.style(e.elem,"opacity",e.now)},_default:function(e){if(e.elem.style&&e.elem.style[e.prop]!=null){e.elem.style[e.prop]=e.now+e.unit}else{e.elem[e.prop]=e.now}}}});s.each(mn.concat.apply([],mn),function(e,t){if(t.indexOf("margin")){s.fx.step[t]=function(e){s.style(e.elem,t,Math.max(0,e.now)+e.unit)}}});if(s.expr&&s.expr.filters){s.expr.filters.animated=function(e){return s.grep(s.timers,function(t){return e===t.elem}).length}}var Sn,xn=/^t(?:able|d|h)$/i,Tn=/^(?:body|html)$/i;if("getBoundingClientRect"in n.documentElement){Sn=function(e,t,n,r){try{r=e.getBoundingClientRect()}catch(i){}if(!r||!s.contains(n,e)){return r?{top:r.top,left:r.left}:{top:0,left:0}}var o=t.body,u=Nn(t),a=n.clientTop||o.clientTop||0,f=n.clientLeft||o.clientLeft||0,l=u.pageYOffset||s.support.boxModel&&n.scrollTop||o.scrollTop,c=u.pageXOffset||s.support.boxModel&&n.scrollLeft||o.scrollLeft,h=r.top+l-a,p=r.left+c-f;return{top:h,left:p}}}else{Sn=function(e,t,n){var r,i=e.offsetParent,o=e,u=t.body,a=t.defaultView,f=a?a.getComputedStyle(e,null):e.currentStyle,l=e.offsetTop,c=e.offsetLeft;while((e=e.parentNode)&&e!==u&&e!==n){if(s.support.fixedPosition&&f.position==="fixed"){break}r=a?a.getComputedStyle(e,null):e.currentStyle;l-=e.scrollTop;c-=e.scrollLeft;if(e===i){l+=e.offsetTop;c+=e.offsetLeft;if(s.support.doesNotAddBorder&&!(s.support.doesAddBorderForTableAndCells&&xn.test(e.nodeName))){l+=parseFloat(r.borderTopWidth)||0;c+=parseFloat(r.borderLeftWidth)||0}o=i;i=e.offsetParent}if(s.support.subtractsBorderForOverflowNotVisible&&r.overflow!=="visible"){l+=parseFloat(r.borderTopWidth)||0;c+=parseFloat(r.borderLeftWidth)||0}f=r}if(f.position==="relative"||f.position==="static"){l+=u.offsetTop;c+=u.offsetLeft}if(s.support.fixedPosition&&f.position==="fixed"){l+=Math.max(n.scrollTop,u.scrollTop);c+=Math.max(n.scrollLeft,u.scrollLeft)}return{top:l,left:c}}}s.fn.offset=function(e){if(arguments.length){return e===t?this:this.each(function(t){s.offset.setOffset(this,e,t)})}var n=this[0],r=n&&n.ownerDocument;if(!r){return null}if(n===r.body){return s.offset.bodyOffset(n)}return Sn(n,r,r.documentElement)};s.offset={bodyOffset:function(e){var t=e.offsetTop,n=e.offsetLeft;if(s.support.doesNotIncludeMarginInBodyOffset){t+=parseFloat(s.css(e,"marginTop"))||0;n+=parseFloat(s.css(e,"marginLeft"))||0}return{top:t,left:n}},setOffset:function(e,t,n){var r=s.css(e,"position");if(r==="static"){e.style.position="relative"}var i=s(e),o=i.offset(),u=s.css(e,"top"),a=s.css(e,"left"),f=(r==="absolute"||r==="fixed")&&s.inArray("auto",[u,a])>-1,l={},c={},h,p;if(f){c=i.position();h=c.top;p=c.left}else{h=parseFloat(u)||0;p=parseFloat(a)||0}if(s.isFunction(t)){t=t.call(e,n,o)}if(t.top!=null){l.top=t.top-o.top+h}if(t.left!=null){l.left=t.left-o.left+p}if("using"in t){t.using.call(e,l)}else{i.css(l)}}};s.fn.extend({position:function(){if(!this[0]){return null}var e=this[0],t=this.offsetParent(),n=this.offset(),r=Tn.test(t[0].nodeName)?{top:0,left:0}:t.offset();n.top-=parseFloat(s.css(e,"marginTop"))||0;n.left-=parseFloat(s.css(e,"marginLeft"))||0;r.top+=parseFloat(s.css(t[0],"borderTopWidth"))||0;r.left+=parseFloat(s.css(t[0],"borderLeftWidth"))||0;return{top:n.top-r.top,left:n.left-r.left}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||n.body;while(e&&!Tn.test(e.nodeName)&&s.css(e,"position")==="static"){e=e.offsetParent}return e})}});s.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);s.fn[e]=function(i){return s.access(this,function(e,i,o){var u=Nn(e);if(o===t){return u?n in u?u[n]:s.support.boxModel&&u.document.documentElement[i]||u.document.body[i]:e[i]}if(u){u.scrollTo(!r?o:s(u).scrollLeft(),r?o:s(u).scrollTop())}else{e[i]=o}},e,i,arguments.length,null)}});s.each({Height:"height",Width:"width"},function(e,n){var r="client"+e,i="scroll"+e,o="offset"+e;s.fn["inner"+e]=function(){var e=this[0];return e?e.style?parseFloat(s.css(e,n,"padding")):this[n]():null};s.fn["outer"+e]=function(e){var t=this[0];return t?t.style?parseFloat(s.css(t,n,e?"margin":"border")):this[n]():null};s.fn[n]=function(e){return s.access(this,function(e,n,u){var a,f,l,c;if(s.isWindow(e)){a=e.document;f=a.documentElement[r];return s.support.boxModel&&f||a.body&&a.body[r]||f}if(e.nodeType===9){a=e.documentElement;if(a[r]>=a[i]){return a[r]}return Math.max(e.body[i],a[i],e.body[o],a[o])}if(u===t){l=s.css(e,n);c=parseFloat(l);return s.isNumeric(c)?c:l}s(e).css(n,u)},n,e,arguments.length,null)}});e.jQuery=e.$=s;if(typeof define==="function"&&define.amd&&define.amd.jQuery){define("jquery",[],function(){return s})}})(window);(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().addBack().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.10.0",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("<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.fn.addBack||(e.fn.addBack=function(e){return this.add(e==null?this.prevObject:this.prevObject.filter(e))}),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)),e.ui.ie=!!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase()),e.support.selectstart="onselectstart"in document.createElement("div"),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)}},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)}})})(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={},f=t.split(".")[0];t=t.split(".")[1],i=f+"-"+t,r||(r=n,n=e.Widget),e.expr[":"][i.toLowerCase()]=function(t){return!!e.data(t,i)},e[f]=e[f]||{},s=e[f][t],o=e[f][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,r){if(!e.isFunction(r)){a[t]=r;return}a[t]=function(){var e=function(){return n.prototype[t].apply(this,arguments)},i=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=i,s=r.apply(this,arguments),this._super=t,this._superApply=n,s}}()}),o.prototype=e.widget.extend(u,{widgetEventPrefix:s?u.widgetEventPrefix:t},a,{constructor:o,namespace:f,widgetName:t,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.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]?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()})}})})(jQuery);(function(e,t){var n=!1;e(document).mouseup(function(){n=!1}),e.widget("ui.mouse",{version:"1.10.0",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||document.documentMode<9)&&!t.button?this._mouseUp(t):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)},_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(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return!0}})})(jQuery);(function(e,t){function n(e,t,n){return[parseInt(e[0],10)*(p.test(e[0])?t/100:1),parseInt(e[1],10)*(p.test(e[1])?n/100:1)]}function r(t,n){return parseInt(e.css(t,n),10)||0}function i(t){var n=t[0];return n.nodeType===9?{width:t.width(),height:t.height(),offset:{top:0,left:0}}:e.isWindow(n)?{width:t.width(),height:t.height(),offset:{top:t.scrollTop(),left:t.scrollLeft()}}:n.preventDefault?{width:0,height:0,offset:{top:n.pageY,left:n.pageX}}:{width:t.outerWidth(),height:t.outerHeight(),offset:t.offset()}}e.ui=e.ui||{};var s,o=Math.max,u=Math.abs,a=Math.round,f=/left|center|right/,l=/top|center|bottom/,c=/[\+\-]\d+%?/,h=/^\w+/,p=/%$/,d=e.fn.position;e.position={scrollbarWidth:function(){if(s!==t)return s;var n,r,i=e("<div style='display:block;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>"),o=i.children()[0];return e("body").append(i),n=o.offsetWidth,i.css("overflow","scroll"),r=o.offsetWidth,n===r&&(r=i[0].clientWidth),i.remove(),s=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 d.apply(this,arguments);t=e.extend({},t);var s,p,v,m,g,y,b=e(t.of),w=e.position.getWithinInfo(t.within),E=e.position.getScrollInfo(w),S=(t.collision||"flip").split(" "),x={};return y=i(b),b[0].preventDefault&&(t.at="left top"),p=y.width,v=y.height,m=y.offset,g=e.extend({},m),e.each(["my","at"],function(){var e=(t[this]||"").split(" "),n,r;e.length===1&&(e=f.test(e[0])?e.concat(["center"]):l.test(e[0])?["center"].concat(e):["center","center"]),e[0]=f.test(e[0])?e[0]:"center",e[1]=l.test(e[1])?e[1]:"center",n=c.exec(e[0]),r=c.exec(e[1]),x[this]=[n?n[0]:0,r?r[0]:0],t[this]=[h.exec(e[0])[0],h.exec(e[1])[0]]}),S.length===1&&(S[1]=S[0]),t.at[0]==="right"?g.left+=p:t.at[0]==="center"&&(g.left+=p/2),t.at[1]==="bottom"?g.top+=v:t.at[1]==="center"&&(g.top+=v/2),s=n(x.at,p,v),g.left+=s[0],g.top+=s[1],this.each(function(){var i,f,l=e(this),c=l.outerWidth(),h=l.outerHeight(),d=r(this,"marginLeft"),y=r(this,"marginTop"),T=c+d+r(this,"marginRight")+E.width,N=h+y+r(this,"marginBottom")+E.height,C=e.extend({},g),k=n(x.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-=h:t.my[1]==="center"&&(C.top-=h/2),C.left+=k[0],C.top+=k[1],e.support.offsetFractions||(C.left=a(C.left),C.top=a(C.top)),i={marginLeft:d,marginTop:y},e.each(["left","top"],function(n,r){e.ui.position[S[n]]&&e.ui.position[S[n]][r](C,{targetWidth:p,targetHeight:v,elemWidth:c,elemHeight:h,collisionPosition:i,collisionWidth:T,collisionHeight:N,offset:[s[0]+k[0],s[1]+k[1]],my:t.my,at:t.at,within:w,elem:l})}),t.using&&(f=function(e){var n=m.left-C.left,r=n+p-c,i=m.top-C.top,s=i+v-h,a={target:{element:b,left:m.left,top:m.top,width:p,height:v},element:{element:l,left:C.left,top:C.top,width:c,height:h},horizontal:r<0?"left":n>0?"right":"center",vertical:s<0?"top":i>0?"bottom":"middle"};p<c&&u(n+r)<p&&(a.horizontal="center"),v<h&&u(i+s)<v&&(a.vertical="middle"),o(u(n),u(r))>o(u(i),u(s))?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,s=e.left-t.collisionPosition.marginLeft,u=r-s,a=s+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=o(e.left-s,e.left)},top:function(e,t){var n=t.within,r=n.isWindow?n.scrollTop:n.offset.top,i=t.within.height,s=e.top-t.collisionPosition.marginTop,u=r-s,a=s+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=o(e.top-s,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,o=e.left-t.collisionPosition.marginLeft,a=o-s,f=o+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<u(a))e.left+=l+c+h}else if(f>0){d=e.left-t.collisionPosition.marginLeft+l+c+h-s;if(d>0||u(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,o=e.top-t.collisionPosition.marginTop,a=o-s,f=o+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<u(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||u(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)}()})(jQuery);(function(e,t){e.widget("ui.draggable",e.ui.mouse,{version:"1.10.0",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,drag:null,start:null,stop:null},_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).closest(".ui-resizable-handle").length>0?!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,r=this,i=!1,s=!1;e.ui.ddmanager&&!this.options.dropBehaviour&&(s=e.ui.ddmanager.drop(this,t)),this.dropped&&(s=this.dropped,this.dropped=!1),n=this.element[0];while(n&&(n=n.parentNode))n===document&&(i=!0);return!i&&this.options.helper==="original"?!1:(this.options.revert==="invalid"&&!s||this.options.revert==="valid"&&s||this.options.revert===!0||e.isFunction(this.options.revert)&&this.options.revert.call(this.element,s)?e(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){r._trigger("stop",t)!==!1&&r._clear()}):this._trigger("stop",t)!==!1&&this._clear(),!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("*").addBack().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,n,r,i=this.options;i.containment==="parent"&&(i.containment=this.helper[0].parentNode);if(i.containment==="document"||i.containment==="window")this.containment=[i.containment==="document"?0:e(window).scrollLeft()-this.offset.relative.left-this.offset.parent.left,i.containment==="document"?0:e(window).scrollTop()-this.offset.relative.top-this.offset.parent.top,(i.containment==="document"?0:e(window).scrollLeft())+e(i.containment==="document"?document:window).width()-this.helperProportions.width-this.margins.left,(i.containment==="document"?0:e(window).scrollTop())+(e(i.containment==="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top];if(!/^(document|window|parent)$/.test(i.containment)&&i.containment.constructor!==Array){n=e(i.containment),r=n[0];if(!r)return;t=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),(t?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,(t?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 i.containment.constructor===Array&&(this.containment=i.containment)},_convertPositionTo:function(t,n){n||(n=this.position);var r=t==="absolute"?1:-1,i=this.cssPosition!=="absolute"||this.scrollParent[0]!==document&&!!e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,s=/(html|body)/i.test(i[0].tagName);return{top:n.top+this.offset.relative.top*r+this.offset.parent.top*r-(this.cssPosition==="fixed"?-this.scrollParent.scrollTop():s?0:i.scrollTop())*r,left:n.left+this.offset.relative.left*r+this.offset.parent.left*r-(this.cssPosition==="fixed"?-this.scrollParent.scrollLeft():s?0:i.scrollLeft())*r}},_generatePosition:function(t){var n,r,i,s,o=this.options,u=this.cssPosition!=="absolute"||this.scrollParent[0]!==document&&!!e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,a=/(html|body)/i.test(u[0].tagName),f=t.pageX,l=t.pageY;return this.originalPosition&&(this.containment&&(this.relative_container?(r=this.relative_container.offset(),n=[this.containment[0]+r.left,this.containment[1]+r.top,this.containment[2]+r.left,this.containment[3]+r.top]):n=this.containment,t.pageX-this.offset.click.left<n[0]&&(f=n[0]+this.offset.click.left),t.pageY-this.offset.click.top<n[1]&&(l=n[1]+this.offset.click.top),t.pageX-this.offset.click.left>n[2]&&(f=n[2]+this.offset.click.left),t.pageY-this.offset.click.top>n[3]&&(l=n[3]+this.offset.click.top)),o.grid&&(i=o.grid[1]?this.originalPageY+Math.round((l-this.originalPageY)/o.grid[1])*o.grid[1]:this.originalPageY,l=n?i-this.offset.click.top>=n[1]||i-this.offset.click.top>n[3]?i:i-this.offset.click.top>=n[1]?i-o.grid[1]:i+o.grid[1]:i,s=o.grid[0]?this.originalPageX+Math.round((f-this.originalPageX)/o.grid[0])*o.grid[0]:this.originalPageX,f=n?s-this.offset.click.left>=n[0]||s-this.offset.click.left>n[2]?s:s-this.offset.click.left>=n[0]?s-o.grid[0]:s+o.grid[0]:s)),{top:l-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(this.cssPosition==="fixed"?-this.scrollParent.scrollTop():a?0:u.scrollTop()),left:f-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(this.cssPosition==="fixed"?-this.scrollParent.scrollLeft():a?0:u.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(){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("ui-draggable"),i=r.options,s=e.extend({},n,{item:r.element});r.sortables=[],e(i.connectToSortable).each(function(){var n=e.data(this,"ui-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("ui-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("ui-draggable"),i=this;e.each(r.sortables,function(){var s=!1,o=this;this.instance.positionAbs=r.positionAbs,this.instance.helperProportions=r.helperProportions,this.instance.offset.click=r.offset.click,this.instance._intersectsWith(this.instance.containerCache)&&(s=!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!==o&&this.instance._intersectsWith(this.instance.containerCache)&&e.ui.contains(o.instance.element[0],this.instance.element[0])&&(s=!1),s})),s?(this.instance.isOver||(this.instance.isOver=1,this.instance.currentItem=e(i).clone().removeAttr("id").appendTo(this.instance.element).data("ui-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(){var t=e("body"),n=e(this).data("ui-draggable").options;t.css("cursor")&&(n._cursor=t.css("cursor")),t.css("cursor",n.cursor)},stop:function(){var t=e(this).data("ui-draggable").options;t._cursor&&e("body").css("cursor",t._cursor)}}),e.ui.plugin.add("draggable","opacity",{start:function(t,n){var r=e(n.helper),i=e(this).data("ui-draggable").options;r.css("opacity")&&(i._opacity=r.css("opacity")),r.css("opacity",i.opacity)},stop:function(t,n){var r=e(this).data("ui-draggable").options;r._opacity&&e(n.helper).css("opacity",r._opacity)}}),e.ui.plugin.add("draggable","scroll",{start:function(){var t=e(this).data("ui-draggable");t.scrollParent[0]!==document&&t.scrollParent[0].tagName!=="HTML"&&(t.overflowOffset=t.scrollParent.offset())},drag:function(t){var n=e(this).data("ui-draggable"),r=n.options,i=!1;if(n.scrollParent[0]!==document&&n.scrollParent[0].tagName!=="HTML"){if(!r.axis||r.axis!=="x")n.overflowOffset.top+n.scrollParent[0].offsetHeight-t.pageY<r.scrollSensitivity?n.scrollParent[0].scrollTop=i=n.scrollParent[0].scrollTop+r.scrollSpeed:t.pageY-n.overflowOffset.top<r.scrollSensitivity&&(n.scrollParent[0].scrollTop=i=n.scrollParent[0].scrollTop-r.scrollSpeed);if(!r.axis||r.axis!=="y")n.overflowOffset.left+n.scrollParent[0].offsetWidth-t.pageX<r.scrollSensitivity?n.scrollParent[0].scrollLeft=i=n.scrollParent[0].scrollLeft+r.scrollSpeed:t.pageX-n.overflowOffset.left<r.scrollSensitivity&&(n.scrollParent[0].scrollLeft=i=n.scrollParent[0].scrollLeft-r.scrollSpeed)}else{if(!r.axis||r.axis!=="x")t.pageY-e(document).scrollTop()<r.scrollSensitivity?i=e(document).scrollTop(e(document).scrollTop()-r.scrollSpeed):e(window).height()-(t.pageY-e(document).scrollTop())<r.scrollSensitivity&&(i=e(document).scrollTop(e(document).scrollTop()+r.scrollSpeed));if(!r.axis||r.axis!=="y")t.pageX-e(document).scrollLeft()<r.scrollSensitivity?i=e(document).scrollLeft(e(document).scrollLeft()-r.scrollSpeed):e(window).width()-(t.pageX-e(document).scrollLeft())<r.scrollSensitivity&&(i=e(document).scrollLeft(e(document).scrollLeft()+r.scrollSpeed))}i!==!1&&e.ui.ddmanager&&!r.dropBehaviour&&e.ui.ddmanager.prepareOffsets(n,t)}}),e.ui.plugin.add("draggable","snap",{start:function(){var t=e(this).data("ui-draggable"),n=t.options;t.snapElements=[],e(n.snap.constructor!==String?n.snap.items||":data(ui-draggable)":n.snap).each(function(){var n=e(this),r=n.offset();this!==t.element[0]&&t.snapElements.push({item:this,width:n.outerWidth(),height:n.outerHeight(),top:r.top,left:r.left})})},drag:function(t,n){var r,i,s,o,u,a,f,l,c,h,p=e(this).data("ui-draggable"),d=p.options,v=d.snapTolerance,m=n.offset.left,g=m+p.helperProportions.width,y=n.offset.top,b=y+p.helperProportions.height;for(c=p.snapElements.length-1;c>=0;c--){u=p.snapElements[c].left,a=u+p.snapElements[c].width,f=p.snapElements[c].top,l=f+p.snapElements[c].height;if(!(u-v<m&&m<a+v&&f-v<y&&y<l+v||u-v<m&&m<a+v&&f-v<b&&b<l+v||u-v<g&&g<a+v&&f-v<y&&y<l+v||u-v<g&&g<a+v&&f-v<b&&b<l+v)){p.snapElements[c].snapping&&p.options.snap.release&&p.options.snap.release.call(p.element,t,e.extend(p._uiHash(),{snapItem:p.snapElements[c].item})),p.snapElements[c].snapping=!1;continue}d.snapMode!=="inner"&&(r=Math.abs(f-b)<=v,i=Math.abs(l-y)<=v,s=Math.abs(u-g)<=v,o=Math.abs(a-m)<=v,r&&(n.position.top=p._convertPositionTo("relative",{top:f-p.helperProportions.height,left:0}).top-p.margins.top),i&&(n.position.top=p._convertPositionTo("relative",{top:l,left:0}).top-p.margins.top),s&&(n.position.left=p._convertPositionTo("relative",{top:0,left:u-p.helperProportions.width}).left-p.margins.left),o&&(n.position.left=p._convertPositionTo("relative",{top:0,left:a}).left-p.margins.left)),h=r||i||s||o,d.snapMode!=="outer"&&(r=Math.abs(f-y)<=v,i=Math.abs(l-b)<=v,s=Math.abs(u-m)<=v,o=Math.abs(a-g)<=v,r&&(n.position.top=p._convertPositionTo("relative",{top:f,left:0}).top-p.margins.top),i&&(n.position.top=p._convertPositionTo("relative",{top:l-p.helperProportions.height,left:0}).top-p.margins.top),s&&(n.position.left=p._convertPositionTo("relative",{top:0,left:u}).left-p.margins.left),o&&(n.position.left=p._convertPositionTo("relative",{top:0,left:a-p.helperProportions.width}).left-p.margins.left)),!p.snapElements[c].snapping&&(r||i||s||o||h)&&p.options.snap.snap&&p.options.snap.snap.call(p.element,t,e.extend(p._uiHash(),{snapItem:p.snapElements[c].item})),p.snapElements[c].snapping=r||i||s||o||h}}}),e.ui.plugin.add("draggable","stack",{start:function(){var t,n=e(this).data("ui-draggable").options,r=e.makeArray(e(n.stack)).sort(function(t,n){return(parseInt(e(t).css("zIndex"),10)||0)-(parseInt(e(n).css("zIndex"),10)||0)});if(!r.length)return;t=parseInt(r[0].style.zIndex,10)||0,e(r).each(function(e){this.style.zIndex=t+e}),this[0].style.zIndex=t+r.length}}),e.ui.plugin.add("draggable","zIndex",{start:function(t,n){var r=e(n.helper),i=e(this).data("ui-draggable").options;r.css("zIndex")&&(i._zIndex=r.css("zIndex")),r.css("zIndex",i.zIndex)},stop:function(t,n){var r=e(this).data("ui-draggable").options;r._zIndex&&e(n.helper).css("zIndex",r._zIndex)}})})(jQuery);(function(e,t){function n(e,t,n){return e>t&&e<t+n}e.widget("ui.droppable",{version:"1.10.0",widgetEventPrefix:"drop",options:{accept:"*",activeClass:!1,addClasses:!0,greedy:!1,hoverClass:!1,scope:"default",tolerance:"intersect",activate:null,deactivate:null,drop:null,out:null,over:null},_create:function(){var t=this.options,n=t.accept;this.isover=!1,this.isout=!0,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=0,n=e.ui.ddmanager.droppables[this.options.scope];for(;t<n.length;t++)n[t]===this&&n.splice(t,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,i=!1;return!r||(r.currentItem||r.element)[0]===this.element[0]?!1:(this.element.find(":data(ui-droppable)").not(".ui-draggable-dragging").each(function(){var t=e.data(this,"ui-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(e,t,r){if(!t.offset)return!1;var i,s,o=(e.positionAbs||e.position.absolute).left,u=o+e.helperProportions.width,a=(e.positionAbs||e.position.absolute).top,f=a+e.helperProportions.height,l=t.offset.left,c=l+t.proportions.width,h=t.offset.top,p=h+t.proportions.height;switch(r){case"fit":return l<=o&&u<=c&&h<=a&&f<=p;case"intersect":return l<o+e.helperProportions.width/2&&u-e.helperProportions.width/2<c&&h<a+e.helperProportions.height/2&&f-e.helperProportions.height/2<p;case"pointer":return i=(e.positionAbs||e.position.absolute).left+(e.clickOffset||e.offset.click).left,s=(e.positionAbs||e.position.absolute).top+(e.clickOffset||e.offset.click).top,n(s,h,t.proportions.height)&&n(i,l,t.proportions.width);case"touch":return(a>=h&&a<=p||f>=h&&f<=p||a<h&&f>p)&&(o>=l&&o<=c||u>=l&&u<=c||o<l&&u>c);default:return!1}},e.ui.ddmanager={current:null,droppables:{"default":[]},prepareOffsets:function(t,n){var r,i,s=e.ui.ddmanager.droppables[t.options.scope]||[],o=n?n.type:null,u=(t.currentItem||t.element).find(":data(ui-droppable)").addBack();e:for(r=0;r<s.length;r++){if(s[r].options.disabled||t&&!s[r].accept.call(s[r].element[0],t.currentItem||t.element))continue;for(i=0;i<u.length;i++)if(u[i]===s[r].element[0]){s[r].proportions.height=0;continue e}s[r].visible=s[r].element.css("display")!=="none";if(!s[r].visible)continue;o==="mousedown"&&s[r]._activate.call(s[r],n),s[r].offset=s[r].element.offset(),s[r].proportions={width:s[r].element[0].offsetWidth,height:s[r].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=!0,this.isover=!1,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,i,s,o=e.ui.intersect(t,this,this.options.tolerance),u=!o&&this.isover?"isout":o&&!this.isover?"isover":null;if(!u)return;this.options.greedy&&(i=this.options.scope,s=this.element.parents(":data(ui-droppable)").filter(function(){return e.data(this,"ui-droppable").options.scope===i}),s.length&&(r=e.data(s[0],"ui-droppable"),r.greedyChild=u==="isover")),r&&u==="isover"&&(r.isover=!1,r.isout=!0,r._out.call(r,n)),this[u]=!0,this[u==="isout"?"isover":"isout"]=!1,this[u==="isover"?"_over":"_out"].call(this,n),r&&u==="isout"&&(r.isout=!1,r.isover=!0,r._over.call(r,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){function n(e){return parseInt(e,10)||0}function r(e){return!isNaN(parseInt(e,10))}e.widget("ui.resizable",e.ui.mouse,{version:"1.10.0",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:90,resize:null,start:null,stop:null},_create:function(){var t,n,r,i,s,o=this,u=this.options;this.element.addClass("ui-resizable"),e.extend(this,{_aspectRatio:!!u.aspectRatio,aspectRatio:u.aspectRatio,originalElement:this.element,_proportionallyResizeElements:[],_helper:u.helper||u.ghost||u.animate?u.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("ui-resizable",this.element.data("ui-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=u.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"),t=this.handles.split(","),this.handles={};for(n=0;n<t.length;n++)r=e.trim(t[n]),s="ui-resizable-"+r,i=e("<div class='ui-resizable-handle "+s+"'></div>"),i.css({zIndex:u.zIndex}),"se"===r&&i.addClass("ui-icon ui-icon-gripsmall-diagonal-se"),this.handles[r]=".ui-resizable-"+r,this.element.append(i)}this._renderAxis=function(t){var n,r,i,s;t=t||this.element;for(n in this.handles){this.handles[n].constructor===String&&(this.handles[n]=e(this.handles[n],this.element).show()),this.elementIsWrapper&&this.originalElement[0].nodeName.match(/textarea|input|select|button/i)&&(r=e(this.handles[n],this.element),s=/sw|ne|nw|se|n|s/.test(n)?r.outerHeight():r.outerWidth(),i=["padding",/ne|nw|n/.test(n)?"Top":/se|sw|s/.test(n)?"Bottom":/^e$/.test(n)?"Right":"Left"].join(""),t.css(i,s),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(){o.resizing||(this.className&&(i=this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i)),o.axis=i&&i[1]?i[1]:"se")}),u.autoHide&&(this._handles.hide(),e(this.element).addClass("ui-resizable-autohide").mouseenter(function(){if(u.disabled)return;e(this).removeClass("ui-resizable-autohide"),o._handles.show()}).mouseleave(function(){if(u.disabled)return;o.resizing||(e(this).addClass("ui-resizable-autohide"),o._handles.hide())})),this._mouseInit()},_destroy:function(){this._mouseDestroy();var t,n=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()};return this.elementIsWrapper&&(n(this.element),t=this.element,this.originalElement.css({position:t.css("position"),width:t.outerWidth(),height:t.outerHeight(),top:t.css("top"),left:t.css("left")}).insertAfter(t),t.remove()),this.originalElement.css("resize",this.originalResizeStyle),n(this.originalElement),this},_mouseCapture:function(t){var n,r,i=!1;for(n in this.handles){r=e(this.handles[n])[0];if(r===t.target||e.contains(r,t.target))i=!0}return!this.options.disabled&&i},_mouseStart:function(t){var r,i,s,o=this.options,u=this.element.position(),a=this.element;return this.resizing=!0,/absolute/.test(a.css("position"))?a.css({position:"absolute",top:a.css("top"),left:a.css("left")}):a.is(".ui-draggable")&&a.css({position:"absolute",top:u.top,left:u.left}),this._renderProxy(),r=n(this.helper.css("left")),i=n(this.helper.css("top")),o.containment&&(r+=e(o.containment).scrollLeft()||0,i+=e(o.containment).scrollTop()||0),this.offset=this.helper.offset(),this.position={left:r,top:i},this.size=this._helper?{width:a.outerWidth(),height:a.outerHeight()}:{width:a.width(),height:a.height()},this.originalSize=this._helper?{width:a.outerWidth(),height:a.outerHeight()}:{width:a.width(),height:a.height()},this.originalPosition={left:r,top:i},this.sizeDiff={width:a.outerWidth()-a.width(),height:a.outerHeight()-a.height()},this.originalMousePosition={left:t.pageX,top:t.pageY},this.aspectRatio=typeof o.aspectRatio=="number"?o.aspectRatio:this.originalSize.width/this.originalSize.height||1,s=e(".ui-resizable-"+this.axis).css("cursor"),e("body").css("cursor",s==="auto"?this.axis+"-resize":s),a.addClass("ui-resizable-resizing"),this._propagate("start",t),!0},_mouseDrag:function(t){var n,r=this.helper,i={},s=this.originalMousePosition,o=this.axis,u=this.position.top,a=this.position.left,f=this.size.width,l=this.size.height,c=t.pageX-s.left||0,h=t.pageY-s.top||0,p=this._change[o];if(!p)return!1;n=p.apply(this,[t,c,h]),this._updateVirtualBoundaries(t.shiftKey);if(this._aspectRatio||t.shiftKey)n=this._updateRatio(n,t);return n=this._respectSize(n,t),this._updateCache(n),this._propagate("resize",t),this.position.top!==u&&(i.top=this.position.top+"px"),this.position.left!==a&&(i.left=this.position.left+"px"),this.size.width!==f&&(i.width=this.size.width+"px"),this.size.height!==l&&(i.height=this.size.height+"px"),r.css(i),!this._helper&&this._proportionallyResizeElements.length&&this._proportionallyResize(),e.isEmptyObject(i)||this._trigger("resize",t,this.ui()),!1},_mouseStop:function(t){this.resizing=!1;var n,r,i,s,o,u,a,f=this.options,l=this;return this._helper&&(n=this._proportionallyResizeElements,r=n.length&&/textarea/i.test(n[0].nodeName),i=r&&e.ui.hasScroll(n[0],"left")?0:l.sizeDiff.height,s=r?0:l.sizeDiff.width,o={width:l.helper.width()-s,height:l.helper.height()-i},u=parseInt(l.element.css("left"),10)+(l.position.left-l.originalPosition.left)||null,a=parseInt(l.element.css("top"),10)+(l.position.top-l.originalPosition.top)||null,f.animate||this.element.css(e.extend(o,{top:a,left:u})),l.helper.height(l.size.height),l.helper.width(l.size.width),this._helper&&!f.animate&&this._proportionallyResize()),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,n,i,s,o,u=this.options;o={minWidth:r(u.minWidth)?u.minWidth:0,maxWidth:r(u.maxWidth)?u.maxWidth:Infinity,minHeight:r(u.minHeight)?u.minHeight:0,maxHeight:r(u.maxHeight)?u.maxHeight:Infinity};if(this._aspectRatio||e)t=o.minHeight*this.aspectRatio,i=o.minWidth/this.aspectRatio,n=o.maxHeight*this.aspectRatio,s=o.maxWidth/this.aspectRatio,t>o.minWidth&&(o.minWidth=t),i>o.minHeight&&(o.minHeight=i),n<o.maxWidth&&(o.maxWidth=n),s<o.maxHeight&&(o.maxHeight=s);this._vBoundaries=o},_updateCache:function(e){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){var t=this.position,n=this.size,i=this.axis;return r(e.height)?e.width=e.height*this.aspectRatio:r(e.width)&&(e.height=e.width/this.aspectRatio),i==="sw"&&(e.left=t.left+(n.width-e.width),e.top=null),i==="nw"&&(e.top=t.top+(n.height-e.height),e.left=t.left+(n.width-e.width)),e},_respectSize:function(e){var t=this._vBoundaries,n=this.axis,i=r(e.width)&&t.maxWidth&&t.maxWidth<e.width,s=r(e.height)&&t.maxHeight&&t.maxHeight<e.height,o=r(e.width)&&t.minWidth&&t.minWidth>e.width,u=r(e.height)&&t.minHeight&&t.minHeight>e.height,a=this.originalPosition.left+this.originalSize.width,f=this.position.top+this.size.height,l=/sw|nw|w/.test(n),c=/nw|ne|n/.test(n);return o&&(e.width=t.minWidth),u&&(e.height=t.minHeight),i&&(e.width=t.maxWidth),s&&(e.height=t.maxHeight),o&&l&&(e.left=a-t.minWidth),i&&l&&(e.left=a-t.maxWidth),u&&c&&(e.top=f-t.minHeight),s&&c&&(e.top=f-t.maxHeight),!e.width&&!e.height&&!e.left&&e.top?e.top=null:!e.width&&!e.height&&!e.top&&e.left&&(e.left=null),e},_proportionallyResize:function(){if(!this._proportionallyResizeElements.length)return;var e,t,n,r,i,s=this.helper||this.element;for(e=0;e<this._proportionallyResizeElements.length;e++){i=this._proportionallyResizeElements[e];if(!this.borderDif){this.borderDif=[],n=[i.css("borderTopWidth"),i.css("borderRightWidth"),i.css("borderBottomWidth"),i.css("borderLeftWidth")],r=[i.css("paddingTop"),i.css("paddingRight"),i.css("paddingBottom"),i.css("paddingLeft")];for(t=0;t<n.length;t++)this.borderDif[t]=(parseInt(n[t],10)||0)+(parseInt(r[t],10)||0)}i.css({height:s.height()-this.borderDif[0]-this.borderDif[2]||0,width:s.width()-this.borderDif[1]-this.borderDif[3]||0})}},_renderProxy:function(){var t=this.element,n=this.options;this.elementOffset=t.offset(),this._helper?(this.helper=this.helper||e("<div style='overflow:hidden;'></div>"),this.helper.addClass(this._helper).css({width:this.element.outerWidth()-1,height:this.element.outerHeight()-1,position:"absolute",left:this.elementOffset.left+"px",top:this.elementOffset.top+"px",zIndex:++n.zIndex}),this.helper.appendTo("body").disableSelection()):this.helper=this.element},_change:{e:function(e,t){return{width:this.originalSize.width+t}},w:function(e,t){var n=this.originalSize,r=this.originalPosition;return{left:r.left+t,width:n.width-t}},n:function(e,t,n){var r=this.originalSize,i=this.originalPosition;return{top:i.top+n,height:r.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","animate",{stop:function(t){var n=e(this).data("ui-resizable"),r=n.options,i=n._proportionallyResizeElements,s=i.length&&/textarea/i.test(i[0].nodeName),o=s&&e.ui.hasScroll(i[0],"left")?0:n.sizeDiff.height,u=s?0:n.sizeDiff.width,a={width:n.size.width-u,height:n.size.height-o},f=parseInt(n.element.css("left"),10)+(n.position.left-n.originalPosition.left)||null,l=parseInt(n.element.css("top"),10)+(n.position.top-n.originalPosition.top)||null;n.element.animate(e.extend(a,l&&f?{top:l,left:f}:{}),{duration:r.animateDuration,easing:r.animateEasing,step:function(){var r={width:parseInt(n.element.css("width"),10),height:parseInt(n.element.css("height"),10),top:parseInt(n.element.css("top"),10),left:parseInt(n.element.css("left"),10)};i&&i.length&&e(i[0]).css({width:r.width,height:r.height}),n._updateCache(r),n._propagate("resize",t)}})}}),e.ui.plugin.add("resizable","containment",{start:function(){var t,r,i,s,o,u,a,f=e(this).data("ui-resizable"),l=f.options,c=f.element,h=l.containment,p=h instanceof e?h.get(0):/parent/.test(h)?c.parent().get(0):h;if(!p)return;f.containerElement=e(p),/document/.test(h)||h===document?(f.containerOffset={left:0,top:0},f.containerPosition={left:0,top:0},f.parentData={element:e(document),left:0,top:0,width:e(document).width(),height:e(document).height()||document.body.parentNode.scrollHeight}):(t=e(p),r=[],e(["Top","Right","Left","Bottom"]).each(function(e,i){r[e]=n(t.css("padding"+i))}),f.containerOffset=t.offset(),f.containerPosition=t.position(),f.containerSize={height:t.innerHeight()-r[3],width:t.innerWidth()-r[1]},i=f.containerOffset,s=f.containerSize.height,o=f.containerSize.width,u=e.ui.hasScroll(p,"left")?p.scrollWidth:o,a=e.ui.hasScroll(p)?p.scrollHeight:s,f.parentData={element:p,left:i.left,top:i.top,width:u,height:a})},resize:function(t){var n,r,i,s,o=e(this).data("ui-resizable"),u=o.options,a=o.containerOffset,f=o.position,l=o._aspectRatio||t.shiftKey,c={top:0,left:0},h=o.containerElement;h[0]!==document&&/static/.test(h.css("position"))&&(c=a),f.left<(o._helper?a.left:0)&&(o.size.width=o.size.width+(o._helper?o.position.left-a.left:o.position.left-c.left),l&&(o.size.height=o.size.width/o.aspectRatio),o.position.left=u.helper?a.left:0),f.top<(o._helper?a.top:0)&&(o.size.height=o.size.height+(o._helper?o.position.top-a.top:o.position.top),l&&(o.size.width=o.size.height*o.aspectRatio),o.position.top=o._helper?a.top:0),o.offset.left=o.parentData.left+o.position.left,o.offset.top=o.parentData.top+o.position.top,n=Math.abs((o._helper?o.offset.left-c.left:o.offset.left-c.left)+o.sizeDiff.width),r=Math.abs((o._helper?o.offset.top-c.top:o.offset.top-a.top)+o.sizeDiff.height),i=o.containerElement.get(0)===o.element.parent().get(0),s=/relative|absolute/.test(o.containerElement.css("position")),i&&s&&(n-=o.parentData.left),n+o.size.width>=o.parentData.width&&(o.size.width=o.parentData.width-n,l&&(o.size.height=o.size.width/o.aspectRatio)),r+o.size.height>=o.parentData.height&&(o.size.height=o.parentData.height-r,l&&(o.size.width=o.size.height*o.aspectRatio))},stop:function(){var t=e(this).data("ui-resizable"),n=t.options,r=t.containerOffset,i=t.containerPosition,s=t.containerElement,o=e(t.helper),u=o.offset(),a=o.outerWidth()-t.sizeDiff.width,f=o.outerHeight()-t.sizeDiff.height;t._helper&&!n.animate&&/relative/.test(s.css("position"))&&e(this).css({left:u.left-i.left-r.left,width:a,height:f}),t._helper&&!n.animate&&/static/.test(s.css("position"))&&e(this).css({left:u.left-i.left-r.left,width:a,height:f})}}),e.ui.plugin.add("resizable","alsoResize",{start:function(){var t=e(this).data("ui-resizable"),n=t.options,r=function(t){e(t).each(function(){var t=e(this);t.data("ui-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 n.alsoResize=="object"&&!n.alsoResize.parentNode?n.alsoResize.length?(n.alsoResize=n.alsoResize[0],r(n.alsoResize)):e.each(n.alsoResize,function(e){r(e)}):r(n.alsoResize)},resize:function(t,n){var r=e(this).data("ui-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("ui-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(){e(this).removeData("resizable-alsoresize")}}),e.ui.plugin.add("resizable","ghost",{start:function(){var t=e(this).data("ui-resizable"),n=t.options,r=t.size;t.ghost=t.originalElement.clone(),t.ghost.css({opacity:.25,display:"block",position:"relative",height:r.height,width:r.width,margin:0,left:0,top:0}).addClass("ui-resizable-ghost").addClass(typeof n.ghost=="string"?n.ghost:""),t.ghost.appendTo(t.helper)},resize:function(){var t=e(this).data("ui-resizable");t.ghost&&t.ghost.css({position:"relative",height:t.size.height,width:t.size.width})},stop:function(){var t=e(this).data("ui-resizable");t.ghost&&t.helper&&t.helper.get(0).removeChild(t.ghost.get(0))}}),e.ui.plugin.add("resizable","grid",{resize:function(){var t=e(this).data("ui-resizable"),n=t.options,r=t.size,i=t.originalSize,s=t.originalPosition,o=t.axis,u=typeof n.grid=="number"?[n.grid,n.grid]:n.grid,a=u[0]||1,f=u[1]||1,l=Math.round((r.width-i.width)/a)*a,c=Math.round((r.height-i.height)/f)*f,h=i.width+l,p=i.height+c,d=n.maxWidth&&n.maxWidth<h,v=n.maxHeight&&n.maxHeight<p,m=n.minWidth&&n.minWidth>h,g=n.minHeight&&n.minHeight>p;n.grid=u,m&&(h+=a),g&&(p+=f),d&&(h-=a),v&&(p-=f),/^(se|s|e)$/.test(o)?(t.size.width=h,t.size.height=p):/^(ne)$/.test(o)?(t.size.width=h,t.size.height=p,t.position.top=s.top-c):/^(sw)$/.test(o)?(t.size.width=h,t.size.height=p,t.position.left=s.left-l):(t.size.width=h,t.size.height=p,t.position.top=s.top-c,t.position.left=s.left-l)}})})(jQuery);(function(e,t){e.widget("ui.selectable",e.ui.mouse,{version:"1.10.0",options:{appendTo:"body",autoRefresh:!0,distance:0,filter:"*",tolerance:"touch",selected:null,selecting:null,start:null,stop:null,unselected:null,unselecting:null},_create:function(){var t,n=this;this.element.addClass("ui-selectable"),this.dragged=!1,this.refresh=function(){t=e(n.options.filter,n.element[0]),t.addClass("ui-selectee"),t.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=t.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,r=this.options;this.opos=[t.pageX,t.pageY];if(this.options.disabled)return;this.selectees=e(r.filter,this.element[0]),this._trigger("start",t),e(r.appendTo).append(this.helper),this.helper.css({left:t.pageX,top:t.pageY,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().addBack().each(function(){var r,i=e.data(this,"selectable-item");if(i)return r=!t.metaKey&&!t.ctrlKey||!i.$element.hasClass("ui-selected"),i.$element.removeClass(r?"ui-unselecting":"ui-selected").addClass(r?"ui-selecting":"ui-unselecting"),i.unselecting=!r,i.selecting=r,i.selected=r,r?n._trigger("selecting",t,{selecting:i.element}):n._trigger("unselecting",t,{unselecting:i.element}),!1})},_mouseDrag:function(t){this.dragged=!0;if(this.options.disabled)return;var n,r=this,i=this.options,s=this.opos[0],o=this.opos[1],u=t.pageX,a=t.pageY;return s>u&&(n=u,u=s,s=n),o>a&&(n=a,a=o,o=n),this.helper.css({left:s,top:o,width:u-s,height:a-o}),this.selectees.each(function(){var n=e.data(this,"selectable-item"),f=!1;if(!n||n.element===r.element[0])return;i.tolerance==="touch"?f=!(n.left>u||n.right<s||n.top>a||n.bottom<o):i.tolerance==="fit"&&(f=n.left>s&&n.right<u&&n.top>o&&n.bottom<a),f?(n.selected&&(n.$element.removeClass("ui-selected"),n.selected=!1),n.unselecting&&(n.$element.removeClass("ui-unselecting"),n.unselecting=!1),n.selecting||(n.$element.addClass("ui-selecting"),n.selecting=!0,r._trigger("selecting",t,{selecting:n.element}))):(n.selecting&&((t.metaKey||t.ctrlKey)&&n.startselected?(n.$element.removeClass("ui-selecting"),n.selecting=!1,n.$element.addClass("ui-selected"),n.selected=!0):(n.$element.removeClass("ui-selecting"),n.selecting=!1,n.startselected&&(n.$element.addClass("ui-unselecting"),n.unselecting=!0),r._trigger("unselecting",t,{unselecting:n.element}))),n.selected&&!t.metaKey&&!t.ctrlKey&&!n.startselected&&(n.$element.removeClass("ui-selected"),n.selected=!1,n.$element.addClass("ui-unselecting"),n.unselecting=!0,r._trigger("unselecting",t,{unselecting:n.element})))}),!1},_mouseStop:function(t){var n=this;return this.dragged=!1,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){function n(e,t,n){return e>t&&e<t+n}e.widget("ui.sortable",e.ui.mouse,{version:"1.10.0",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,activate:null,beforeStop:null,change:null,deactivate:null,out:null,over:null,receive:null,remove:null,sort:null,start:null,stop:null,update:null},_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=null,i=!1,s=this;if(this.reverting)return!1;if(this.options.disabled||this.options.type==="static")return!1;this._refreshItems(t),e(t.target).parents().each(function(){if(e.data(this,s.widgetName+"-item")===s)return r=e(this),!1}),e.data(t.target,s.widgetName+"-item")===s&&(r=e(t.target));if(!r)return!1;if(this.options.handle&&!n){e(this.options.handle,r).find("*").addBack().each(function(){this===t.target&&(i=!0)});if(!i)return!1}return this.currentItem=r,this._removeCurrentsFromItems(),!0},_mouseStart:function(t,n,r){var i,s=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,s.cursorAt&&this._adjustOffsetFromHelper(s.cursorAt),this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]},this.helper[0]!==this.currentItem[0]&&this.currentItem.hide(),this._createPlaceholder(),s.containment&&this._setContainment(),s.cursor&&(e("body").css("cursor")&&(this._storedCursor=e("body").css("cursor")),e("body").css("cursor",s.cursor)),s.opacity&&(this.helper.css("opacity")&&(this._storedOpacity=this.helper.css("opacity")),this.helper.css("opacity",s.opacity)),s.zIndex&&(this.helper.css("zIndex")&&(this._storedZIndex=this.helper.css("zIndex")),this.helper.css("zIndex",s.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(i=this.containers.length-1;i>=0;i--)this.containers[i]._trigger("activate",t,this._uiHash(this));return e.ui.ddmanager&&(e.ui.ddmanager.current=this),e.ui.ddmanager&&!s.dropBehaviour&&e.ui.ddmanager.prepareOffsets(this,t),this.dragging=!0,this.helper.addClass("ui-sortable-helper"),this._mouseDrag(t),!0},_mouseDrag:function(t){var n,r,i,s,o=this.options,u=!1;this.position=this._generatePosition(t),this.positionAbs=this._convertPositionTo("absolute"),this.lastPositionAbs||(this.lastPositionAbs=this.positionAbs),this.options.scroll&&(this.scrollParent[0]!==document&&this.scrollParent[0].tagName!=="HTML"?(this.overflowOffset.top+this.scrollParent[0].offsetHeight-t.pageY<o.scrollSensitivity?this.scrollParent[0].scrollTop=u=this.scrollParent[0].scrollTop+o.scrollSpeed:t.pageY-this.overflowOffset.top<o.scrollSensitivity&&(this.scrollParent[0].scrollTop=u=this.scrollParent[0].scrollTop-o.scrollSpeed),this.overflowOffset.left+this.scrollParent[0].offsetWidth-t.pageX<o.scrollSensitivity?this.scrollParent[0].scrollLeft=u=this.scrollParent[0].scrollLeft+o.scrollSpeed:t.pageX-this.overflowOffset.left<o.scrollSensitivity&&(this.scrollParent[0].scrollLeft=u=this.scrollParent[0].scrollLeft-o.scrollSpeed)):(t.pageY-e(document).scrollTop()<o.scrollSensitivity?u=e(document).scrollTop(e(document).scrollTop()-o.scrollSpeed):e(window).height()-(t.pageY-e(document).scrollTop())<o.scrollSensitivity&&(u=e(document).scrollTop(e(document).scrollTop()+o.scrollSpeed)),t.pageX-e(document).scrollLeft()<o.scrollSensitivity?u=e(document).scrollLeft(e(document).scrollLeft()-o.scrollSpeed):e(window).width()-(t.pageX-e(document).scrollLeft())<o.scrollSensitivity&&(u=e(document).scrollLeft(e(document).scrollLeft()+o.scrollSpeed))),u!==!1&&e.ui.ddmanager&&!o.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(n=this.items.length-1;n>=0;n--){r=this.items[n],i=r.item[0],s=this._intersectsWithPointer(r);if(!s)continue;if(r.instance!==this.currentContainer)continue;if(i!==this.currentItem[0]&&this.placeholder[s===1?"next":"prev"]()[0]!==i&&!e.contains(this.placeholder[0],i)&&(this.options.type==="semi-dynamic"?!e.contains(this.element[0],i):!0)){this.direction=s===1?"down":"up";if(this.options.tolerance!=="pointer"&&!this._intersectsWithSides(r))break;this._rearrange(t,r),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(e){var t=this.options.axis==="x"||n(this.positionAbs.top+this.offset.click.top,e.top,e.height),r=this.options.axis==="y"||n(this.positionAbs.left+this.offset.click.left,e.left,e.width),i=t&&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(e){var t=n(this.positionAbs.top+this.offset.click.top,e.top+e.height/2,e.height),r=n(this.positionAbs.left+this.offset.click.left,e.left+e.width/2,e.width),i=this._getDragVerticalDirection(),s=this._getDragHorizontalDirection();return this.floating&&s?s==="right"&&r||s==="left"&&!r:i&&(i==="down"&&t||i==="up"&&!t)},_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,s,o=[],u=[],a=this._connectWith();if(a&&t)for(n=a.length-1;n>=0;n--){i=e(a[n]);for(r=i.length-1;r>=0;r--)s=e.data(i[r],this.widgetFullName),s&&s!==this&&!s.options.disabled&&u.push([e.isFunction(s.options.items)?s.options.items.call(s.element):e(s.options.items,s.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),s])}u.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(n=u.length-1;n>=0;n--)u[n][0].each(function(){o.push(this)});return e(o)},_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,r,i,s,o,u,a,f,l=this.items,c=[[e.isFunction(this.options.items)?this.options.items.call(this.element[0],t,{item:this.currentItem}):e(this.options.items,this.element),this]],h=this._connectWith();if(h&&this.ready)for(n=h.length-1;n>=0;n--){i=e(h[n]);for(r=i.length-1;r>=0;r--)s=e.data(i[r],this.widgetFullName),s&&s!==this&&!s.options.disabled&&(c.push([e.isFunction(s.options.items)?s.options.items.call(s.element[0],t,{item:this.currentItem}):e(s.options.items,s.element),s]),this.containers.push(s))}for(n=c.length-1;n>=0;n--){o=c[n][1],u=c[n][0];for(r=0,f=u.length;r<f;r++)a=e(u[r]),a.data(this.widgetName+"-item",o),l.push({item:a,instance:o,width:0,height:0,left:0,top:0})}},refreshPositions:function(t){this.offsetParent&&this.helper&&(this.offset.parent=this._getParentOffset());var n,r,i,s;for(n=this.items.length-1;n>=0;n--){r=this.items[n];if(r.instance!==this.currentContainer&&this.currentContainer&&r.item[0]!==this.currentItem[0])continue;i=this.options.toleranceElement?e(this.options.toleranceElement,r.item):r.item,t||(r.width=i.outerWidth(),r.height=i.outerHeight()),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(n=this.containers.length-1;n>=0;n--)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,r=t.options;if(!r.placeholder||r.placeholder.constructor===String)n=r.placeholder,r.placeholder={element:function(){var r=e(document.createElement(t.currentItem[0].nodeName)).addClass(n||t.currentItem[0].className+" ui-sortable-placeholder").removeClass("ui-sortable-helper")[0];return n||(r.style.visibility="hidden"),r},update:function(e,i){if(n&&!r.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(r.placeholder.element.call(t.element,t.currentItem)),t.currentItem.after(t.placeholder),r.placeholder.update(t,t.placeholder)},_contactContainers:function(t){var n,r,i,s,o,u,a,f,l,c=null,h=null;for(n=this.containers.length-1;n>=0;n--){if(e.contains(this.currentItem[0],this.containers[n].element[0]))continue;if(this._intersectsWith(this.containers[n].containerCache)){if(c&&e.contains(this.containers[n].element[0],c.element[0]))continue;c=this.containers[n],h=n}else this.containers[n].containerCache.over&&(this.containers[n]._trigger("out",t,this._uiHash(this)),this.containers[n].containerCache.over=0)}if(!c)return;if(this.containers.length===1)this.containers[h]._trigger("over",t,this._uiHash(this)),this.containers[h].containerCache.over=1;else{i=1e4,s=null,o=this.containers[h].floating?"left":"top",u=this.containers[h].floating?"width":"height",a=this.positionAbs[o]+this.offset.click[o];for(r=this.items.length-1;r>=0;r--){if(!e.contains(this.containers[h].element[0],this.items[r].item[0]))continue;if(this.items[r].item[0]===this.currentItem[0])continue;f=this.items[r].item.offset()[o],l=!1,Math.abs(f-a)>Math.abs(f+this.items[r][u]-a)&&(l=!0,f+=this.items[r][u]),Math.abs(f-a)<i&&(i=Math.abs(f-a),s=this.items[r],this.direction=l?"up":"down")}if(!s&&!this.options.dropOnEmpty)return;this.currentContainer=this.containers[h],s?this._rearrange(t,s,null,!0):this._rearrange(t,null,this.containers[h].element,!0),this._trigger("change",t,this._uiHash()),this.containers[h]._trigger("change",t,this._uiHash(this)),this.options.placeholder.update(this.currentContainer,this.placeholder),this.containers[h]._trigger("over",t,this._uiHash(this)),this.containers[h].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,n,r,i=this.options;i.containment==="parent"&&(i.containment=this.helper[0].parentNode);if(i.containment==="document"||i.containment==="window")this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,e(i.containment==="document"?document:window).width()-this.helperProportions.width-this.margins.left,(e(i.containment==="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top];/^(document|window|parent)$/.test(i.containment)||(t=e(i.containment)[0],n=e(i.containment).offset(),r=e(t).css("overflow")!=="hidden",this.containment=[n.left+(parseInt(e(t).css("borderLeftWidth"),10)||0)+(parseInt(e(t).css("paddingLeft"),10)||0)-this.margins.left,n.top+(parseInt(e(t).css("borderTopWidth"),10)||0)+(parseInt(e(t).css("paddingTop"),10)||0)-this.margins.top,n.left+(r?Math.max(t.scrollWidth,t.offsetWidth):t.offsetWidth)-(parseInt(e(t).css("borderLeftWidth"),10)||0)-(parseInt(e(t).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,n.top+(r?Math.max(t.scrollHeight,t.offsetHeight):t.offsetHeight)-(parseInt(e(t).css("borderTopWidth"),10)||0)-(parseInt(e(t).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.cssPosition!=="absolute"||this.scrollParent[0]!==document&&!!e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,s=/(html|body)/i.test(i[0].tagName);return{top:n.top+this.offset.relative.top*r+this.offset.parent.top*r-(this.cssPosition==="fixed"?-this.scrollParent.scrollTop():s?0:i.scrollTop())*r,left:n.left+this.offset.relative.left*r+this.offset.parent.left*r-(this.cssPosition==="fixed"?-this.scrollParent.scrollLeft():s?0:i.scrollLeft())*r}},_generatePosition:function(t){var n,r,i=this.options,s=t.pageX,o=t.pageY,u=this.cssPosition!=="absolute"||this.scrollParent[0]!==document&&!!e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,a=/(html|body)/i.test(u[0].tagName);return this.cssPosition==="relative"&&(this.scrollParent[0]===document||this.scrollParent[0]===this.offsetParent[0])&&(this.offset.relative=this._getRelativeOffset()),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)),i.grid&&(n=this.originalPageY+Math.round((o-this.originalPageY)/i.grid[1])*i.grid[1],o=this.containment?n-this.offset.click.top>=this.containment[1]&&n-this.offset.click.top<=this.containment[3]?n:n-this.offset.click.top>=this.containment[1]?n-i.grid[1]:n+i.grid[1]:n,r=this.originalPageX+Math.round((s-this.originalPageX)/i.grid[0])*i.grid[0],s=this.containment?r-this.offset.click.left>=this.containment[0]&&r-this.offset.click.left<=this.containment[2]?r:r-this.offset.click.left>=this.containment[0]?r-i.grid[0]:r+i.grid[0]:r)),{top:o-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(this.cssPosition==="fixed"?-this.scrollParent.scrollTop():a?0:u.scrollTop()),left:s-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(this.cssPosition==="fixed"?-this.scrollParent.scrollLeft():a?0:u.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,i=[];!this._noFinalSort&&this.currentItem.parent().length&&this.placeholder.before(this.currentItem),this._noFinalSort=null;if(this.helper[0]===this.currentItem[0]){for(r in this._storedCSS)if(this._storedCSS[r]==="auto"||this._storedCSS[r]==="static")this._storedCSS[r]="";this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else this.currentItem.show();this.fromOutside&&!n&&i.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&&i.push(function(e){this._trigger("update",e,this._uiHash())}),this!==this.currentContainer&&(n||(i.push(function(e){this._trigger("remove",e,this._uiHash())}),i.push(function(e){return function(t){e._trigger("receive",t,this._uiHash(this))}}.call(this,this.currentContainer)),i.push(function(e){return function(t){e._trigger("update",t,this._uiHash(this))}}.call(this,this.currentContainer))));for(r=this.containers.length-1;r>=0;r--)n||i.push(function(e){return function(t){e._trigger("deactivate",t,this._uiHash(this))}}.call(this,this.containers[r])),this.containers[r].containerCache.over&&(i.push(function(e){return function(t){e._trigger("out",t,this._uiHash(this))}}.call(this,this.containers[r])),this.containers[r].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(r=0;r<i.length;r++)i[r].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(r=0;r<i.length;r++)i[r].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);(function(e,t){var n=0,r={},i={};r.height=r.paddingTop=r.paddingBottom=r.borderTopWidth=r.borderBottomWidth="hide",i.height=i.paddingTop=i.paddingBottom=i.borderTopWidth=i.borderBottomWidth="show",e.widget("ui.accordion",{version:"1.10.0",options:{active:0,animate:{},collapsible:!1,event:"click",header:"> li > :first-child,> :not(li):even",heightStyle:"auto",icons:{activeHeader:"ui-icon-triangle-1-s",header:"ui-icon-triangle-1-e"},activate:null,beforeActivate:null},_create:function(){var t=this.options;this.prevShow=this.prevHide=e(),this.element.addClass("ui-accordion ui-widget ui-helper-reset").attr("role","tablist"),!t.collapsible&&(t.active===!1||t.active==null)&&(t.active=0),this._processPanels(),t.active<0&&(t.active+=this.headers.length),this._refresh()},_getCreateEventData:function(){return{header:this.active,content:this.active.length?this.active.next():e()}},_createIcons:function(){var t=this.options.icons;t&&(e("<span>").addClass("ui-accordion-header-icon ui-icon "+t.header).prependTo(this.headers),this.active.children(".ui-accordion-header-icon").removeClass(t.header).addClass(t.activeHeader),this.headers.addClass("ui-accordion-icons"))},_destroyIcons:function(){this.headers.removeClass("ui-accordion-icons").children(".ui-accordion-header-icon").remove()},_destroy:function(){var e;this.element.removeClass("ui-accordion ui-widget ui-helper-reset").removeAttr("role"),this.headers.removeClass("ui-accordion-header ui-accordion-header-active ui-helper-reset ui-state-default ui-corner-all ui-state-active ui-state-disabled ui-corner-top").removeAttr("role").removeAttr("aria-selected").removeAttr("aria-controls").removeAttr("tabIndex").each(function(){/^ui-accordion/.test(this.id)&&this.removeAttribute("id")}),this._destroyIcons(),e=this.headers.next().css("display","").removeAttr("role").removeAttr("aria-expanded").removeAttr("aria-hidden").removeAttr("aria-labelledby").removeClass("ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content ui-accordion-content-active ui-state-disabled").each(function(){/^ui-accordion/.test(this.id)&&this.removeAttribute("id")}),this.options.heightStyle!=="content"&&e.css("height","")},_setOption:function(e,t){if(e==="active"){this._activate(t);return}e==="event"&&(this.options.event&&this._off(this.headers,this.options.event),this._setupEvents(t)),this._super(e,t),e==="collapsible"&&!t&&this.options.active===!1&&this._activate(0),e==="icons"&&(this._destroyIcons(),t&&this._createIcons()),e==="disabled"&&this.headers.add(this.headers.next()).toggleClass("ui-state-disabled",!!t)},_keydown:function(t){if(t.altKey||t.ctrlKey)return;var n=e.ui.keyCode,r=this.headers.length,i=this.headers.index(t.target),s=!1;switch(t.keyCode){case n.RIGHT:case n.DOWN:s=this.headers[(i+1)%r];break;case n.LEFT:case n.UP:s=this.headers[(i-1+r)%r];break;case n.SPACE:case n.ENTER:this._eventHandler(t);break;case n.HOME:s=this.headers[0];break;case n.END:s=this.headers[r-1]}s&&(e(t.target).attr("tabIndex",-1),e(s).attr("tabIndex",0),s.focus(),t.preventDefault())},_panelKeyDown:function(t){t.keyCode===e.ui.keyCode.UP&&t.ctrlKey&&e(t.currentTarget).prev().focus()},refresh:function(){var t=this.options;this._processPanels();if(t.active===!1&&t.collapsible===!0||!this.headers.length)t.active=!1,this.active=e();t.active===!1?this._activate(0):this.active.length&&!e.contains(this.element[0],this.active[0])?this.headers.length===this.headers.find(".ui-state-disabled").length?(t.active=!1,this.active=e()):this._activate(Math.max(0,t.active-1)):t.active=this.headers.index(this.active),this._destroyIcons(),this._refresh()},_processPanels:function(){this.headers=this.element.find(this.options.header).addClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-all"),this.headers.next().addClass("ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom").filter(":not(.ui-accordion-content-active)").hide()},_refresh:function(){var t,r=this.options,i=r.heightStyle,s=this.element.parent(),o=this.accordionId="ui-accordion-"+(this.element.attr("id")||++n);this.active=this._findActive(r.active).addClass("ui-accordion-header-active ui-state-active").toggleClass("ui-corner-all ui-corner-top"),this.active.next().addClass("ui-accordion-content-active").show(),this.headers.attr("role","tab").each(function(t){var n=e(this),r=n.attr("id"),i=n.next(),s=i.attr("id");r||(r=o+"-header-"+t,n.attr("id",r)),s||(s=o+"-panel-"+t,i.attr("id",s)),n.attr("aria-controls",s),i.attr("aria-labelledby",r)}).next().attr("role","tabpanel"),this.headers.not(this.active).attr({"aria-selected":"false",tabIndex:-1}).next().attr({"aria-expanded":"false","aria-hidden":"true"}).hide(),this.active.length?this.active.attr({"aria-selected":"true",tabIndex:0}).next().attr({"aria-expanded":"true","aria-hidden":"false"}):this.headers.eq(0).attr("tabIndex",0),this._createIcons(),this._setupEvents(r.event),i==="fill"?(t=s.height(),this.element.siblings(":visible").each(function(){var n=e(this),r=n.css("position");if(r==="absolute"||r==="fixed")return;t-=n.outerHeight(!0)}),this.headers.each(function(){t-=e(this).outerHeight(!0)}),this.headers.next().each(function(){e(this).height(Math.max(0,t-e(this).innerHeight()+e(this).height()))}).css("overflow","auto")):i==="auto"&&(t=0,this.headers.next().each(function(){t=Math.max(t,e(this).css("height","").height())}).height(t))},_activate:function(t){var n=this._findActive(t)[0];if(n===this.active[0])return;n=n||this.active[0],this._eventHandler({target:n,currentTarget:n,preventDefault:e.noop})},_findActive:function(t){return typeof t=="number"?this.headers.eq(t):e()},_setupEvents:function(t){var n={keydown:"_keydown"};t&&e.each(t.split(" "),function(e,t){n[t]="_eventHandler"}),this._off(this.headers.add(this.headers.next())),this._on(this.headers,n),this._on(this.headers.next(),{keydown:"_panelKeyDown"}),this._hoverable(this.headers),this._focusable(this.headers)},_eventHandler:function(t){var n=this.options,r=this.active,i=e(t.currentTarget),s=i[0]===r[0],o=s&&n.collapsible,u=o?e():i.next(),a=r.next(),f={oldHeader:r,oldPanel:a,newHeader:o?e():i,newPanel:u};t.preventDefault();if(s&&!n.collapsible||this._trigger("beforeActivate",t,f)===!1)return;n.active=o?!1:this.headers.index(i),this.active=s?e():i,this._toggle(f),r.removeClass("ui-accordion-header-active ui-state-active"),n.icons&&r.children(".ui-accordion-header-icon").removeClass(n.icons.activeHeader).addClass(n.icons.header),s||(i.removeClass("ui-corner-all").addClass("ui-accordion-header-active ui-state-active ui-corner-top"),n.icons&&i.children(".ui-accordion-header-icon").removeClass(n.icons.header).addClass(n.icons.activeHeader),i.next().addClass("ui-accordion-content-active"))},_toggle:function(t){var n=t.newPanel,r=this.prevShow.length?this.prevShow:t.oldPanel;this.prevShow.add(this.prevHide).stop(!0,!0),this.prevShow=n,this.prevHide=r,this.options.animate?this._animate(n,r,t):(r.hide(),n.show(),this._toggleComplete(t)),r.attr({"aria-expanded":"false","aria-hidden":"true"}),r.prev().attr("aria-selected","false"),n.length&&r.length?r.prev().attr("tabIndex",-1):n.length&&this.headers.filter(function(){return e(this).attr("tabIndex")===0}).attr("tabIndex",-1),n.attr({"aria-expanded":"true","aria-hidden":"false"}).prev().attr({"aria-selected":"true",tabIndex:0})},_animate:function(e,t,n){var s,o,u,a=this,f=0,l=e.length&&(!t.length||e.index()<t.index()),c=this.options.animate||{},h=l&&c.down||c,p=function(){a._toggleComplete(n)};typeof h=="number"&&(u=h),typeof h=="string"&&(o=h),o=o||h.easing||c.easing,u=u||h.duration||c.duration;if(!t.length)return e.animate(i,u,o,p);if(!e.length)return t.animate(r,u,o,p);s=e.show().outerHeight(),t.animate(r,{duration:u,easing:o,step:function(e,t){t.now=Math.round(e)}}),e.hide().animate(i,{duration:u,easing:o,complete:p,step:function(e,n){n.now=Math.round(e),n.prop!=="height"?f+=n.now:a.options.heightStyle!=="content"&&(n.now=Math.round(s-t.outerHeight()-f),f=0)}})},_toggleComplete:function(e){var t=e.oldPanel;t.removeClass("ui-accordion-content-active").prev().removeClass("ui-corner-top").addClass("ui-corner-all"),t.length&&(t.parent()[0].className=t.parent()[0].className),this._trigger("activate",null,e)}})})(jQuery);(function(e,t){var n=0;e.widget("ui.autocomplete",{version:"1.10.0",defaultElement:"<input>",options:{appendTo:null,autoFocus:!1,delay:300,minLength:1,position:{my:"left top",at:"left bottom",collision:"none"},source:null,change:null,close:null,focus:null,open:null,response:null,search:null,select:null},pending:0,_create:function(){var t,n,r;this.isMultiLine=this._isMultiLine(),this.valueMethod=this.element[this.element.is("input,textarea")?"val":"text"],this.isNewMenu=!0,this.element.addClass("ui-autocomplete-input").attr("autocomplete","off"),this._on(this.element,{keydown:function(i){if(this.element.prop("readOnly")){t=!0,r=!0,n=!0;return}t=!1,r=!1,n=!1;var s=e.ui.keyCode;switch(i.keyCode){case s.PAGE_UP:t=!0,this._move("previousPage",i);break;case s.PAGE_DOWN:t=!0,this._move("nextPage",i);break;case s.UP:t=!0,this._keyEvent("previous",i);break;case s.DOWN:t=!0,this._keyEvent("next",i);break;case s.ENTER:case s.NUMPAD_ENTER:this.menu.active&&(t=!0,i.preventDefault(),this.menu.select(i));break;case s.TAB:this.menu.active&&this.menu.select(i);break;case s.ESCAPE:this.menu.element.is(":visible")&&(this._value(this.term),this.close(i),i.preventDefault());break;default:n=!0,this._searchTimeout(i)}},keypress:function(r){if(t){t=!1,r.preventDefault();return}if(n)return;var i=e.ui.keyCode;switch(r.keyCode){case i.PAGE_UP:this._move("previousPage",r);break;case i.PAGE_DOWN:this._move("nextPage",r);break;case i.UP:this._keyEvent("previous",r);break;case i.DOWN:this._keyEvent("next",r)}},input:function(e){if(r){r=!1,e.preventDefault();return}this._searchTimeout(e)},focus:function(){this.selectedItem=null,this.previous=this._value()},blur:function(e){if(this.cancelBlur){delete this.cancelBlur;return}clearTimeout(this.searching),this.close(e),this._change(e)}}),this._initSource(),this.menu=e("<ul>").addClass("ui-autocomplete").appendTo(this._appendTo()).menu({input:e(),role:null}).zIndex(this.element.zIndex()+1).hide().data("ui-menu"),this._on(this.menu.element,{mousedown:function(t){t.preventDefault(),this.cancelBlur=!0,this._delay(function(){delete this.cancelBlur});var n=this.menu.element[0];e(t.target).closest(".ui-menu-item").length||this._delay(function(){var t=this;this.document.one("mousedown",function(r){r.target!==t.element[0]&&r.target!==n&&!e.contains(n,r.target)&&t.close()})})},menufocus:function(t,n){if(this.isNewMenu){this.isNewMenu=!1;if(t.originalEvent&&/^mouse/.test(t.originalEvent.type)){this.menu.blur(),this.document.one("mousemove",function(){e(t.target).trigger(t.originalEvent)});return}}var r=n.item.data("ui-autocomplete-item");!1!==this._trigger("focus",t,{item:r})?t.originalEvent&&/^key/.test(t.originalEvent.type)&&this._value(r.value):this.liveRegion.text(r.value)},menuselect:function(e,t){var n=t.item.data("ui-autocomplete-item"),r=this.previous;this.element[0]!==this.document[0].activeElement&&(this.element.focus(),this.previous=r,this._delay(function(){this.previous=r,this.selectedItem=n})),!1!==this._trigger("select",e,{item:n})&&this._value(n.value),this.term=this._value(),this.close(e),this.selectedItem=n}}),this.liveRegion=e("<span>",{role:"status","aria-live":"polite"}).addClass("ui-helper-hidden-accessible").insertAfter(this.element),this._on(this.window,{beforeunload:function(){this.element.removeAttr("autocomplete")}})},_destroy:function(){clearTimeout(this.searching),this.element.removeClass("ui-autocomplete-input").removeAttr("autocomplete"),this.menu.element.remove(),this.liveRegion.remove()},_setOption:function(e,t){this._super(e,t),e==="source"&&this._initSource(),e==="appendTo"&&this.menu.element.appendTo(this._appendTo()),e==="disabled"&&t&&this.xhr&&this.xhr.abort()},_appendTo:function(){var t=this.options.appendTo;return t&&(t=t.jquery||t.nodeType?e(t):this.document.find(t).eq(0)),t||(t=this.element.closest(".ui-front")),t.length||(t=this.document[0].body),t},_isMultiLine:function(){return this.element.is("textarea")?!0:this.element.is("input")?!1:this.element.prop("isContentEditable")},_initSource:function(){var t,n,r=this;e.isArray(this.options.source)?(t=this.options.source,this.source=function(n,r){r(e.ui.autocomplete.filter(t,n.term))}):typeof this.options.source=="string"?(n=this.options.source,this.source=function(t,i){r.xhr&&r.xhr.abort(),r.xhr=e.ajax({url:n,data:t,dataType:"json",success:function(e){i(e)},error:function(){i([])}})}):this.source=this.options.source},_searchTimeout:function(e){clearTimeout(this.searching),this.searching=this._delay(function(){this.term!==this._value()&&(this.selectedItem=null,this.search(null,e))},this.options.delay)},search:function(e,t){e=e!=null?e:this._value(),this.term=this._value();if(e.length<this.options.minLength)return this.close(t);if(this._trigger("search",t)===!1)return;return this._search(e)},_search:function(e){this.pending++,this.element.addClass("ui-autocomplete-loading"),this.cancelSearch=!1,this.source({term:e},this._response())},_response:function(){var e=this,t=++n;return function(r){t===n&&e.__response(r),e.pending--,e.pending||e.element.removeClass("ui-autocomplete-loading")}},__response:function(e){e&&(e=this._normalize(e)),this._trigger("response",null,{content:e}),!this.options.disabled&&e&&e.length&&!this.cancelSearch?(this._suggest(e),this._trigger("open")):this._close()},close:function(e){this.cancelSearch=!0,this._close(e)},_close:function(e){this.menu.element.is(":visible")&&(this.menu.element.hide(),this.menu.blur(),this.isNewMenu=!0,this._trigger("close",e))},_change:function(e){this.previous!==this._value()&&this._trigger("change",e,{item:this.selectedItem})},_normalize:function(t){return t.length&&t[0].label&&t[0].value?t:e.map(t,function(t){return typeof t=="string"?{label:t,value:t}:e.extend({label:t.label||t.value,value:t.value||t.label},t)})},_suggest:function(t){var n=this.menu.element.empty().zIndex(this.element.zIndex()+1);this._renderMenu(n,t),this.menu.refresh(),n.show(),this._resizeMenu(),n.position(e.extend({of:this.element},this.options.position)),this.options.autoFocus&&this.menu.next()},_resizeMenu:function(){var e=this.menu.element;e.outerWidth(Math.max(e.width("").outerWidth()+1,this.element.outerWidth()))},_renderMenu:function(t,n){var r=this;e.each(n,function(e,n){r._renderItemData(t,n)})},_renderItemData:function(e,t){return this._renderItem(e,t).data("ui-autocomplete-item",t)},_renderItem:function(t,n){return e("<li>").append(e("<a>").text(n.label)).appendTo(t)},_move:function(e,t){if(!this.menu.element.is(":visible")){this.search(null,t);return}if(this.menu.isFirstItem()&&/^previous/.test(e)||this.menu.isLastItem()&&/^next/.test(e)){this._value(this.term),this.menu.blur();return}this.menu[e](t)},widget:function(){return this.menu.element},_value:function(){return this.valueMethod.apply(this.element,arguments)},_keyEvent:function(e,t){if(!this.isMultiLine||this.menu.element.is(":visible"))this._move(e,t),t.preventDefault()}}),e.extend(e.ui.autocomplete,{escapeRegex:function(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")},filter:function(t,n){var r=new RegExp(e.ui.autocomplete.escapeRegex(n),"i");return e.grep(t,function(e){return r.test(e.label||e.value||e)})}}),e.widget("ui.autocomplete",e.ui.autocomplete,{options:{messages:{noResults:"No search results.",results:function(e){return e+(e>1?" results are":" result is")+" available, use up and down arrow keys to navigate."}}},__response:function(e){var t;this._superApply(arguments);if(this.options.disabled||this.cancelSearch)return;e&&e.length?t=this.options.messages.results(e.length):t=this.options.messages.noResults,this.liveRegion.text(t)}})})(jQuery);(function(e,t){var n,r,i,s,o="ui-button ui-widget ui-state-default ui-corner-all",u="ui-state-hover ui-state-active ",a="ui-button-icons-only ui-button-icon-only ui-button-text-icons ui-button-text-icon-primary ui-button-text-icon-secondary ui-button-text-only",f=function(){var t=e(this).find(":ui-button");setTimeout(function(){t.button("refresh")},1)},l=function(t){var n=t.name,r=t.form,i=e([]);return n&&(n=n.replace(/'/g,"\\'"),r?i=e(r).find("[name='"+n+"']"):i=e("[name='"+n+"']",t.ownerDocument).filter(function(){return!this.form})),i};e.widget("ui.button",{version:"1.10.0",defaultElement:"<button>",options:{disabled:null,text:!0,label:null,icons:{primary:null,secondary:null}},_create:function(){this.element.closest("form").unbind("reset"+this.eventNamespace).bind("reset"+this.eventNamespace,f),typeof this.options.disabled!="boolean"?this.options.disabled=!!this.element.prop("disabled"):this.element.prop("disabled",this.options.disabled),this._determineButtonType(),this.hasTitle=!!this.buttonElement.attr("title");var t=this,u=this.options,a=this.type==="checkbox"||this.type==="radio",c=a?"":"ui-state-active",h="ui-state-focus";u.label===null&&(u.label=this.type==="input"?this.buttonElement.val():this.buttonElement.html()),this._hoverable(this.buttonElement),this.buttonElement.addClass(o).attr("role","button").bind("mouseenter"+this.eventNamespace,function(){if(u.disabled)return;this===n&&e(this).addClass("ui-state-active")}).bind("mouseleave"+this.eventNamespace,function(){if(u.disabled)return;e(this).removeClass(c)}).bind("click"+this.eventNamespace,function(e){u.disabled&&(e.preventDefault(),e.stopImmediatePropagation())}),this.element.bind("focus"+this.eventNamespace,function(){t.buttonElement.addClass(h)}).bind("blur"+this.eventNamespace,function(){t.buttonElement.removeClass(h)}),a&&(this.element.bind("change"+this.eventNamespace,function(){if(s)return;t.refresh()}),this.buttonElement.bind("mousedown"+this.eventNamespace,function(e){if(u.disabled)return;s=!1,r=e.pageX,i=e.pageY}).bind("mouseup"+this.eventNamespace,function(e){if(u.disabled)return;if(r!==e.pageX||i!==e.pageY)s=!0})),this.type==="checkbox"?this.buttonElement.bind("click"+this.eventNamespace,function(){if(u.disabled||s)return!1}):this.type==="radio"?this.buttonElement.bind("click"+this.eventNamespace,function(){if(u.disabled||s)return!1;e(this).addClass("ui-state-active"),t.buttonElement.attr("aria-pressed","true");var n=t.element[0];l(n).not(n).map(function(){return e(this).button("widget")[0]}).removeClass("ui-state-active").attr("aria-pressed","false")}):(this.buttonElement.bind("mousedown"+this.eventNamespace,function(){if(u.disabled)return!1;e(this).addClass("ui-state-active"),n=this,t.document.one("mouseup",function(){n=null})}).bind("mouseup"+this.eventNamespace,function(){if(u.disabled)return!1;e(this).removeClass("ui-state-active")}).bind("keydown"+this.eventNamespace,function(t){if(u.disabled)return!1;(t.keyCode===e.ui.keyCode.SPACE||t.keyCode===e.ui.keyCode.ENTER)&&e(this).addClass("ui-state-active")}).bind("keyup"+this.eventNamespace+" blur"+this.eventNamespace,function(){e(this).removeClass("ui-state-active")}),this.buttonElement.is("a")&&this.buttonElement.keyup(function(t){t.keyCode===e.ui.keyCode.SPACE&&e(this).click()})),this._setOption("disabled",u.disabled),this._resetButton()},_determineButtonType:function(){var e,t,n;this.element.is("[type=checkbox]")?this.type="checkbox":this.element.is("[type=radio]")?this.type="radio":this.element.is("input")?this.type="input":this.type="button",this.type==="checkbox"||this.type==="radio"?(e=this.element.parents().last(),t="label[for='"+this.element.attr("id")+"']",this.buttonElement=e.find(t),this.buttonElement.length||(e=e.length?e.siblings():this.element.siblings(),this.buttonElement=e.filter(t),this.buttonElement.length||(this.buttonElement=e.find(t))),this.element.addClass("ui-helper-hidden-accessible"),n=this.element.is(":checked"),n&&this.buttonElement.addClass("ui-state-active"),this.buttonElement.prop("aria-pressed",n)):this.buttonElement=this.element},widget:function(){return this.buttonElement},_destroy:function(){this.element.removeClass("ui-helper-hidden-accessible"),this.buttonElement.removeClass(o+" "+u+" "+a).removeAttr("role").removeAttr("aria-pressed").html(this.buttonElement.find(".ui-button-text").html()),this.hasTitle||this.buttonElement.removeAttr("title")},_setOption:function(e,t){this._super(e,t);if(e==="disabled"){t?this.element.prop("disabled",!0):this.element.prop("disabled",!1);return}this._resetButton()},refresh:function(){var t=this.element.is("input, button")?this.element.is(":disabled"):this.element.hasClass("ui-button-disabled");t!==this.options.disabled&&this._setOption("disabled",t),this.type==="radio"?l(this.element[0]).each(function(){e(this).is(":checked")?e(this).button("widget").addClass("ui-state-active").attr("aria-pressed","true"):e(this).button("widget").removeClass("ui-state-active").attr("aria-pressed","false")}):this.type==="checkbox"&&(this.element.is(":checked")?this.buttonElement.addClass("ui-state-active").attr("aria-pressed","true"):this.buttonElement.removeClass("ui-state-active").attr("aria-pressed","false"))},_resetButton:function(){if(this.type==="input"){this.options.label&&this.element.val(this.options.label);return}var t=this.buttonElement.removeClass(a),n=e("<span></span>",this.document[0]).addClass("ui-button-text").html(this.options.label).appendTo(t.empty()).text(),r=this.options.icons,i=r.primary&&r.secondary,s=[];r.primary||r.secondary?(this.options.text&&s.push("ui-button-text-icon"+(i?"s":r.primary?"-primary":"-secondary")),r.primary&&t.prepend("<span class='ui-button-icon-primary ui-icon "+r.primary+"'></span>"),r.secondary&&t.append("<span class='ui-button-icon-secondary ui-icon "+r.secondary+"'></span>"),this.options.text||(s.push(i?"ui-button-icons-only":"ui-button-icon-only"),this.hasTitle||t.attr("title",e.trim(n)))):s.push("ui-button-text-only"),t.addClass(s.join(" "))}}),e.widget("ui.buttonset",{version:"1.10.0",options:{items:"button, input[type=button], input[type=submit], input[type=reset], input[type=checkbox], input[type=radio], a, :data(ui-button)"},_create:function(){this.element.addClass("ui-buttonset")},_init:function(){this.refresh()},_setOption:function(e,t){e==="disabled"&&this.buttons.button("option",e,t),this._super(e,t)},refresh:function(){var t=this.element.css("direction")==="rtl";this.buttons=this.element.find(this.options.items).filter(":ui-button").button("refresh").end().not(":ui-button").button().end().map(function(){return e(this).button("widget")[0]}).removeClass("ui-corner-all ui-corner-left ui-corner-right").filter(":first").addClass(t?"ui-corner-right":"ui-corner-left").end().filter(":last").addClass(t?"ui-corner-left":"ui-corner-right").end().end()},_destroy:function(){this.element.removeClass("ui-buttonset"),this.buttons.map(function(){return e(this).button("widget")[0]}).removeClass("ui-corner-left ui-corner-right").end().button("destroy")}})})(jQuery);(function(e,t){function n(){this._curInst=null,this._keyEvent=!1,this._disabledInputs=[],this._datepickerShowing=!1,this._inDialog=!1,this._mainDivId="ui-datepicker-div",this._inlineClass="ui-datepicker-inline",this._appendClass="ui-datepicker-append",this._triggerClass="ui-datepicker-trigger",this._dialogClass="ui-datepicker-dialog",this._disableClass="ui-datepicker-disabled",this._unselectableClass="ui-datepicker-unselectable",this._currentClass="ui-datepicker-current-day",this._dayOverClass="ui-datepicker-days-cell-over",this.regional=[],this.regional[""]={closeText:"Done",prevText:"Prev",nextText:"Next",currentText:"Today",monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["Su","Mo","Tu","We","Th","Fr","Sa"],weekHeader:"Wk",dateFormat:"mm/dd/yy",firstDay:0,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},this._defaults={showOn:"focus",showAnim:"fadeIn",showOptions:{},defaultDate:null,appendText:"",buttonText:"...",buttonImage:"",buttonImageOnly:!1,hideIfNoPrevNext:!1,navigationAsDateFormat:!1,gotoCurrent:!1,changeMonth:!1,changeYear:!1,yearRange:"c-10:c+10",showOtherMonths:!1,selectOtherMonths:!1,showWeek:!1,calculateWeek:this.iso8601Week,shortYearCutoff:"+10",minDate:null,maxDate:null,duration:"fast",beforeShowDay:null,beforeShow:null,onSelect:null,onChangeMonthYear:null,onClose:null,numberOfMonths:1,showCurrentAtPos:0,stepMonths:1,stepBigMonths:12,altField:"",altFormat:"",constrainInput:!0,showButtonPanel:!1,autoSize:!1,disabled:!1},e.extend(this._defaults,this.regional[""]),this.dpDiv=r(e("<div id='"+this._mainDivId+"' class='ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>"))}function r(t){var n="button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";return t.delegate(n,"mouseout",function(){e(this).removeClass("ui-state-hover"),this.className.indexOf("ui-datepicker-prev")!==-1&&e(this).removeClass("ui-datepicker-prev-hover"),this.className.indexOf("ui-datepicker-next")!==-1&&e(this).removeClass("ui-datepicker-next-hover")}).delegate(n,"mouseover",function(){e.datepicker._isDisabledDatepicker(u.inline?t.parent()[0]:u.input[0])||(e(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover"),e(this).addClass("ui-state-hover"),this.className.indexOf("ui-datepicker-prev")!==-1&&e(this).addClass("ui-datepicker-prev-hover"),this.className.indexOf("ui-datepicker-next")!==-1&&e(this).addClass("ui-datepicker-next-hover"))})}function i(t,n){e.extend(t,n);for(var r in n)n[r]==null&&(t[r]=n[r]);return t}e.extend(e.ui,{datepicker:{version:"1.10.0"}});var s="datepicker",o=(new Date).getTime(),u;e.extend(n.prototype,{markerClassName:"hasDatepicker",maxRows:4,_widgetDatepicker:function(){return this.dpDiv},setDefaults:function(e){return i(this._defaults,e||{}),this},_attachDatepicker:function(t,n){var r,i,s;r=t.nodeName.toLowerCase(),i=r==="div"||r==="span",t.id||(this.uuid+=1,t.id="dp"+this.uuid),s=this._newInst(e(t),i),s.settings=e.extend({},n||{}),r==="input"?this._connectDatepicker(t,s):i&&this._inlineDatepicker(t,s)},_newInst:function(t,n){var i=t[0].id.replace(/([^A-Za-z0-9_\-])/g,"\\\\$1");return{id:i,input:t,selectedDay:0,selectedMonth:0,selectedYear:0,drawMonth:0,drawYear:0,inline:n,dpDiv:n?r(e("<div class='"+this._inlineClass+" ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>")):this.dpDiv}},_connectDatepicker:function(t,n){var r=e(t);n.append=e([]),n.trigger=e([]);if(r.hasClass(this.markerClassName))return;this._attachments(r,n),r.addClass(this.markerClassName).keydown(this._doKeyDown).keypress(this._doKeyPress).keyup(this._doKeyUp),this._autoSize(n),e.data(t,s,n),n.settings.disabled&&this._disableDatepicker(t)},_attachments:function(t,n){var r,i,s,o=this._get(n,"appendText"),u=this._get(n,"isRTL");n.append&&n.append.remove(),o&&(n.append=e("<span class='"+this._appendClass+"'>"+o+"</span>"),t[u?"before":"after"](n.append)),t.unbind("focus",this._showDatepicker),n.trigger&&n.trigger.remove(),r=this._get(n,"showOn"),(r==="focus"||r==="both")&&t.focus(this._showDatepicker);if(r==="button"||r==="both")i=this._get(n,"buttonText"),s=this._get(n,"buttonImage"),n.trigger=e(this._get(n,"buttonImageOnly")?e("<img/>").addClass(this._triggerClass).attr({src:s,alt:i,title:i}):e("<button type='button'></button>").addClass(this._triggerClass).html(s?e("<img/>").attr({src:s,alt:i,title:i}):i)),t[u?"before":"after"](n.trigger),n.trigger.click(function(){return e.datepicker._datepickerShowing&&e.datepicker._lastInput===t[0]?e.datepicker._hideDatepicker():e.datepicker._datepickerShowing&&e.datepicker._lastInput!==t[0]?(e.datepicker._hideDatepicker(),e.datepicker._showDatepicker(t[0])):e.datepicker._showDatepicker(t[0]),!1})},_autoSize:function(e){if(this._get(e,"autoSize")&&!e.inline){var t,n,r,i,s=new Date(2009,11,20),o=this._get(e,"dateFormat");o.match(/[DM]/)&&(t=function(e){n=0,r=0;for(i=0;i<e.length;i++)e[i].length>n&&(n=e[i].length,r=i);return r},s.setMonth(t(this._get(e,o.match(/MM/)?"monthNames":"monthNamesShort"))),s.setDate(t(this._get(e,o.match(/DD/)?"dayNames":"dayNamesShort"))+20-s.getDay())),e.input.attr("size",this._formatDate(e,s).length)}},_inlineDatepicker:function(t,n){var r=e(t);if(r.hasClass(this.markerClassName))return;r.addClass(this.markerClassName).append(n.dpDiv),e.data(t,s,n),this._setDate(n,this._getDefaultDate(n),!0),this._updateDatepicker(n),this._updateAlternate(n),n.settings.disabled&&this._disableDatepicker(t),n.dpDiv.css("display","block")},_dialogDatepicker:function(t,n,r,o,u){var a,f,l,c,h,p=this._dialogInst;return p||(this.uuid+=1,a="dp"+this.uuid,this._dialogInput=e("<input type='text' id='"+a+"' style='position: absolute; top: -100px; width: 0px;'/>"),this._dialogInput.keydown(this._doKeyDown),e("body").append(this._dialogInput),p=this._dialogInst=this._newInst(this._dialogInput,!1),p.settings={},e.data(this._dialogInput[0],s,p)),i(p.settings,o||{}),n=n&&n.constructor===Date?this._formatDate(p,n):n,this._dialogInput.val(n),this._pos=u?u.length?u:[u.pageX,u.pageY]:null,this._pos||(f=document.documentElement.clientWidth,l=document.documentElement.clientHeight,c=document.documentElement.scrollLeft||document.body.scrollLeft,h=document.documentElement.scrollTop||document.body.scrollTop,this._pos=[f/2-100+c,l/2-150+h]),this._dialogInput.css("left",this._pos[0]+20+"px").css("top",this._pos[1]+"px"),p.settings.onSelect=r,this._inDialog=!0,this.dpDiv.addClass(this._dialogClass),this._showDatepicker(this._dialogInput[0]),e.blockUI&&e.blockUI(this.dpDiv),e.data(this._dialogInput[0],s,p),this},_destroyDatepicker:function(t){var n,r=e(t),i=e.data(t,s);if(!r.hasClass(this.markerClassName))return;n=t.nodeName.toLowerCase(),e.removeData(t,s),n==="input"?(i.append.remove(),i.trigger.remove(),r.removeClass(this.markerClassName).unbind("focus",this._showDatepicker).unbind("keydown",this._doKeyDown).unbind("keypress",this._doKeyPress).unbind("keyup",this._doKeyUp)):(n==="div"||n==="span")&&r.removeClass(this.markerClassName).empty()},_enableDatepicker:function(t){var n,r,i=e(t),o=e.data(t,s);if(!i.hasClass(this.markerClassName))return;n=t.nodeName.toLowerCase();if(n==="input")t.disabled=!1,o.trigger.filter("button").each(function(){this.disabled=!1}).end().filter("img").css({opacity:"1.0",cursor:""});else if(n==="div"||n==="span")r=i.children("."+this._inlineClass),r.children().removeClass("ui-state-disabled"),r.find("select.ui-datepicker-month, select.ui-datepicker-year").prop("disabled",!1);this._disabledInputs=e.map(this._disabledInputs,function(e){return e===t?null:e})},_disableDatepicker:function(t){var n,r,i=e(t),o=e.data(t,s);if(!i.hasClass(this.markerClassName))return;n=t.nodeName.toLowerCase();if(n==="input")t.disabled=!0,o.trigger.filter("button").each(function(){this.disabled=!0}).end().filter("img").css({opacity:"0.5",cursor:"default"});else if(n==="div"||n==="span")r=i.children("."+this._inlineClass),r.children().addClass("ui-state-disabled"),r.find("select.ui-datepicker-month, select.ui-datepicker-year").prop("disabled",!0);this._disabledInputs=e.map(this._disabledInputs,function(e){return e===t?null:e}),this._disabledInputs[this._disabledInputs.length]=t},_isDisabledDatepicker:function(e){if(!e)return!1;for(var t=0;t<this._disabledInputs.length;t++)if(this._disabledInputs[t]===e)return!0;return!1},_getInst:function(t){try{return e.data(t,s)}catch(n){throw"Missing instance data for this datepicker"}},_optionDatepicker:function(n,r,s){var o,u,a,f,l=this._getInst(n);if(arguments.length===2&&typeof r=="string")return r==="defaults"?e.extend({},e.datepicker._defaults):l?r==="all"?e.extend({},l.settings):this._get(l,r):null;o=r||{},typeof r=="string"&&(o={},o[r]=s),l&&(this._curInst===l&&this._hideDatepicker(),u=this._getDateDatepicker(n,!0),a=this._getMinMaxDate(l,"min"),f=this._getMinMaxDate(l,"max"),i(l.settings,o),a!==null&&o.dateFormat!==t&&o.minDate===t&&(l.settings.minDate=this._formatDate(l,a)),f!==null&&o.dateFormat!==t&&o.maxDate===t&&(l.settings.maxDate=this._formatDate(l,f)),"disabled"in o&&(o.disabled?this._disableDatepicker(n):this._enableDatepicker(n)),this._attachments(e(n),l),this._autoSize(l),this._setDate(l,u),this._updateAlternate(l),this._updateDatepicker(l))},_changeDatepicker:function(e,t,n){this._optionDatepicker(e,t,n)},_refreshDatepicker:function(e){var t=this._getInst(e);t&&this._updateDatepicker(t)},_setDateDatepicker:function(e,t){var n=this._getInst(e);n&&(this._setDate(n,t),this._updateDatepicker(n),this._updateAlternate(n))},_getDateDatepicker:function(e,t){var n=this._getInst(e);return n&&!n.inline&&this._setDateFromField(n,t),n?this._getDate(n):null},_doKeyDown:function(t){var n,r,i,s=e.datepicker._getInst(t.target),o=!0,u=s.dpDiv.is(".ui-datepicker-rtl");s._keyEvent=!0;if(e.datepicker._datepickerShowing)switch(t.keyCode){case 9:e.datepicker._hideDatepicker(),o=!1;break;case 13:return i=e("td."+e.datepicker._dayOverClass+":not(."+e.datepicker._currentClass+")",s.dpDiv),i[0]&&e.datepicker._selectDay(t.target,s.selectedMonth,s.selectedYear,i[0]),n=e.datepicker._get(s,"onSelect"),n?(r=e.datepicker._formatDate(s),n.apply(s.input?s.input[0]:null,[r,s])):e.datepicker._hideDatepicker(),!1;case 27:e.datepicker._hideDatepicker();break;case 33:e.datepicker._adjustDate(t.target,t.ctrlKey?-e.datepicker._get(s,"stepBigMonths"):-e.datepicker._get(s,"stepMonths"),"M");break;case 34:e.datepicker._adjustDate(t.target,t.ctrlKey?+e.datepicker._get(s,"stepBigMonths"):+e.datepicker._get(s,"stepMonths"),"M");break;case 35:(t.ctrlKey||t.metaKey)&&e.datepicker._clearDate(t.target),o=t.ctrlKey||t.metaKey;break;case 36:(t.ctrlKey||t.metaKey)&&e.datepicker._gotoToday(t.target),o=t.ctrlKey||t.metaKey;break;case 37:(t.ctrlKey||t.metaKey)&&e.datepicker._adjustDate(t.target,u?1:-1,"D"),o=t.ctrlKey||t.metaKey,t.originalEvent.altKey&&e.datepicker._adjustDate(t.target,t.ctrlKey?-e.datepicker._get(s,"stepBigMonths"):-e.datepicker._get(s,"stepMonths"),"M");break;case 38:(t.ctrlKey||t.metaKey)&&e.datepicker._adjustDate(t.target,-7,"D"),o=t.ctrlKey||t.metaKey;break;case 39:(t.ctrlKey||t.metaKey)&&e.datepicker._adjustDate(t.target,u?-1:1,"D"),o=t.ctrlKey||t.metaKey,t.originalEvent.altKey&&e.datepicker._adjustDate(t.target,t.ctrlKey?+e.datepicker._get(s,"stepBigMonths"):+e.datepicker._get(s,"stepMonths"),"M");break;case 40:(t.ctrlKey||t.metaKey)&&e.datepicker._adjustDate(t.target,7,"D"),o=t.ctrlKey||t.metaKey;break;default:o=!1}else t.keyCode===36&&t.ctrlKey?e.datepicker._showDatepicker(this):o=!1;o&&(t.preventDefault(),t.stopPropagation())},_doKeyPress:function(t){var n,r,i=e.datepicker._getInst(t.target);if(e.datepicker._get(i,"constrainInput"))return n=e.datepicker._possibleChars(e.datepicker._get(i,"dateFormat")),r=String.fromCharCode(t.charCode==null?t.keyCode:t.charCode),t.ctrlKey||t.metaKey||r<" "||!n||n.indexOf(r)>-1},_doKeyUp:function(t){var n,r=e.datepicker._getInst(t.target);if(r.input.val()!==r.lastVal)try{n=e.datepicker.parseDate(e.datepicker._get(r,"dateFormat"),r.input?r.input.val():null,e.datepicker._getFormatConfig(r)),n&&(e.datepicker._setDateFromField(r),e.datepicker._updateAlternate(r),e.datepicker._updateDatepicker(r))}catch(i){}return!0},_showDatepicker:function(t){t=t.target||t,t.nodeName.toLowerCase()!=="input"&&(t=e("input",t.parentNode)[0]);if(e.datepicker._isDisabledDatepicker(t)||e.datepicker._lastInput===t)return;var n,r,s,o,u,a,f;n=e.datepicker._getInst(t),e.datepicker._curInst&&e.datepicker._curInst!==n&&(e.datepicker._curInst.dpDiv.stop(!0,!0),n&&e.datepicker._datepickerShowing&&e.datepicker._hideDatepicker(e.datepicker._curInst.input[0])),r=e.datepicker._get(n,"beforeShow"),s=r?r.apply(t,[t,n]):{};if(s===!1)return;i(n.settings,s),n.lastVal=null,e.datepicker._lastInput=t,e.datepicker._setDateFromField(n),e.datepicker._inDialog&&(t.value=""),e.datepicker._pos||(e.datepicker._pos=e.datepicker._findPos(t),e.datepicker._pos[1]+=t.offsetHeight),o=!1,e(t).parents().each(function(){return o|=e(this).css("position")==="fixed",!o}),u={left:e.datepicker._pos[0],top:e.datepicker._pos[1]},e.datepicker._pos=null,n.dpDiv.empty(),n.dpDiv.css({position:"absolute",display:"block",top:"-1000px"}),e.datepicker._updateDatepicker(n),u=e.datepicker._checkOffset(n,u,o),n.dpDiv.css({position:e.datepicker._inDialog&&e.blockUI?"static":o?"fixed":"absolute",display:"none",left:u.left+"px",top:u.top+"px"}),n.inline||(a=e.datepicker._get(n,"showAnim"),f=e.datepicker._get(n,"duration"),n.dpDiv.zIndex(e(t).zIndex()+1),e.datepicker._datepickerShowing=!0,e.effects&&e.effects.effect[a]?n.dpDiv.show(a,e.datepicker._get(n,"showOptions"),f):n.dpDiv[a||"show"](a?f:null),n.input.is(":visible")&&!n.input.is(":disabled")&&n.input.focus(),e.datepicker._curInst=n)},_updateDatepicker:function(t){this.maxRows=4,u=t,t.dpDiv.empty().append(this._generateHTML(t)),this._attachHandlers(t),t.dpDiv.find("."+this._dayOverClass+" a").mouseover();var n,r=this._getNumberOfMonths(t),i=r[1],s=17;t.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width(""),i>1&&t.dpDiv.addClass("ui-datepicker-multi-"+i).css("width",s*i+"em"),t.dpDiv[(r[0]!==1||r[1]!==1?"add":"remove")+"Class"]("ui-datepicker-multi"),t.dpDiv[(this._get(t,"isRTL")?"add":"remove")+"Class"]("ui-datepicker-rtl"),t===e.datepicker._curInst&&e.datepicker._datepickerShowing&&t.input&&t.input.is(":visible")&&!t.input.is(":disabled")&&t.input[0]!==document.activeElement&&t.input.focus(),t.yearshtml&&(n=t.yearshtml,setTimeout(function(){n===t.yearshtml&&t.yearshtml&&t.dpDiv.find("select.ui-datepicker-year:first").replaceWith(t.yearshtml),n=t.yearshtml=null},0))},_getBorders:function(e){var t=function(e){return{thin:1,medium:2,thick:3}[e]||e};return[parseFloat(t(e.css("border-left-width"))),parseFloat(t(e.css("border-top-width")))]},_checkOffset:function(t,n,r){var i=t.dpDiv.outerWidth(),s=t.dpDiv.outerHeight(),o=t.input?t.input.outerWidth():0,u=t.input?t.input.outerHeight():0,a=document.documentElement.clientWidth+(r?0:e(document).scrollLeft()),f=document.documentElement.clientHeight+(r?0:e(document).scrollTop());return n.left-=this._get(t,"isRTL")?i-o:0,n.left-=r&&n.left===t.input.offset().left?e(document).scrollLeft():0,n.top-=r&&n.top===t.input.offset().top+u?e(document).scrollTop():0,n.left-=Math.min(n.left,n.left+i>a&&a>i?Math.abs(n.left+i-a):0),n.top-=Math.min(n.top,n.top+s>f&&f>s?Math.abs(s+u):0),n},_findPos:function(t){var n,r=this._getInst(t),i=this._get(r,"isRTL");while(t&&(t.type==="hidden"||t.nodeType!==1||e.expr.filters.hidden(t)))t=t[i?"previousSibling":"nextSibling"];return n=e(t).offset(),[n.left,n.top]},_hideDatepicker:function(t){var n,r,i,o,u=this._curInst;if(!u||t&&u!==e.data(t,s))return;this._datepickerShowing&&(n=this._get(u,"showAnim"),r=this._get(u,"duration"),i=function(){e.datepicker._tidyDialog(u)},e.effects&&(e.effects.effect[n]||e.effects[n])?u.dpDiv.hide(n,e.datepicker._get(u,"showOptions"),r,i):u.dpDiv[n==="slideDown"?"slideUp":n==="fadeIn"?"fadeOut":"hide"](n?r:null,i),n||i(),this._datepickerShowing=!1,o=this._get(u,"onClose"),o&&o.apply(u.input?u.input[0]:null,[u.input?u.input.val():"",u]),this._lastInput=null,this._inDialog&&(this._dialogInput.css({position:"absolute",left:"0",top:"-100px"}),e.blockUI&&(e.unblockUI(),e("body").append(this.dpDiv))),this._inDialog=!1)},_tidyDialog:function(e){e.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar")},_checkExternalClick:function(t){if(!e.datepicker._curInst)return;var n=e(t.target),r=e.datepicker._getInst(n[0]);(n[0].id!==e.datepicker._mainDivId&&n.parents("#"+e.datepicker._mainDivId).length===0&&!n.hasClass(e.datepicker.markerClassName)&&!n.closest("."+e.datepicker._triggerClass).length&&e.datepicker._datepickerShowing&&(!e.datepicker._inDialog||!e.blockUI)||n.hasClass(e.datepicker.markerClassName)&&e.datepicker._curInst!==r)&&e.datepicker._hideDatepicker()},_adjustDate:function(t,n,r){var i=e(t),s=this._getInst(i[0]);if(this._isDisabledDatepicker(i[0]))return;this._adjustInstDate(s,n+(r==="M"?this._get(s,"showCurrentAtPos"):0),r),this._updateDatepicker(s)},_gotoToday:function(t){var n,r=e(t),i=this._getInst(r[0]);this._get(i,"gotoCurrent")&&i.currentDay?(i.selectedDay=i.currentDay,i.drawMonth=i.selectedMonth=i.currentMonth,i.drawYear=i.selectedYear=i.currentYear):(n=new Date,i.selectedDay=n.getDate(),i.drawMonth=i.selectedMonth=n.getMonth(),i.drawYear=i.selectedYear=n.getFullYear()),this._notifyChange(i),this._adjustDate(r)},_selectMonthYear:function(t,n,r){var i=e(t),s=this._getInst(i[0]);s["selected"+(r==="M"?"Month":"Year")]=s["draw"+(r==="M"?"Month":"Year")]=parseInt(n.options[n.selectedIndex].value,10),this._notifyChange(s),this._adjustDate(i)},_selectDay:function(t,n,r,i){var s,o=e(t);if(e(i).hasClass(this._unselectableClass)||this._isDisabledDatepicker(o[0]))return;s=this._getInst(o[0]),s.selectedDay=s.currentDay=e("a",i).html(),s.selectedMonth=s.currentMonth=n,s.selectedYear=s.currentYear=r,this._selectDate(t,this._formatDate(s,s.currentDay,s.currentMonth,s.currentYear))},_clearDate:function(t){var n=e(t);this._selectDate(n,"")},_selectDate:function(t,n){var r,i=e(t),s=this._getInst(i[0]);n=n!=null?n:this._formatDate(s),s.input&&s.input.val(n),this._updateAlternate(s),r=this._get(s,"onSelect"),r?r.apply(s.input?s.input[0]:null,[n,s]):s.input&&s.input.trigger("change"),s.inline?this._updateDatepicker(s):(this._hideDatepicker(),this._lastInput=s.input[0],typeof s.input[0]!="object"&&s.input.focus(),this._lastInput=null)},_updateAlternate:function(t){var n,r,i,s=this._get(t,"altField");s&&(n=this._get(t,"altFormat")||this._get(t,"dateFormat"),r=this._getDate(t),i=this.formatDate(n,r,this._getFormatConfig(t)),e(s).each(function(){e(this).val(i)}))},noWeekends:function(e){var t=e.getDay();return[t>0&&t<6,""]},iso8601Week:function(e){var t,n=new Date(e.getTime());return n.setDate(n.getDate()+4-(n.getDay()||7)),t=n.getTime(),n.setMonth(0),n.setDate(1),Math.floor(Math.round((t-n)/864e5)/7)+1},parseDate:function(t,n,r){if(t==null||n==null)throw"Invalid arguments";n=typeof n=="object"?n.toString():n+"";if(n==="")return null;var i,s,o,u=0,a=(r?r.shortYearCutoff:null)||this._defaults.shortYearCutoff,f=typeof a!="string"?a:(new Date).getFullYear()%100+parseInt(a,10),l=(r?r.dayNamesShort:null)||this._defaults.dayNamesShort,c=(r?r.dayNames:null)||this._defaults.dayNames,h=(r?r.monthNamesShort:null)||this._defaults.monthNamesShort,p=(r?r.monthNames:null)||this._defaults.monthNames,d=-1,v=-1,m=-1,g=-1,y=!1,b,w=function(e){var n=i+1<t.length&&t.charAt(i+1)===e;return n&&i++,n},E=function(e){var t=w(e),r=e==="@"?14:e==="!"?20:e==="y"&&t?4:e==="o"?3:2,i=new RegExp("^\\d{1,"+r+"}"),s=n.substring(u).match(i);if(!s)throw"Missing number at position "+u;return u+=s[0].length,parseInt(s[0],10)},S=function(t,r,i){var s=-1,o=e.map(w(t)?i:r,function(e,t){return[[t,e]]}).sort(function(e,t){return-(e[1].length-t[1].length)});e.each(o,function(e,t){var r=t[1];if(n.substr(u,r.length).toLowerCase()===r.toLowerCase())return s=t[0],u+=r.length,!1});if(s!==-1)return s+1;throw"Unknown name at position "+u},x=function(){if(n.charAt(u)!==t.charAt(i))throw"Unexpected literal at position "+u;u++};for(i=0;i<t.length;i++)if(y)t.charAt(i)==="'"&&!w("'")?y=!1:x();else switch(t.charAt(i)){case"d":m=E("d");break;case"D":S("D",l,c);break;case"o":g=E("o");break;case"m":v=E("m");break;case"M":v=S("M",h,p);break;case"y":d=E("y");break;case"@":b=new Date(E("@")),d=b.getFullYear(),v=b.getMonth()+1,m=b.getDate();break;case"!":b=new Date((E("!")-this._ticksTo1970)/1e4),d=b.getFullYear(),v=b.getMonth()+1,m=b.getDate();break;case"'":w("'")?x():y=!0;break;default:x()}if(u<n.length){o=n.substr(u);if(!/^\s+/.test(o))throw"Extra/unparsed characters found in date: "+o}d===-1?d=(new Date).getFullYear():d<100&&(d+=(new Date).getFullYear()-(new Date).getFullYear()%100+(d<=f?0:-100));if(g>-1){v=1,m=g;do{s=this._getDaysInMonth(d,v-1);if(m<=s)break;v++,m-=s}while(!0)}b=this._daylightSavingAdjust(new Date(d,v-1,m));if(b.getFullYear()!==d||b.getMonth()+1!==v||b.getDate()!==m)throw"Invalid date";return b},ATOM:"yy-mm-dd",COOKIE:"D, dd M yy",ISO_8601:"yy-mm-dd",RFC_822:"D, d M y",RFC_850:"DD, dd-M-y",RFC_1036:"D, d M y",RFC_1123:"D, d M yy",RFC_2822:"D, d M yy",RSS:"D, d M y",TICKS:"!",TIMESTAMP:"@",W3C:"yy-mm-dd",_ticksTo1970:(718685+Math.floor(492.5)-Math.floor(19.7)+Math.floor(4.925))*24*60*60*1e7,formatDate:function(e,t,n){if(!t)return"";var r,i=(n?n.dayNamesShort:null)||this._defaults.dayNamesShort,s=(n?n.dayNames:null)||this._defaults.dayNames,o=(n?n.monthNamesShort:null)||this._defaults.monthNamesShort,u=(n?n.monthNames:null)||this._defaults.monthNames,a=function(t){var n=r+1<e.length&&e.charAt(r+1)===t;return n&&r++,n},f=function(e,t,n){var r=""+t;if(a(e))while(r.length<n)r="0"+r;return r},l=function(e,t,n,r){return a(e)?r[t]:n[t]},c="",h=!1;if(t)for(r=0;r<e.length;r++)if(h)e.charAt(r)==="'"&&!a("'")?h=!1:c+=e.charAt(r);else switch(e.charAt(r)){case"d":c+=f("d",t.getDate(),2);break;case"D":c+=l("D",t.getDay(),i,s);break;case"o":c+=f("o",Math.round(((new Date(t.getFullYear(),t.getMonth(),t.getDate())).getTime()-(new Date(t.getFullYear(),0,0)).getTime())/864e5),3);break;case"m":c+=f("m",t.getMonth()+1,2);break;case"M":c+=l("M",t.getMonth(),o,u);break;case"y":c+=a("y")?t.getFullYear():(t.getYear()%100<10?"0":"")+t.getYear()%100;break;case"@":c+=t.getTime();break;case"!":c+=t.getTime()*1e4+this._ticksTo1970;break;case"'":a("'")?c+="'":h=!0;break;default:c+=e.charAt(r)}return c},_possibleChars:function(e){var t,n="",r=!1,i=function(n){var r=t+1<e.length&&e.charAt(t+1)===n;return r&&t++,r};for(t=0;t<e.length;t++)if(r)e.charAt(t)==="'"&&!i("'")?r=!1:n+=e.charAt(t);else switch(e.charAt(t)){case"d":case"m":case"y":case"@":n+="0123456789";break;case"D":case"M":return null;case"'":i("'")?n+="'":r=!0;break;default:n+=e.charAt(t)}return n},_get:function(e,n){return e.settings[n]!==t?e.settings[n]:this._defaults[n]},_setDateFromField:function(e,t){if(e.input.val()===e.lastVal)return;var n=this._get(e,"dateFormat"),r=e.lastVal=e.input?e.input.val():null,i=this._getDefaultDate(e),s=i,o=this._getFormatConfig(e);try{s=this.parseDate(n,r,o)||i}catch(u){r=t?"":r}e.selectedDay=s.getDate(),e.drawMonth=e.selectedMonth=s.getMonth(),e.drawYear=e.selectedYear=s.getFullYear(),e.currentDay=r?s.getDate():0,e.currentMonth=r?s.getMonth():0,e.currentYear=r?s.getFullYear():0,this._adjustInstDate(e)},_getDefaultDate:function(e){return this._restrictMinMax(e,this._determineDate(e,this._get(e,"defaultDate"),new Date))},_determineDate:function(t,n,r){var i=function(e){var t=new Date;return t.setDate(t.getDate()+e),t},s=function(n){try{return e.datepicker.parseDate(e.datepicker._get(t,"dateFormat"),n,e.datepicker._getFormatConfig(t))}catch(r){}var i=(n.toLowerCase().match(/^c/)?e.datepicker._getDate(t):null)||new Date,s=i.getFullYear(),o=i.getMonth(),u=i.getDate(),a=/([+\-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,f=a.exec(n);while(f){switch(f[2]||"d"){case"d":case"D":u+=parseInt(f[1],10);break;case"w":case"W":u+=parseInt(f[1],10)*7;break;case"m":case"M":o+=parseInt(f[1],10),u=Math.min(u,e.datepicker._getDaysInMonth(s,o));break;case"y":case"Y":s+=parseInt(f[1],10),u=Math.min(u,e.datepicker._getDaysInMonth(s,o))}f=a.exec(n)}return new Date(s,o,u)},o=n==null||n===""?r:typeof n=="string"?s(n):typeof n=="number"?isNaN(n)?r:i(n):new Date(n.getTime());return o=o&&o.toString()==="Invalid Date"?r:o,o&&(o.setHours(0),o.setMinutes(0),o.setSeconds(0),o.setMilliseconds(0)),this._daylightSavingAdjust(o)},_daylightSavingAdjust:function(e){return e?(e.setHours(e.getHours()>12?e.getHours()+2:0),e):null},_setDate:function(e,t,n){var r=!t,i=e.selectedMonth,s=e.selectedYear,o=this._restrictMinMax(e,this._determineDate(e,t,new Date));e.selectedDay=e.currentDay=o.getDate(),e.drawMonth=e.selectedMonth=e.currentMonth=o.getMonth(),e.drawYear=e.selectedYear=e.currentYear=o.getFullYear(),(i!==e.selectedMonth||s!==e.selectedYear)&&!n&&this._notifyChange(e),this._adjustInstDate(e),e.input&&e.input.val(r?"":this._formatDate(e))},_getDate:function(e){var t=!e.currentYear||e.input&&e.input.val()===""?null:this._daylightSavingAdjust(new Date(e.currentYear,e.currentMonth,e.currentDay));return t},_attachHandlers:function(t){var n=this._get(t,"stepMonths"),r="#"+t.id.replace(/\\\\/g,"\\");t.dpDiv.find("[data-handler]").map(function(){var t={prev:function(){window["DP_jQuery_"+o].datepicker._adjustDate(r,-n,"M")},next:function(){window["DP_jQuery_"+o].datepicker._adjustDate(r,+n,"M")},hide:function(){window["DP_jQuery_"+o].datepicker._hideDatepicker()},today:function(){window["DP_jQuery_"+o].datepicker._gotoToday(r)},selectDay:function(){return window["DP_jQuery_"+o].datepicker._selectDay(r,+this.getAttribute("data-month"),+this.getAttribute("data-year"),this),!1},selectMonth:function(){return window["DP_jQuery_"+o].datepicker._selectMonthYear(r,this,"M"),!1},selectYear:function(){return window["DP_jQuery_"+o].datepicker._selectMonthYear(r,this,"Y"),!1}};e(this).bind(this.getAttribute("data-event"),t[this.getAttribute("data-handler")])})},_generateHTML:function(e){var t,n,r,i,s,o,u,a,f,l,c,h,p,d,v,m,g,y,b,w,E,S,x,T,N,C,k,L,A,O,M,_,D,P,H,B,j,F,I,q=new Date,R=this._daylightSavingAdjust(new Date(q.getFullYear(),q.getMonth(),q.getDate())),U=this._get(e,"isRTL"),z=this._get(e,"showButtonPanel"),W=this._get(e,"hideIfNoPrevNext"),X=this._get(e,"navigationAsDateFormat"),V=this._getNumberOfMonths(e),$=this._get(e,"showCurrentAtPos"),J=this._get(e,"stepMonths"),K=V[0]!==1||V[1]!==1,Q=this._daylightSavingAdjust(e.currentDay?new Date(e.currentYear,e.currentMonth,e.currentDay):new Date(9999,9,9)),G=this._getMinMaxDate(e,"min"),Y=this._getMinMaxDate(e,"max"),Z=e.drawMonth-$,et=e.drawYear;Z<0&&(Z+=12,et--);if(Y){t=this._daylightSavingAdjust(new Date(Y.getFullYear(),Y.getMonth()-V[0]*V[1]+1,Y.getDate())),t=G&&t<G?G:t;while(this._daylightSavingAdjust(new Date(et,Z,1))>t)Z--,Z<0&&(Z=11,et--)}e.drawMonth=Z,e.drawYear=et,n=this._get(e,"prevText"),n=X?this.formatDate(n,this._daylightSavingAdjust(new Date(et,Z-J,1)),this._getFormatConfig(e)):n,r=this._canAdjustMonth(e,-1,et,Z)?"<a class='ui-datepicker-prev ui-corner-all' data-handler='prev' data-event='click' title='"+n+"'><span class='ui-icon ui-icon-circle-triangle-"+(U?"e":"w")+"'>"+n+"</span></a>":W?"":"<a class='ui-datepicker-prev ui-corner-all ui-state-disabled' title='"+n+"'><span class='ui-icon ui-icon-circle-triangle-"+(U?"e":"w")+"'>"+n+"</span></a>",i=this._get(e,"nextText"),i=X?this.formatDate(i,this._daylightSavingAdjust(new Date(et,Z+J,1)),this._getFormatConfig(e)):i,s=this._canAdjustMonth(e,1,et,Z)?"<a class='ui-datepicker-next ui-corner-all' data-handler='next' data-event='click' title='"+i+"'><span class='ui-icon ui-icon-circle-triangle-"+(U?"w":"e")+"'>"+i+"</span></a>":W?"":"<a class='ui-datepicker-next ui-corner-all ui-state-disabled' title='"+i+"'><span class='ui-icon ui-icon-circle-triangle-"+(U?"w":"e")+"'>"+i+"</span></a>",o=this._get(e,"currentText"),u=this._get(e,"gotoCurrent")&&e.currentDay?Q:R,o=X?this.formatDate(o,u,this._getFormatConfig(e)):o,a=e.inline?"":"<button type='button' class='ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all' data-handler='hide' data-event='click'>"+this._get(e,"closeText")+"</button>",f=z?"<div class='ui-datepicker-buttonpane ui-widget-content'>"+(U?a:"")+(this._isInRange(e,u)?"<button type='button' class='ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all' data-handler='today' data-event='click'>"+o+"</button>":"")+(U?"":a)+"</div>":"",l=parseInt(this._get(e,"firstDay"),10),l=isNaN(l)?0:l,c=this._get(e,"showWeek"),h=this._get(e,"dayNames"),p=this._get(e,"dayNamesMin"),d=this._get(e,"monthNames"),v=this._get(e,"monthNamesShort"),m=this._get(e,"beforeShowDay"),g=this._get(e,"showOtherMonths"),y=this._get(e,"selectOtherMonths"),b=this._getDefaultDate(e),w="",E;for(S=0;S<V[0];S++){x="",this.maxRows=4;for(T=0;T<V[1];T++){N=this._daylightSavingAdjust(new Date(et,Z,e.selectedDay)),C=" ui-corner-all",k="";if(K){k+="<div class='ui-datepicker-group";if(V[1]>1)switch(T){case 0:k+=" ui-datepicker-group-first",C=" ui-corner-"+(U?"right":"left");break;case V[1]-1:k+=" ui-datepicker-group-last",C=" ui-corner-"+(U?"left":"right");break;default:k+=" ui-datepicker-group-middle",C=""}k+="'>"}k+="<div class='ui-datepicker-header ui-widget-header ui-helper-clearfix"+C+"'>"+(/all|left/.test(C)&&S===0?U?s:r:"")+(/all|right/.test(C)&&S===0?U?r:s:"")+this._generateMonthYearHeader(e,Z,et,G,Y,S>0||T>0,d,v)+"</div><table class='ui-datepicker-calendar'><thead>"+"<tr>",L=c?"<th class='ui-datepicker-week-col'>"+this._get(e,"weekHeader")+"</th>":"";for(E=0;E<7;E++)A=(E+l)%7,L+="<th"+((E+l+6)%7>=5?" class='ui-datepicker-week-end'":"")+">"+"<span title='"+h[A]+"'>"+p[A]+"</span></th>";k+=L+"</tr></thead><tbody>",O=this._getDaysInMonth(et,Z),et===e.selectedYear&&Z===e.selectedMonth&&(e.selectedDay=Math.min(e.selectedDay,O)),M=(this._getFirstDayOfMonth(et,Z)-l+7)%7,_=Math.ceil((M+O)/7),D=K?this.maxRows>_?this.maxRows:_:_,this.maxRows=D,P=this._daylightSavingAdjust(new Date(et,Z,1-M));for(H=0;H<D;H++){k+="<tr>",B=c?"<td class='ui-datepicker-week-col'>"+this._get(e,"calculateWeek")(P)+"</td>":"";for(E=0;E<7;E++)j=m?m.apply(e.input?e.input[0]:null,[P]):[!0,""],F=P.getMonth()!==Z,I=F&&!y||!j[0]||G&&P<G||Y&&P>Y,B+="<td class='"+((E+l+6)%7>=5?" ui-datepicker-week-end":"")+(F?" ui-datepicker-other-month":"")+(P.getTime()===N.getTime()&&Z===e.selectedMonth&&e._keyEvent||b.getTime()===P.getTime()&&b.getTime()===N.getTime()?" "+this._dayOverClass:"")+(I?" "+this._unselectableClass+" ui-state-disabled":"")+(F&&!g?"":" "+j[1]+(P.getTime()===Q.getTime()?" "+this._currentClass:"")+(P.getTime()===R.getTime()?" ui-datepicker-today":""))+"'"+((!F||g)&&j[2]?" title='"+j[2]+"'":"")+(I?"":" data-handler='selectDay' data-event='click' data-month='"+P.getMonth()+"' data-year='"+P.getFullYear()+"'")+">"+(F&&!g?" ":I?"<span class='ui-state-default'>"+P.getDate()+"</span>":"<a class='ui-state-default"+(P.getTime()===R.getTime()?" ui-state-highlight":"")+(P.getTime()===Q.getTime()?" ui-state-active":"")+(F?" ui-priority-secondary":"")+"' href='#'>"+P.getDate()+"</a>")+"</td>",P.setDate(P.getDate()+1),P=this._daylightSavingAdjust(P);k+=B+"</tr>"}Z++,Z>11&&(Z=0,et++),k+="</tbody></table>"+(K?"</div>"+(V[0]>0&&T===V[1]-1?"<div class='ui-datepicker-row-break'></div>":""):""),x+=k}w+=x}return w+=f,e._keyEvent=!1,w},_generateMonthYearHeader:function(e,t,n,r,i,s,o,u){var a,f,l,c,h,p,d,v,m=this._get(e,"changeMonth"),g=this._get(e,"changeYear"),y=this._get(e,"showMonthAfterYear"),b="<div class='ui-datepicker-title'>",w="";if(s||!m)w+="<span class='ui-datepicker-month'>"+o[t]+"</span>";else{a=r&&r.getFullYear()===n,f=i&&i.getFullYear()===n,w+="<select class='ui-datepicker-month' data-handler='selectMonth' data-event='change'>";for(l=0;l<12;l++)(!a||l>=r.getMonth())&&(!f||l<=i.getMonth())&&(w+="<option value='"+l+"'"+(l===t?" selected='selected'":"")+">"+u[l]+"</option>");w+="</select>"}y||(b+=w+(s||!m||!g?" ":""));if(!e.yearshtml){e.yearshtml="";if(s||!g)b+="<span class='ui-datepicker-year'>"+n+"</span>";else{c=this._get(e,"yearRange").split(":"),h=(new Date).getFullYear(),p=function(e){var t=e.match(/c[+\-].*/)?n+parseInt(e.substring(1),10):e.match(/[+\-].*/)?h+parseInt(e,10):parseInt(e,10);return isNaN(t)?h:t},d=p(c[0]),v=Math.max(d,p(c[1]||"")),d=r?Math.max(d,r.getFullYear()):d,v=i?Math.min(v,i.getFullYear()):v,e.yearshtml+="<select class='ui-datepicker-year' data-handler='selectYear' data-event='change'>";for(;d<=v;d++)e.yearshtml+="<option value='"+d+"'"+(d===n?" selected='selected'":"")+">"+d+"</option>";e.yearshtml+="</select>",b+=e.yearshtml,e.yearshtml=null}}return b+=this._get(e,"yearSuffix"),y&&(b+=(s||!m||!g?" ":"")+w),b+="</div>",b},_adjustInstDate:function(e,t,n){var r=e.drawYear+(n==="Y"?t:0),i=e.drawMonth+(n==="M"?t:0),s=Math.min(e.selectedDay,this._getDaysInMonth(r,i))+(n==="D"?t:0),o=this._restrictMinMax(e,this._daylightSavingAdjust(new Date(r,i,s)));e.selectedDay=o.getDate(),e.drawMonth=e.selectedMonth=o.getMonth(),e.drawYear=e.selectedYear=o.getFullYear(),(n==="M"||n==="Y")&&this._notifyChange(e)},_restrictMinMax:function(e,t){var n=this._getMinMaxDate(e,"min"),r=this._getMinMaxDate(e,"max"),i=n&&t<n?n:t;return r&&i>r?r:i},_notifyChange:function(e){var t=this._get(e,"onChangeMonthYear");t&&t.apply(e.input?e.input[0]:null,[e.selectedYear,e.selectedMonth+1,e])},_getNumberOfMonths:function(e){var t=this._get(e,"numberOfMonths");return t==null?[1,1]:typeof t=="number"?[1,t]:t},_getMinMaxDate:function(e,t){return this._determineDate(e,this._get(e,t+"Date"),null)},_getDaysInMonth:function(e,t){return 32-this._daylightSavingAdjust(new Date(e,t,32)).getDate()},_getFirstDayOfMonth:function(e,t){return(new Date(e,t,1)).getDay()},_canAdjustMonth:function(e,t,n,r){var i=this._getNumberOfMonths(e),s=this._daylightSavingAdjust(new Date(n,r+(t<0?t:i[0]*i[1]),1));return t<0&&s.setDate(this._getDaysInMonth(s.getFullYear(),s.getMonth())),this._isInRange(e,s)},_isInRange:function(e,t){var n,r,i=this._getMinMaxDate(e,"min"),s=this._getMinMaxDate(e,"max"),o=null,u=null,a=this._get(e,"yearRange");return a&&(n=a.split(":"),r=(new Date).getFullYear(),o=parseInt(n[0],10)+r,u=parseInt(n[1],10)+r),(!i||t.getTime()>=i.getTime())&&(!s||t.getTime()<=s.getTime())&&(!o||t.getFullYear()>=o)&&(!u||t.getFullYear()<=u)},_getFormatConfig:function(e){var t=this._get(e,"shortYearCutoff");return t=typeof t!="string"?t:(new Date).getFullYear()%100+parseInt(t,10),{shortYearCutoff:t,dayNamesShort:this._get(e,"dayNamesShort"),dayNames:this._get(e,"dayNames"),monthNamesShort:this._get(e,"monthNamesShort"),monthNames:this._get(e,"monthNames")}},_formatDate:function(e,t,n,r){t||(e.currentDay=e.selectedDay,e.currentMonth=e.selectedMonth,e.currentYear=e.selectedYear);var i=t?typeof t=="object"?t:this._daylightSavingAdjust(new Date(r,n,t)):this._daylightSavingAdjust(new Date(e.currentYear,e.currentMonth,e.currentDay));return this.formatDate(this._get(e,"dateFormat"),i,this._getFormatConfig(e))}}),e.fn.datepicker=function(t){if(!this.length)return this;e.datepicker.initialized||(e(document).mousedown(e.datepicker._checkExternalClick),e.datepicker.initialized=!0),e("#"+e.datepicker._mainDivId).length===0&&e("body").append(e.datepicker.dpDiv);var n=Array.prototype.slice.call(arguments,1);return typeof t!="string"||t!=="isDisabled"&&t!=="getDate"&&t!=="widget"?t==="option"&&arguments.length===2&&typeof arguments[1]=="string"?e.datepicker["_"+t+"Datepicker"].apply(e.datepicker,[this[0]].concat(n)):this.each(function(){typeof t=="string"?e.datepicker["_"+t+"Datepicker"].apply(e.datepicker,[this].concat(n)):e.datepicker._attachDatepicker(this,t)}):e.datepicker["_"+t+"Datepicker"].apply(e.datepicker,[this[0]].concat(n))},e.datepicker=new n,e.datepicker.initialized=!1,e.datepicker.uuid=(new Date).getTime(),e.datepicker.version="1.10.0",window["DP_jQuery_"+o]=e})(jQuery);(function(e,t){var n={buttons:!0,height:!0,maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0,width:!0},r={maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0};e.widget("ui.dialog",{version:"1.10.0",options:{appendTo:"body",autoOpen:!0,buttons:[],closeOnEscape:!0,closeText:"close",dialogClass:"",draggable:!0,hide:null,height:"auto",maxHeight:null,maxWidth:null,minHeight:150,minWidth:150,modal:!1,position:{my:"center",at:"center",of:window,collision:"fit",using:function(t){var n=e(this).css(t).offset().top;n<0&&e(this).css("top",t.top-n)}},resizable:!0,show:null,title:null,width:300,beforeClose:null,close:null,drag:null,dragStart:null,dragStop:null,focus:null,open:null,resize:null,resizeStart:null,resizeStop:null},_create:function(){this.originalCss={display:this.element[0].style.display,width:this.element[0].style.width,minHeight:this.element[0].style.minHeight,maxHeight:this.element[0].style.maxHeight,height:this.element[0].style.height},this.originalPosition={parent:this.element.parent(),index:this.element.parent().children().index(this.element)},this.originalTitle=this.element.attr("title"),this.options.title=this.options.title||this.originalTitle,this._createWrapper(),this.element.show().removeAttr("title").addClass("ui-dialog-content ui-widget-content").appendTo(this.uiDialog),this._createTitlebar(),this._createButtonPane(),this.options.draggable&&e.fn.draggable&&this._makeDraggable(),this.options.resizable&&e.fn.resizable&&this._makeResizable(),this._isOpen=!1},_init:function(){this.options.autoOpen&&this.open()},_appendTo:function(){var t=this.options.appendTo;return t&&(t.jquery||t.nodeType)?e(t):this.document.find(t||"body").eq(0)},_destroy:function(){var e,t=this.originalPosition;this._destroyOverlay(),this.element.removeUniqueId().removeClass("ui-dialog-content ui-widget-content").css(this.originalCss).detach(),this.uiDialog.stop(!0,!0).remove(),this.originalTitle&&this.element.attr("title",this.originalTitle),e=t.parent.children().eq(t.index),e.length&&e[0]!==this.element[0]?e.before(this.element):t.parent.append(this.element)},widget:function(){return this.uiDialog},disable:e.noop,enable:e.noop,close:function(t){var n=this;if(!this._isOpen||this._trigger("beforeClose",t)===!1)return;this._isOpen=!1,this._destroyOverlay(),this.opener.filter(":focusable").focus().length||e(this.document[0].activeElement).blur(),this._hide(this.uiDialog,this.options.hide,function(){n._trigger("close",t)})},isOpen:function(){return this._isOpen},moveToTop:function(){this._moveToTop()},_moveToTop:function(e,t){var n=!!this.uiDialog.nextAll(":visible").insertBefore(this.uiDialog).length;return n&&!t&&this._trigger("focus",e),n},open:function(){if(this._isOpen){this._moveToTop()&&this._focusTabbable();return}this.opener=e(this.document[0].activeElement),this._size(),this._position(),this._createOverlay(),this._moveToTop(null,!0),this._show(this.uiDialog,this.options.show),this._focusTabbable(),this._isOpen=!0,this._trigger("open"),this._trigger("focus")},_focusTabbable:function(){var e=this.element.find("[autofocus]");e.length||(e=this.element.find(":tabbable")),e.length||(e=this.uiDialogButtonPane.find(":tabbable")),e.length||(e=this.uiDialogTitlebarClose.filter(":tabbable")),e.length||(e=this.uiDialog),e.eq(0).focus()},_keepFocus:function(t){function n(){var t=this.document[0].activeElement,n=this.uiDialog[0]===t||e.contains(this.uiDialog[0],t);n||this._focusTabbable()}t.preventDefault(),n.call(this),this._delay(n)},_createWrapper:function(){this.uiDialog=e("<div>").addClass("ui-dialog ui-widget ui-widget-content ui-corner-all ui-front "+this.options.dialogClass).hide().attr({tabIndex:-1,role:"dialog"}).appendTo(this._appendTo()),this._on(this.uiDialog,{keydown:function(t){if(this.options.closeOnEscape&&!t.isDefaultPrevented()&&t.keyCode&&t.keyCode===e.ui.keyCode.ESCAPE){t.preventDefault(),this.close(t);return}if(t.keyCode!==e.ui.keyCode.TAB)return;var n=this.uiDialog.find(":tabbable"),r=n.filter(":first"),i=n.filter(":last");t.target!==i[0]&&t.target!==this.uiDialog[0]||!!t.shiftKey?(t.target===r[0]||t.target===this.uiDialog[0])&&t.shiftKey&&(i.focus(1),t.preventDefault()):(r.focus(1),t.preventDefault())},mousedown:function(e){this._moveToTop(e)&&this._focusTabbable()}}),this.element.find("[aria-describedby]").length||this.uiDialog.attr({"aria-describedby":this.element.uniqueId().attr("id")})},_createTitlebar:function(){var t;this.uiDialogTitlebar=e("<div>").addClass("ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix").prependTo(this.uiDialog),this._on(this.uiDialogTitlebar,{mousedown:function(t){e(t.target).closest(".ui-dialog-titlebar-close")||this.uiDialog.focus()}}),this.uiDialogTitlebarClose=e("<button></button>").button({label:this.options.closeText,icons:{primary:"ui-icon-closethick"},text:!1}).addClass("ui-dialog-titlebar-close").appendTo(this.uiDialogTitlebar),this._on(this.uiDialogTitlebarClose,{click:function(e){e.preventDefault(),this.close(e)}}),t=e("<span>").uniqueId().addClass("ui-dialog-title").prependTo(this.uiDialogTitlebar),this._title(t),this.uiDialog.attr({"aria-labelledby":t.attr("id")})},_title:function(e){this.options.title||e.html(" "),e.text(this.options.title)},_createButtonPane:function(){this.uiDialogButtonPane=e("<div>").addClass("ui-dialog-buttonpane ui-widget-content ui-helper-clearfix"),this.uiButtonSet=e("<div>").addClass("ui-dialog-buttonset").appendTo(this.uiDialogButtonPane),this._createButtons()},_createButtons:function(){var t=this,n=this.options.buttons;this.uiDialogButtonPane.remove(),this.uiButtonSet.empty();if(e.isEmptyObject(n)){this.uiDialog.removeClass("ui-dialog-buttons");return}e.each(n,function(n,r){var i,s;r=e.isFunction(r)?{click:r,text:n}:r,r=e.extend({type:"button"},r),i=r.click,r.click=function(){i.apply(t.element[0],arguments)},s={icons:r.icons,text:r.showText},delete r.icons,delete r.showText,e("<button></button>",r).button(s).appendTo(t.uiButtonSet)}),this.uiDialog.addClass("ui-dialog-buttons"),this.uiDialogButtonPane.appendTo(this.uiDialog)},_makeDraggable:function(){function t(e){return{position:e.position,offset:e.offset}}var n=this,r=this.options;this.uiDialog.draggable({cancel:".ui-dialog-content, .ui-dialog-titlebar-close",handle:".ui-dialog-titlebar",containment:"document",start:function(r,i){e(this).addClass("ui-dialog-dragging"),n._trigger("dragStart",r,t(i))},drag:function(e,r){n._trigger("drag",e,t(r))},stop:function(i,s){r.position=[s.position.left-n.document.scrollLeft(),s.position.top-n.document.scrollTop()],e(this).removeClass("ui-dialog-dragging"),n._trigger("dragStop",i,t(s))}})},_makeResizable:function(){function t(e){return{originalPosition:e.originalPosition,originalSize:e.originalSize,position:e.position,size:e.size}}var n=this,r=this.options,i=r.resizable,s=this.uiDialog.css("position"),o=typeof i=="string"?i:"n,e,s,w,se,sw,ne,nw";this.uiDialog.resizable({cancel:".ui-dialog-content",containment:"document",alsoResize:this.element,maxWidth:r.maxWidth,maxHeight:r.maxHeight,minWidth:r.minWidth,minHeight:this._minHeight(),handles:o,start:function(r,i){e(this).addClass("ui-dialog-resizing"),n._trigger("resizeStart",r,t(i))},resize:function(e,r){n._trigger("resize",e,t(r))},stop:function(i,s){r.height=e(this).height(),r.width=e(this).width(),e(this).removeClass("ui-dialog-resizing"),n._trigger("resizeStop",i,t(s))}}).css("position",s)},_minHeight:function(){var e=this.options;return e.height==="auto"?e.minHeight:Math.min(e.minHeight,e.height)},_position:function(){var e=this.uiDialog.is(":visible");e||this.uiDialog.show(),this.uiDialog.position(this.options.position),e||this.uiDialog.hide()},_setOptions:function(t){var i=this,s=!1,o={};e.each(t,function(e,t){i._setOption(e,t),e in n&&(s=!0),e in r&&(o[e]=t)}),s&&(this._size(),this._position()),this.uiDialog.is(":data(ui-resizable)")&&this.uiDialog.resizable("option",o)},_setOption:function(e,t){var n,r,i=this.uiDialog;e==="dialogClass"&&i.removeClass(this.options.dialogClass).addClass(t);if(e==="disabled")return;this._super(e,t),e==="appendTo"&&this.uiDialog.appendTo(this._appendTo()),e==="buttons"&&this._createButtons(),e==="closeText"&&this.uiDialogTitlebarClose.button({label:""+t}),e==="draggable"&&(n=i.is(":data(ui-draggable)"),n&&!t&&i.draggable("destroy"),!n&&t&&this._makeDraggable()),e==="position"&&this._position(),e==="resizable"&&(r=i.is(":data(ui-resizable)"),r&&!t&&i.resizable("destroy"),r&&typeof t=="string"&&i.resizable("option","handles",t),!r&&t!==!1&&this._makeResizable()),e==="title"&&this._title(this.uiDialogTitlebar.find(".ui-dialog-title"))},_size:function(){var e,t,n,r=this.options;this.element.show().css({width:"auto",minHeight:0,maxHeight:"none",height:0}),r.minWidth>r.width&&(r.width=r.minWidth),e=this.uiDialog.css({height:"auto",width:r.width}).outerHeight(),t=Math.max(0,r.minHeight-e),n=typeof r.maxHeight=="number"?Math.max(0,r.maxHeight-e):"none",r.height==="auto"?this.element.css({minHeight:t,maxHeight:n,height:"auto"}):this.element.height(Math.max(0,r.height-e)),this.uiDialog.is(":data(ui-resizable)")&&this.uiDialog.resizable("option","minHeight",this._minHeight())},_createOverlay:function(){if(!this.options.modal)return;e.ui.dialog.overlayInstances||this._delay(function(){e.ui.dialog.overlayInstances&&this._on(this.document,{focusin:function(t){e(t.target).closest(".ui-dialog").length||(t.preventDefault(),e(".ui-dialog:visible:last .ui-dialog-content").data("ui-dialog")._focusTabbable())}})}),this.overlay=e("<div>").addClass("ui-widget-overlay ui-front").appendTo(this.document[0].body),this._on(this.overlay,{mousedown:"_keepFocus"}),e.ui.dialog.overlayInstances++},_destroyOverlay:function(){if(!this.options.modal)return;e.ui.dialog.overlayInstances--,e.ui.dialog.overlayInstances||this._off(this.document,"focusin"),this.overlay.remove()}}),e.ui.dialog.overlayInstances=0,e.uiBackCompat!==!1&&e.widget("ui.dialog",e.ui.dialog,{_position:function(){var t=this.options.position,n=[],r=[0,0],i;if(t){if(typeof t=="string"||typeof t=="object"&&"0"in t)n=t.split?t.split(" "):[t[0],t[1]],n.length===1&&(n[1]=n[0]),e.each(["left","top"],function(e,t){+n[e]===n[e]&&(r[e]=n[e],n[e]=t)}),t={my:n[0]+(r[0]<0?r[0]:"+"+r[0])+" "+n[1]+(r[1]<0?r[1]:"+"+r[1]),at:n.join(" ")};t=e.extend({},e.ui.dialog.prototype.options.position,t)}else t=e.ui.dialog.prototype.options.position;i=this.uiDialog.is(":visible"),i||this.uiDialog.show(),this.uiDialog.position(t),i||this.uiDialog.hide()}})})(jQuery);(function(e,t){e.widget("ui.menu",{version:"1.10.0",defaultElement:"<ul>",delay:300,options:{icons:{submenu:"ui-icon-carat-1-e"},menus:"ul",position:{my:"left top",at:"right top"},role:"menu",blur:null,focus:null,select:null},_create:function(){this.activeMenu=this.element,this.mouseHandled=!1,this.element.uniqueId().addClass("ui-menu ui-widget ui-widget-content ui-corner-all").toggleClass("ui-menu-icons",!!this.element.find(".ui-icon").length).attr({role:this.options.role,tabIndex:0}).bind("click"+this.eventNamespace,e.proxy(function(e){this.options.disabled&&e.preventDefault()},this)),this.options.disabled&&this.element.addClass("ui-state-disabled").attr("aria-disabled","true"),this._on({"mousedown .ui-menu-item > a":function(e){e.preventDefault()},"click .ui-state-disabled > a":function(e){e.preventDefault()},"click .ui-menu-item:has(a)":function(t){var n=e(t.target).closest(".ui-menu-item");!this.mouseHandled&&n.not(".ui-state-disabled").length&&(this.mouseHandled=!0,this.select(t),n.has(".ui-menu").length?this.expand(t):this.element.is(":focus")||(this.element.trigger("focus",[!0]),this.active&&this.active.parents(".ui-menu").length===1&&clearTimeout(this.timer)))},"mouseenter .ui-menu-item":function(t){var n=e(t.currentTarget);n.siblings().children(".ui-state-active").removeClass("ui-state-active"),this.focus(t,n)},mouseleave:"collapseAll","mouseleave .ui-menu":"collapseAll",focus:function(e,t){var n=this.active||this.element.children(".ui-menu-item").eq(0);t||this.focus(e,n)},blur:function(t){this._delay(function(){e.contains(this.element[0],this.document[0].activeElement)||this.collapseAll(t)})},keydown:"_keydown"}),this.refresh(),this._on(this.document,{click:function(t){e(t.target).closest(".ui-menu").length||this.collapseAll(t),this.mouseHandled=!1}})},_destroy:function(){this.element.removeAttr("aria-activedescendant").find(".ui-menu").addBack().removeClass("ui-menu ui-widget ui-widget-content ui-corner-all ui-menu-icons").removeAttr("role").removeAttr("tabIndex").removeAttr("aria-labelledby").removeAttr("aria-expanded").removeAttr("aria-hidden").removeAttr("aria-disabled").removeUniqueId().show(),this.element.find(".ui-menu-item").removeClass("ui-menu-item").removeAttr("role").removeAttr("aria-disabled").children("a").removeUniqueId().removeClass("ui-corner-all ui-state-hover").removeAttr("tabIndex").removeAttr("role").removeAttr("aria-haspopup").children().each(function(){var t=e(this);t.data("ui-menu-submenu-carat")&&t.remove()}),this.element.find(".ui-menu-divider").removeClass("ui-menu-divider ui-widget-content")},_keydown:function(t){function n(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}var r,i,s,o,u,a=!0;switch(t.keyCode){case e.ui.keyCode.PAGE_UP:this.previousPage(t);break;case e.ui.keyCode.PAGE_DOWN:this.nextPage(t);break;case e.ui.keyCode.HOME:this._move("first","first",t);break;case e.ui.keyCode.END:this._move("last","last",t);break;case e.ui.keyCode.UP:this.previous(t);break;case e.ui.keyCode.DOWN:this.next(t);break;case e.ui.keyCode.LEFT:this.collapse(t);break;case e.ui.keyCode.RIGHT:this.active&&!this.active.is(".ui-state-disabled")&&this.expand(t);break;case e.ui.keyCode.ENTER:case e.ui.keyCode.SPACE:this._activate(t);break;case e.ui.keyCode.ESCAPE:this.collapse(t);break;default:a=!1,i=this.previousFilter||"",s=String.fromCharCode(t.keyCode),o=!1,clearTimeout(this.filterTimer),s===i?o=!0:s=i+s,u=new RegExp("^"+n(s),"i"),r=this.activeMenu.children(".ui-menu-item").filter(function(){return u.test(e(this).children("a").text())}),r=o&&r.index(this.active.next())!==-1?this.active.nextAll(".ui-menu-item"):r,r.length||(s=String.fromCharCode(t.keyCode),u=new RegExp("^"+n(s),"i"),r=this.activeMenu.children(".ui-menu-item").filter(function(){return u.test(e(this).children("a").text())})),r.length?(this.focus(t,r),r.length>1?(this.previousFilter=s,this.filterTimer=this._delay(function(){delete this.previousFilter},1e3)):delete this.previousFilter):delete this.previousFilter}a&&t.preventDefault()},_activate:function(e){this.active.is(".ui-state-disabled")||(this.active.children("a[aria-haspopup='true']").length?this.expand(e):this.select(e))},refresh:function(){var t,n=this.options.icons.submenu,r=this.element.find(this.options.menus);r.filter(":not(.ui-menu)").addClass("ui-menu ui-widget ui-widget-content ui-corner-all").hide().attr({role:this.options.role,"aria-hidden":"true","aria-expanded":"false"}).each(function(){var t=e(this),r=t.prev("a"),i=e("<span>").addClass("ui-menu-icon ui-icon "+n).data("ui-menu-submenu-carat",!0);r.attr("aria-haspopup","true").prepend(i),t.attr("aria-labelledby",r.attr("id"))}),t=r.add(this.element),t.children(":not(.ui-menu-item):has(a)").addClass("ui-menu-item").attr("role","presentation").children("a").uniqueId().addClass("ui-corner-all").attr({tabIndex:-1,role:this._itemRole()}),t.children(":not(.ui-menu-item)").each(function(){var t=e(this);/[^\-—–\s]/.test(t.text())||t.addClass("ui-widget-content ui-menu-divider")}),t.children(".ui-state-disabled").attr("aria-disabled","true"),this.active&&!e.contains(this.element[0],this.active[0])&&this.blur()},_itemRole:function(){return{menu:"menuitem",listbox:"option"}[this.options.role]},_setOption:function(e,t){e==="icons"&&this.element.find(".ui-menu-icon").removeClass(this.options.icons.submenu).addClass(t.submenu),this._super(e,t)},focus:function(e,t){var n,r;this.blur(e,e&&e.type==="focus"),this._scrollIntoView(t),this.active=t.first(),r=this.active.children("a").addClass("ui-state-focus"),this.options.role&&this.element.attr("aria-activedescendant",r.attr("id")),this.active.parent().closest(".ui-menu-item").children("a:first").addClass("ui-state-active"),e&&e.type==="keydown"?this._close():this.timer=this._delay(function(){this._close()},this.delay),n=t.children(".ui-menu"),n.length&&/^mouse/.test(e.type)&&this._startOpening(n),this.activeMenu=t.parent(),this._trigger("focus",e,{item:t})},_scrollIntoView:function(t){var n,r,i,s,o,u;this._hasScroll()&&(n=parseFloat(e.css(this.activeMenu[0],"borderTopWidth"))||0,r=parseFloat(e.css(this.activeMenu[0],"paddingTop"))||0,i=t.offset().top-this.activeMenu.offset().top-n-r,s=this.activeMenu.scrollTop(),o=this.activeMenu.height(),u=t.height(),i<0?this.activeMenu.scrollTop(s+i):i+u>o&&this.activeMenu.scrollTop(s+i-o+u))},blur:function(e,t){t||clearTimeout(this.timer);if(!this.active)return;this.active.children("a").removeClass("ui-state-focus"),this.active=null,this._trigger("blur",e,{item:this.active})},_startOpening:function(e){clearTimeout(this.timer);if(e.attr("aria-hidden")!=="true")return;this.timer=this._delay(function(){this._close(),this._open(e)},this.delay)},_open:function(t){var n=e.extend({of:this.active},this.options.position);clearTimeout(this.timer),this.element.find(".ui-menu").not(t.parents(".ui-menu")).hide().attr("aria-hidden","true"),t.show().removeAttr("aria-hidden").attr("aria-expanded","true").position(n)},collapseAll:function(t,n){clearTimeout(this.timer),this.timer=this._delay(function(){var r=n?this.element:e(t&&t.target).closest(this.element.find(".ui-menu"));r.length||(r=this.element),this._close(r),this.blur(t),this.activeMenu=r},this.delay)},_close:function(e){e||(e=this.active?this.active.parent():this.element),e.find(".ui-menu").hide().attr("aria-hidden","true").attr("aria-expanded","false").end().find("a.ui-state-active").removeClass("ui-state-active")},collapse:function(e){var t=this.active&&this.active.parent().closest(".ui-menu-item",this.element);t&&t.length&&(this._close(),this.focus(e,t))},expand:function(e){var t=this.active&&this.active.children(".ui-menu ").children(".ui-menu-item").first();t&&t.length&&(this._open(t.parent()),this._delay(function(){this.focus(e,t)}))},next:function(e){this._move("next","first",e)},previous:function(e){this._move("prev","last",e)},isFirstItem:function(){return this.active&&!this.active.prevAll(".ui-menu-item").length},isLastItem:function(){return this.active&&!this.active.nextAll(".ui-menu-item").length},_move:function(e,t,n){var r;this.active&&(e==="first"||e==="last"?r=this.active[e==="first"?"prevAll":"nextAll"](".ui-menu-item").eq(-1):r=this.active[e+"All"](".ui-menu-item").eq(0));if(!r||!r.length||!this.active)r=this.activeMenu.children(".ui-menu-item")[t]();this.focus(n,r)},nextPage:function(t){var n,r,i;if(!this.active){this.next(t);return}if(this.isLastItem())return;this._hasScroll()?(r=this.active.offset().top,i=this.element.height(),this.active.nextAll(".ui-menu-item").each(function(){return n=e(this),n.offset().top-r-i<0}),this.focus(t,n)):this.focus(t,this.activeMenu.children(".ui-menu-item")[this.active?"last":"first"]())},previousPage:function(t){var n,r,i;if(!this.active){this.next(t);return}if(this.isFirstItem())return;this._hasScroll()?(r=this.active.offset().top,i=this.element.height(),this.active.prevAll(".ui-menu-item").each(function(){return n=e(this),n.offset().top-r+i>0}),this.focus(t,n)):this.focus(t,this.activeMenu.children(".ui-menu-item").first())},_hasScroll:function(){return this.element.outerHeight()<this.element.prop("scrollHeight")},select:function(t){this.active=this.active||e(t.target).closest(".ui-menu-item");var n={item:this.active};this.active.has(".ui-menu").length||this.collapseAll(t,!0),this._trigger("select",t,n)}})})(jQuery);(function(e,t){e.widget("ui.progressbar",{version:"1.10.0",options:{max:100,value:0,change:null,complete:null},min:0,_create:function(){this.oldValue=this.options.value=this._constrainedValue(),this.element.addClass("ui-progressbar ui-widget ui-widget-content ui-corner-all").attr({role:"progressbar","aria-valuemin":this.min}),this.valueDiv=e("<div class='ui-progressbar-value ui-widget-header ui-corner-left'></div>").appendTo(this.element),this._refreshValue()},_destroy:function(){this.element.removeClass("ui-progressbar ui-widget ui-widget-content ui-corner-all").removeAttr("role").removeAttr("aria-valuemin").removeAttr("aria-valuemax").removeAttr("aria-valuenow"),this.valueDiv.remove()},value:function(e){if(e===t)return this.options.value;this.options.value=this._constrainedValue(e),this._refreshValue()},_constrainedValue:function(e){return e===t&&(e=this.options.value),this.indeterminate=e===!1,typeof e!="number"&&(e=0),this.indeterminate?!1:Math.min(this.options.max,Math.max(this.min,e))},_setOptions:function(e){var t=e.value;delete e.value,this._super(e),this.options.value=this._constrainedValue(t),this._refreshValue()},_setOption:function(e,t){e==="max"&&(t=Math.max(this.min,t)),this._super(e,t)},_percentage:function(){return this.indeterminate?100:100*(this.options.value-this.min)/(this.options.max-this.min)},_refreshValue:function(){var t=this.options.value,n=this._percentage();this.valueDiv.toggle(this.indeterminate||t>this.min).toggleClass("ui-corner-right",t===this.options.max).width(n.toFixed(0)+"%"),this.element.toggleClass("ui-progressbar-indeterminate",this.indeterminate),this.indeterminate?(this.element.removeAttr("aria-valuenow"),this.overlayDiv||(this.overlayDiv=e("<div class='ui-progressbar-overlay'></div>").appendTo(this.valueDiv))):(this.element.attr({"aria-valuemax":this.options.max,"aria-valuenow":t}),this.overlayDiv&&(this.overlayDiv.remove(),this.overlayDiv=null)),this.oldValue!==t&&(this.oldValue=t,this._trigger("change")),t===this.options.max&&this._trigger("complete")}})})(jQuery);(function(e,t){var n=5;e.widget("ui.slider",e.ui.mouse,{version:"1.10.0",widgetEventPrefix:"slide",options:{animate:!1,distance:0,max:100,min:0,orientation:"horizontal",range:!1,step:1,value:0,values:null,change:null,slide:null,start:null,stop:null},_create:function(){var t,n,r=this.options,i=this.element.find(".ui-slider-handle").addClass("ui-state-default ui-corner-all"),s="<a class='ui-slider-handle ui-state-default ui-corner-all' href='#'></a>",o=[];this._keySliding=!1,this._mouseSliding=!1,this._animateOff=!0,this._handleIndex=null,this._detectOrientation(),this._mouseInit(),this.element.addClass("ui-slider ui-slider-"+this.orientation+" ui-widget"+" ui-widget-content"+" ui-corner-all"),this.range=e([]),r.range&&(r.range===!0&&(r.values?r.values.length&&r.values.length!==2?r.values=[r.values[0],r.values[0]]:e.isArray(r.values)&&(r.values=r.values.slice(0)):r.values=[this._valueMin(),this._valueMin()]),this.range=e("<div></div>").appendTo(this.element).addClass("ui-slider-range ui-widget-header"+(r.range==="min"||r.range==="max"?" ui-slider-range-"+r.range:""))),n=r.values&&r.values.length||1;for(t=i.length;t<n;t++)o.push(s);this.handles=i.add(e(o.join("")).appendTo(this.element)),this.handle=this.handles.eq(0),this.handles.add(this.range).filter("a").click(function(e){e.preventDefault()}).mouseenter(function(){r.disabled||e(this).addClass("ui-state-hover")}).mouseleave(function(){e(this).removeClass("ui-state-hover")}).focus(function(){r.disabled?e(this).blur():(e(".ui-slider .ui-state-focus").removeClass("ui-state-focus"),e(this).addClass("ui-state-focus"))}).blur(function(){e(this).removeClass("ui-state-focus")}),this.handles.each(function(t){e(this).data("ui-slider-handle-index",t)}),this._setOption("disabled",r.disabled),this._on(this.handles,this._handleEvents),this._refreshValue(),this._animateOff=!1},_destroy:function(){this.handles.remove(),this.range.remove(),this.element.removeClass("ui-slider ui-slider-horizontal ui-slider-vertical ui-widget ui-widget-content ui-corner-all"),this._mouseDestroy()},_mouseCapture:function(t){var n,r,i,s,o,u,a,f,l=this,c=this.options;return c.disabled?!1:(this.elementSize={width:this.element.outerWidth(),height:this.element.outerHeight()},this.elementOffset=this.element.offset(),n={x:t.pageX,y:t.pageY},r=this._normValueFromMouse(n),i=this._valueMax()-this._valueMin()+1,this.handles.each(function(t){var n=Math.abs(r-l.values(t));if(i>n||i===n&&(t===l._lastChangedValue||l.values(t)===c.min))i=n,s=e(this),o=t}),u=this._start(t,o),u===!1?!1:(this._mouseSliding=!0,this._handleIndex=o,s.addClass("ui-state-active").focus(),a=s.offset(),f=!e(t.target).parents().addBack().is(".ui-slider-handle"),this._clickOffset=f?{left:0,top:0}:{left:t.pageX-a.left-s.width()/2,top:t.pageY-a.top-s.height()/2-(parseInt(s.css("borderTopWidth"),10)||0)-(parseInt(s.css("borderBottomWidth"),10)||0)+(parseInt(s.css("marginTop"),10)||0)},this.handles.hasClass("ui-state-hover")||this._slide(t,o,r),this._animateOff=!0,!0))},_mouseStart:function(){return!0},_mouseDrag:function(e){var t={x:e.pageX,y:e.pageY},n=this._normValueFromMouse(t);return this._slide(e,this._handleIndex,n),!1},_mouseStop:function(e){return this.handles.removeClass("ui-state-active"),this._mouseSliding=!1,this._stop(e,this._handleIndex),this._change(e,this._handleIndex),this._handleIndex=null,this._clickOffset=null,this._animateOff=!1,!1},_detectOrientation:function(){this.orientation=this.options.orientation==="vertical"?"vertical":"horizontal"},_normValueFromMouse:function(e){var t,n,r,i,s;return this.orientation==="horizontal"?(t=this.elementSize.width,n=e.x-this.elementOffset.left-(this._clickOffset?this._clickOffset.left:0)):(t=this.elementSize.height,n=e.y-this.elementOffset.top-(this._clickOffset?this._clickOffset.top:0)),r=n/t,r>1&&(r=1),r<0&&(r=0),this.orientation==="vertical"&&(r=1-r),i=this._valueMax()-this._valueMin(),s=this._valueMin()+r*i,this._trimAlignValue(s)},_start:function(e,t){var n={handle:this.handles[t],value:this.value()};return this.options.values&&this.options.values.length&&(n.value=this.values(t),n.values=this.values()),this._trigger("start",e,n)},_slide:function(e,t,n){var r,i,s;this.options.values&&this.options.values.length?(r=this.values(t?0:1),this.options.values.length===2&&this.options.range===!0&&(t===0&&n>r||t===1&&n<r)&&(n=r),n!==this.values(t)&&(i=this.values(),i[t]=n,s=this._trigger("slide",e,{handle:this.handles[t],value:n,values:i}),r=this.values(t?0:1),s!==!1&&this.values(t,n,!0))):n!==this.value()&&(s=this._trigger("slide",e,{handle:this.handles[t],value:n}),s!==!1&&this.value(n))},_stop:function(e,t){var n={handle:this.handles[t],value:this.value()};this.options.values&&this.options.values.length&&(n.value=this.values(t),n.values=this.values()),this._trigger("stop",e,n)},_change:function(e,t){if(!this._keySliding&&!this._mouseSliding){var n={handle:this.handles[t],value:this.value()};this.options.values&&this.options.values.length&&(n.value=this.values(t),n.values=this.values()),this._lastChangedValue=t,this._trigger("change",e,n)}},value:function(e){if(arguments.length){this.options.value=this._trimAlignValue(e),this._refreshValue(),this._change(null,0);return}return this._value()},values:function(t,n){var r,i,s;if(arguments.length>1){this.options.values[t]=this._trimAlignValue(n),this._refreshValue(),this._change(null,t);return}if(!arguments.length)return this._values();if(!e.isArray(arguments[0]))return this.options.values&&this.options.values.length?this._values(t):this.value();r=this.options.values,i=arguments[0];for(s=0;s<r.length;s+=1)r[s]=this._trimAlignValue(i[s]),this._change(null,s);this._refreshValue()},_setOption:function(t,n){var r,i=0;e.isArray(this.options.values)&&(i=this.options.values.length),e.Widget.prototype._setOption.apply(this,arguments);switch(t){case"disabled":n?(this.handles.filter(".ui-state-focus").blur(),this.handles.removeClass("ui-state-hover"),this.handles.prop("disabled",!0)):this.handles.prop("disabled",!1);break;case"orientation":this._detectOrientation(),this.element.removeClass("ui-slider-horizontal ui-slider-vertical").addClass("ui-slider-"+this.orientation),this._refreshValue();break;case"value":this._animateOff=!0,this._refreshValue(),this._change(null,0),this._animateOff=!1;break;case"values":this._animateOff=!0,this._refreshValue();for(r=0;r<i;r+=1)this._change(null,r);this._animateOff=!1;break;case"min":case"max":this._animateOff=!0,this._refreshValue(),this._animateOff=!1}},_value:function(){var e=this.options.value;return e=this._trimAlignValue(e),e},_values:function(e){var t,n,r;if(arguments.length)return t=this.options.values[e],t=this._trimAlignValue(t),t;n=this.options.values.slice();for(r=0;r<n.length;r+=1)n[r]=this._trimAlignValue(n[r]);return n},_trimAlignValue:function(e){if(e<=this._valueMin())return this._valueMin();if(e>=this._valueMax())return this._valueMax();var t=this.options.step>0?this.options.step:1,n=(e-this._valueMin())%t,r=e-n;return Math.abs(n)*2>=t&&(r+=n>0?t:-t),parseFloat(r.toFixed(5))},_valueMin:function(){return this.options.min},_valueMax:function(){return this.options.max},_refreshValue:function(){var t,n,r,i,s,o=this.options.range,u=this.options,a=this,f=this._animateOff?!1:u.animate,l={};this.options.values&&this.options.values.length?this.handles.each(function(r){n=(a.values(r)-a._valueMin())/(a._valueMax()-a._valueMin())*100,l[a.orientation==="horizontal"?"left":"bottom"]=n+"%",e(this).stop(1,1)[f?"animate":"css"](l,u.animate),a.options.range===!0&&(a.orientation==="horizontal"?(r===0&&a.range.stop(1,1)[f?"animate":"css"]({left:n+"%"},u.animate),r===1&&a.range[f?"animate":"css"]({width:n-t+"%"},{queue:!1,duration:u.animate})):(r===0&&a.range.stop(1,1)[f?"animate":"css"]({bottom:n+"%"},u.animate),r===1&&a.range[f?"animate":"css"]({height:n-t+"%"},{queue:!1,duration:u.animate}))),t=n}):(r=this.value(),i=this._valueMin(),s=this._valueMax(),n=s!==i?(r-i)/(s-i)*100:0,l[this.orientation==="horizontal"?"left":"bottom"]=n+"%",this.handle.stop(1,1)[f?"animate":"css"](l,u.animate),o==="min"&&this.orientation==="horizontal"&&this.range.stop(1,1)[f?"animate":"css"]({width:n+"%"},u.animate),o==="max"&&this.orientation==="horizontal"&&this.range[f?"animate":"css"]({width:100-n+"%"},{queue:!1,duration:u.animate}),o==="min"&&this.orientation==="vertical"&&this.range.stop(1,1)[f?"animate":"css"]({height:n+"%"},u.animate),o==="max"&&this.orientation==="vertical"&&this.range[f?"animate":"css"]({height:100-n+"%"},{queue:!1,duration:u.animate}))},_handleEvents:{keydown:function(t){var r,i,s,o,u=e(t.target).data("ui-slider-handle-index");switch(t.keyCode){case e.ui.keyCode.HOME:case e.ui.keyCode.END:case e.ui.keyCode.PAGE_UP:case e.ui.keyCode.PAGE_DOWN:case e.ui.keyCode.UP:case e.ui.keyCode.RIGHT:case e.ui.keyCode.DOWN:case e.ui.keyCode.LEFT:t.preventDefault();if(!this._keySliding){this._keySliding=!0,e(t.target).addClass("ui-state-active"),r=this._start(t,u);if(r===!1)return}}o=this.options.step,this.options.values&&this.options.values.length?i=s=this.values(u):i=s=this.value();switch(t.keyCode){case e.ui.keyCode.HOME:s=this._valueMin();break;case e.ui.keyCode.END:s=this._valueMax();break;case e.ui.keyCode.PAGE_UP:s=this._trimAlignValue(i+(this._valueMax()-this._valueMin())/n);break;case e.ui.keyCode.PAGE_DOWN:s=this._trimAlignValue(i-(this._valueMax()-this._valueMin())/n);break;case e.ui.keyCode.UP:case e.ui.keyCode.RIGHT:if(i===this._valueMax())return;s=this._trimAlignValue(i+o);break;case e.ui.keyCode.DOWN:case e.ui.keyCode.LEFT:if(i===this._valueMin())return;s=this._trimAlignValue(i-o)}this._slide(t,u,s)},keyup:function(t){var n=e(t.target).data("ui-slider-handle-index");this._keySliding&&(this._keySliding=!1,this._stop(t,n),this._change(t,n),e(t.target).removeClass("ui-state-active"))}}})})(jQuery);(function(e){function t(e){return function(){var t=this.element.val();e.apply(this,arguments),this._refresh(),t!==this.element.val()&&this._trigger("change")}}e.widget("ui.spinner",{version:"1.10.0",defaultElement:"<input>",widgetEventPrefix:"spin",options:{culture:null,icons:{down:"ui-icon-triangle-1-s",up:"ui-icon-triangle-1-n"},incremental:!0,max:null,min:null,numberFormat:null,page:10,step:1,change:null,spin:null,start:null,stop:null},_create:function(){this._setOption("max",this.options.max),this._setOption("min",this.options.min),this._setOption("step",this.options.step),this._value(this.element.val(),!0),this._draw(),this._on(this._events),this._refresh(),this._on(this.window,{beforeunload:function(){this.element.removeAttr("autocomplete")}})},_getCreateOptions:function(){var t={},n=this.element;return e.each(["min","max","step"],function(e,r){var i=n.attr(r);i!==undefined&&i.length&&(t[r]=i)}),t},_events:{keydown:function(e){this._start(e)&&this._keydown(e)&&e.preventDefault()},keyup:"_stop",focus:function(){this.previous=this.element.val()},blur:function(e){if(this.cancelBlur){delete this.cancelBlur;return}this._refresh(),this.previous!==this.element.val()&&this._trigger("change",e)},mousewheel:function(e,t){if(!t)return;if(!this.spinning&&!this._start(e))return!1;this._spin((t>0?1:-1)*this.options.step,e),clearTimeout(this.mousewheelTimer),this.mousewheelTimer=this._delay(function(){this.spinning&&this._stop(e)},100),e.preventDefault()},"mousedown .ui-spinner-button":function(t){function n(){var e=this.element[0]===this.document[0].activeElement;e||(this.element.focus(),this.previous=r,this._delay(function(){this.previous=r}))}var r;r=this.element[0]===this.document[0].activeElement?this.previous:this.element.val(),t.preventDefault(),n.call(this),this.cancelBlur=!0,this._delay(function(){delete this.cancelBlur,n.call(this)});if(this._start(t)===!1)return;this._repeat(null,e(t.currentTarget).hasClass("ui-spinner-up")?1:-1,t)},"mouseup .ui-spinner-button":"_stop","mouseenter .ui-spinner-button":function(t){if(!e(t.currentTarget).hasClass("ui-state-active"))return;if(this._start(t)===!1)return!1;this._repeat(null,e(t.currentTarget).hasClass("ui-spinner-up")?1:-1,t)},"mouseleave .ui-spinner-button":"_stop"},_draw:function(){var e=this.uiSpinner=this.element.addClass("ui-spinner-input").attr("autocomplete","off").wrap(this._uiSpinnerHtml()).parent().append(this._buttonHtml());this.element.attr("role","spinbutton"),this.buttons=e.find(".ui-spinner-button").attr("tabIndex",-1).button().removeClass("ui-corner-all"),this.buttons.height()>Math.ceil(e.height()*.5)&&e.height()>0&&e.height(e.height()),this.options.disabled&&this.disable()},_keydown:function(t){var n=this.options,r=e.ui.keyCode;switch(t.keyCode){case r.UP:return this._repeat(null,1,t),!0;case r.DOWN:return this._repeat(null,-1,t),!0;case r.PAGE_UP:return this._repeat(null,n.page,t),!0;case r.PAGE_DOWN:return this._repeat(null,-n.page,t),!0}return!1},_uiSpinnerHtml:function(){return"<span class='ui-spinner ui-widget ui-widget-content ui-corner-all'></span>"},_buttonHtml:function(){return"<a class='ui-spinner-button ui-spinner-up ui-corner-tr'><span class='ui-icon "+this.options.icons.up+"'>▲</span>"+"</a>"+"<a class='ui-spinner-button ui-spinner-down ui-corner-br'>"+"<span class='ui-icon "+this.options.icons.down+"'>▼</span>"+"</a>"},_start:function(e){return!this.spinning&&this._trigger("start",e)===!1?!1:(this.counter||(this.counter=1),this.spinning=!0,!0)},_repeat:function(e,t,n){e=e||500,clearTimeout(this.timer),this.timer=this._delay(function(){this._repeat(40,t,n)},e),this._spin(t*this.options.step,n)},_spin:function(e,t){var n=this.value()||0;this.counter||(this.counter=1),n=this._adjustValue(n+e*this._increment(this.counter));if(!this.spinning||this._trigger("spin",t,{value:n})!==!1)this._value(n),this.counter++},_increment:function(t){var n=this.options.incremental;return n?e.isFunction(n)?n(t):Math.floor(t*t*t/5e4-t*t/500+17*t/200+1):1},_precision:function(){var e=this._precisionOf(this.options.step);return this.options.min!==null&&(e=Math.max(e,this._precisionOf(this.options.min))),e},_precisionOf:function(e){var t=e.toString(),n=t.indexOf(".");return n===-1?0:t.length-n-1},_adjustValue:function(e){var t,n,r=this.options;return t=r.min!==null?r.min:0,n=e-t,n=Math.round(n/r.step)*r.step,e=t+n,e=parseFloat(e.toFixed(this._precision())),r.max!==null&&e>r.max?r.max:r.min!==null&&e<r.min?r.min:e},_stop:function(e){if(!this.spinning)return;clearTimeout(this.timer),clearTimeout(this.mousewheelTimer),this.counter=0,this.spinning=!1,this._trigger("stop",e)},_setOption:function(e,t){if(e==="culture"||e==="numberFormat"){var n=this._parse(this.element.val());this.options[e]=t,this.element.val(this._format(n));return}(e==="max"||e==="min"||e==="step")&&typeof t=="string"&&(t=this._parse(t)),e==="icons"&&(this.buttons.first().find(".ui-icon").removeClass(this.options.icons.up).addClass(t.up),this.buttons.last().find(".ui-icon").removeClass(this.options.icons.down).addClass(t.down)),this._super(e,t),e==="disabled"&&(t?(this.element.prop("disabled",!0),this.buttons.button("disable")):(this.element.prop("disabled",!1),this.buttons.button("enable")))},_setOptions:t(function(e){this._super(e),this._value(this.element.val())}),_parse:function(e){return typeof e=="string"&&e!==""&&(e=window.Globalize&&this.options.numberFormat?Globalize.parseFloat(e,10,this.options.culture):+e),e===""||isNaN(e)?null:e},_format:function(e){return e===""?"":window.Globalize&&this.options.numberFormat?Globalize.format(e,this.options.numberFormat,this.options.culture):e},_refresh:function(){this.element.attr({"aria-valuemin":this.options.min,"aria-valuemax":this.options.max,"aria-valuenow":this._parse(this.element.val())})},_value:function(e,t){var n;e!==""&&(n=this._parse(e),n!==null&&(t||(n=this._adjustValue(n)),e=this._format(n))),this.element.val(e),this._refresh()},_destroy:function(){this.element.removeClass("ui-spinner-input").prop("disabled",!1).removeAttr("autocomplete").removeAttr("role").removeAttr("aria-valuemin").removeAttr("aria-valuemax").removeAttr("aria-valuenow"),this.uiSpinner.replaceWith(this.element)},stepUp:t(function(e){this._stepUp(e)}),_stepUp:function(e){this._start()&&(this._spin((e||1)*this.options.step),this._stop())},stepDown:t(function(e){this._stepDown(e)}),_stepDown:function(e){this._start()&&(this._spin((e||1)*-this.options.step),this._stop())},pageUp:t(function(e){this._stepUp((e||1)*this.options.page)}),pageDown:t(function(e){this._stepDown((e||1)*this.options.page)}),value:function(e){if(!arguments.length)return this._parse(this.element.val());t(this._value).call(this,e)},widget:function(){return this.uiSpinner}})})(jQuery);(function(e,t){function n(){return++i}function r(e){return e.hash.length>1&&decodeURIComponent(e.href.replace(s,""))===decodeURIComponent(location.href.replace(s,""))}var i=0,s=/#.*$/;e.widget("ui.tabs",{version:"1.10.0",delay:300,options:{active:null,collapsible:!1,event:"click",heightStyle:"content",hide:null,show:null,activate:null,beforeActivate:null,beforeLoad:null,load:null},_create:function(){var t=this,n=this.options;this.running=!1,this.element.addClass("ui-tabs ui-widget ui-widget-content ui-corner-all").toggleClass("ui-tabs-collapsible",n.collapsible).delegate(".ui-tabs-nav > li","mousedown"+this.eventNamespace,function(t){e(this).is(".ui-state-disabled")&&t.preventDefault()}).delegate(".ui-tabs-anchor","focus"+this.eventNamespace,function(){e(this).closest("li").is(".ui-state-disabled")&&this.blur()}),this._processTabs(),n.active=this._initialActive(),e.isArray(n.disabled)&&(n.disabled=e.unique(n.disabled.concat(e.map(this.tabs.filter(".ui-state-disabled"),function(e){return t.tabs.index(e)}))).sort()),this.options.active!==!1&&this.anchors.length?this.active=this._findActive(n.active):this.active=e(),this._refresh(),this.active.length&&this.load(n.active)},_initialActive:function(){var t=this.options.active,n=this.options.collapsible,r=location.hash.substring(1);if(t===null){r&&this.tabs.each(function(n,i){if(e(i).attr("aria-controls")===r)return t=n,!1}),t===null&&(t=this.tabs.index(this.tabs.filter(".ui-tabs-active")));if(t===null||t===-1)t=this.tabs.length?0:!1}return t!==!1&&(t=this.tabs.index(this.tabs.eq(t)),t===-1&&(t=n?!1:0)),!n&&t===!1&&this.anchors.length&&(t=0),t},_getCreateEventData:function(){return{tab:this.active,panel:this.active.length?this._getPanelForTab(this.active):e()}},_tabKeydown:function(t){var n=e(this.document[0].activeElement).closest("li"),r=this.tabs.index(n),i=!0;if(this._handlePageNav(t))return;switch(t.keyCode){case e.ui.keyCode.RIGHT:case e.ui.keyCode.DOWN:r++;break;case e.ui.keyCode.UP:case e.ui.keyCode.LEFT:i=!1,r--;break;case e.ui.keyCode.END:r=this.anchors.length-1;break;case e.ui.keyCode.HOME:r=0;break;case e.ui.keyCode.SPACE:t.preventDefault(),clearTimeout(this.activating),this._activate(r);return;case e.ui.keyCode.ENTER:t.preventDefault(),clearTimeout(this.activating),this._activate(r===this.options.active?!1:r);return;default:return}t.preventDefault(),clearTimeout(this.activating),r=this._focusNextTab(r,i),t.ctrlKey||(n.attr("aria-selected","false"),this.tabs.eq(r).attr("aria-selected","true"),this.activating=this._delay(function(){this.option("active",r)},this.delay))},_panelKeydown:function(t){if(this._handlePageNav(t))return;t.ctrlKey&&t.keyCode===e.ui.keyCode.UP&&(t.preventDefault(),this.active.focus())},_handlePageNav:function(t){if(t.altKey&&t.keyCode===e.ui.keyCode.PAGE_UP)return this._activate(this._focusNextTab(this.options.active-1,!1)),!0;if(t.altKey&&t.keyCode===e.ui.keyCode.PAGE_DOWN)return this._activate(this._focusNextTab(this.options.active+1,!0)),!0},_findNextTab:function(t,n){function r(){return t>i&&(t=0),t<0&&(t=i),t}var i=this.tabs.length-1;while(e.inArray(r(),this.options.disabled)!==-1)t=n?t+1:t-1;return t},_focusNextTab:function(e,t){return e=this._findNextTab(e,t),this.tabs.eq(e).focus(),e},_setOption:function(e,t){if(e==="active"){this._activate(t);return}if(e==="disabled"){this._setupDisabled(t);return}this._super(e,t),e==="collapsible"&&(this.element.toggleClass("ui-tabs-collapsible",t),!t&&this.options.active===!1&&this._activate(0)),e==="event"&&this._setupEvents(t),e==="heightStyle"&&this._setupHeightStyle(t)},_tabId:function(e){return e.attr("aria-controls")||"ui-tabs-"+n()},_sanitizeSelector:function(e){return e?e.replace(/[!"$%&'()*+,.\/:;<=>?@\[\]\^`{|}~]/g,"\\$&"):""},refresh:function(){var t=this.options,n=this.tablist.children(":has(a[href])");t.disabled=e.map(n.filter(".ui-state-disabled"),function(e){return n.index(e)}),this._processTabs(),t.active===!1||!this.anchors.length?(t.active=!1,this.active=e()):this.active.length&&!e.contains(this.tablist[0],this.active[0])?this.tabs.length===t.disabled.length?(t.active=!1,this.active=e()):this._activate(this._findNextTab(Math.max(0,t.active-1),!1)):t.active=this.tabs.index(this.active),this._refresh()},_refresh:function(){this._setupDisabled(this.options.disabled),this._setupEvents(this.options.event),this._setupHeightStyle(this.options.heightStyle),this.tabs.not(this.active).attr({"aria-selected":"false",tabIndex:-1}),this.panels.not(this._getPanelForTab(this.active)).hide().attr({"aria-expanded":"false","aria-hidden":"true"}),this.active.length?(this.active.addClass("ui-tabs-active ui-state-active").attr({"aria-selected":"true",tabIndex:0}),this._getPanelForTab(this.active).show().attr({"aria-expanded":"true","aria-hidden":"false"})):this.tabs.eq(0).attr("tabIndex",0)},_processTabs:function(){var t=this;this.tablist=this._getList().addClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all").attr("role","tablist"),this.tabs=this.tablist.find("> li:has(a[href])").addClass("ui-state-default ui-corner-top").attr({role:"tab",tabIndex:-1}),this.anchors=this.tabs.map(function(){return e("a",this)[0]}).addClass("ui-tabs-anchor").attr({role:"presentation",tabIndex:-1}),this.panels=e(),this.anchors.each(function(n,i){var s,o,u,a=e(i).uniqueId().attr("id"),f=e(i).closest("li"),l=f.attr("aria-controls");r(i)?(s=i.hash,o=t.element.find(t._sanitizeSelector(s))):(u=t._tabId(f),s="#"+u,o=t.element.find(s),o.length||(o=t._createPanel(u),o.insertAfter(t.panels[n-1]||t.tablist)),o.attr("aria-live","polite")),o.length&&(t.panels=t.panels.add(o)),l&&f.data("ui-tabs-aria-controls",l),f.attr({"aria-controls":s.substring(1),"aria-labelledby":a}),o.attr("aria-labelledby",a)}),this.panels.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").attr("role","tabpanel")},_getList:function(){return this.element.find("ol,ul").eq(0)},_createPanel:function(t){return e("<div>").attr("id",t).addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").data("ui-tabs-destroy",!0)},_setupDisabled:function(t){e.isArray(t)&&(t.length?t.length===this.anchors.length&&(t=!0):t=!1);for(var n=0,r;r=this.tabs[n];n++)t===!0||e.inArray(n,t)!==-1?e(r).addClass("ui-state-disabled").attr("aria-disabled","true"):e(r).removeClass("ui-state-disabled").removeAttr("aria-disabled");this.options.disabled=t},_setupEvents:function(t){var n={click:function(e){e.preventDefault()}};t&&e.each(t.split(" "),function(e,t){n[t]="_eventHandler"}),this._off(this.anchors.add(this.tabs).add(this.panels)),this._on(this.anchors,n),this._on(this.tabs,{keydown:"_tabKeydown"}),this._on(this.panels,{keydown:"_panelKeydown"}),this._focusable(this.tabs),this._hoverable(this.tabs)},_setupHeightStyle:function(t){var n,r=this.element.parent();t==="fill"?(n=r.height(),n-=this.element.outerHeight()-this.element.height(),this.element.siblings(":visible").each(function(){var t=e(this),r=t.css("position");if(r==="absolute"||r==="fixed")return;n-=t.outerHeight(!0)}),this.element.children().not(this.panels).each(function(){n-=e(this).outerHeight(!0)}),this.panels.each(function(){e(this).height(Math.max(0,n-e(this).innerHeight()+e(this).height()))}).css("overflow","auto")):t==="auto"&&(n=0,this.panels.each(function(){n=Math.max(n,e(this).height("").height())}).height(n))},_eventHandler:function(t){var n=this.options,r=this.active,i=e(t.currentTarget),s=i.closest("li"),o=s[0]===r[0],u=o&&n.collapsible,a=u?e():this._getPanelForTab(s),f=r.length?this._getPanelForTab(r):e(),l={oldTab:r,oldPanel:f,newTab:u?e():s,newPanel:a};t.preventDefault();if(s.hasClass("ui-state-disabled")||s.hasClass("ui-tabs-loading")||this.running||o&&!n.collapsible||this._trigger("beforeActivate",t,l)===!1)return;n.active=u?!1:this.tabs.index(s),this.active=o?e():s,this.xhr&&this.xhr.abort(),!f.length&&!a.length&&e.error("jQuery UI Tabs: Mismatching fragment identifier."),a.length&&this.load(this.tabs.index(s),t),this._toggle(t,l)},_toggle:function(t,n){function r(){s.running=!1,s._trigger("activate",t,n)}function i(){n.newTab.closest("li").addClass("ui-tabs-active ui-state-active"),o.length&&s.options.show?s._show(o,s.options.show,r):(o.show(),r())}var s=this,o=n.newPanel,u=n.oldPanel;this.running=!0,u.length&&this.options.hide?this._hide(u,this.options.hide,function(){n.oldTab.closest("li").removeClass("ui-tabs-active ui-state-active"),i()}):(n.oldTab.closest("li").removeClass("ui-tabs-active ui-state-active"),u.hide(),i()),u.attr({"aria-expanded":"false","aria-hidden":"true"}),n.oldTab.attr("aria-selected","false"),o.length&&u.length?n.oldTab.attr("tabIndex",-1):o.length&&this.tabs.filter(function(){return e(this).attr("tabIndex")===0}).attr("tabIndex",-1),o.attr({"aria-expanded":"true","aria-hidden":"false"}),n.newTab.attr({"aria-selected":"true",tabIndex:0})},_activate:function(t){var n,r=this._findActive(t);if(r[0]===this.active[0])return;r.length||(r=this.active),n=r.find(".ui-tabs-anchor")[0],this._eventHandler({target:n,currentTarget:n,preventDefault:e.noop})},_findActive:function(t){return t===!1?e():this.tabs.eq(t)},_getIndex:function(e){return typeof e=="string"&&(e=this.anchors.index(this.anchors.filter("[href$='"+e+"']"))),e},_destroy:function(){this.xhr&&this.xhr.abort(),this.element.removeClass("ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible"),this.tablist.removeClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all").removeAttr("role"),this.anchors.removeClass("ui-tabs-anchor").removeAttr("role").removeAttr("tabIndex").removeUniqueId(),this.tabs.add(this.panels).each(function(){e.data(this,"ui-tabs-destroy")?e(this).remove():e(this).removeClass("ui-state-default ui-state-active ui-state-disabled ui-corner-top ui-corner-bottom ui-widget-content ui-tabs-active ui-tabs-panel").removeAttr("tabIndex").removeAttr("aria-live").removeAttr("aria-busy").removeAttr("aria-selected").removeAttr("aria-labelledby").removeAttr("aria-hidden").removeAttr("aria-expanded").removeAttr("role")}),this.tabs.each(function(){var t=e(this),n=t.data("ui-tabs-aria-controls");n?t.attr("aria-controls",n).removeData("ui-tabs-aria-controls"):t.removeAttr("aria-controls")}),this.panels.show(),this.options.heightStyle!=="content"&&this.panels.css("height","")},enable:function(n){var r=this.options.disabled;if(r===!1)return;n===t?r=!1:(n=this._getIndex(n),e.isArray(r)?r=e.map(r,function(e){return e!==n?e:null}):r=e.map(this.tabs,function(e,t){return t!==n?t:null})),this._setupDisabled(r)},disable:function(n){var r=this.options.disabled;if(r===!0)return;if(n===t)r=!0;else{n=this._getIndex(n);if(e.inArray(n,r)!==-1)return;e.isArray(r)?r=e.merge([n],r).sort():r=[n]}this._setupDisabled(r)},load:function(t,n){t=this._getIndex(t);var i=this,s=this.tabs.eq(t),o=s.find(".ui-tabs-anchor"),u=this._getPanelForTab(s),a={tab:s,panel:u};if(r(o[0]))return;this.xhr=e.ajax(this._ajaxSettings(o,n,a)),this.xhr&&this.xhr.statusText!=="canceled"&&(s.addClass("ui-tabs-loading"),u.attr("aria-busy","true"),this.xhr.success(function(e){setTimeout(function(){u.html(e),i._trigger("load",n,a)},1)}).complete(function(e,t){setTimeout(function(){t==="abort"&&i.panels.stop(!1,!0),s.removeClass("ui-tabs-loading"),u.removeAttr("aria-busy"),e===i.xhr&&delete i.xhr},1)}))},_ajaxSettings:function(t,n,r){var i=this;return{url:t.attr("href"),beforeSend:function(t,s){return i._trigger("beforeLoad",n,e.extend({jqXHR:t,ajaxSettings:s},r))}}},_getPanelForTab:function(t){var n=e(t).attr("aria-controls");return this.element.find(this._sanitizeSelector("#"+n))}})})(jQuery);(function(e){function t(t,n){var r=(t.attr("aria-describedby")||"").split(/\s+/);r.push(n),t.data("ui-tooltip-id",n).attr("aria-describedby",e.trim(r.join(" ")))}function n(t){var n=t.data("ui-tooltip-id"),r=(t.attr("aria-describedby")||"").split(/\s+/),i=e.inArray(n,r);i!==-1&&r.splice(i,1),t.removeData("ui-tooltip-id"),r=e.trim(r.join(" ")),r?t.attr("aria-describedby",r):t.removeAttr("aria-describedby")}var r=0;e.widget("ui.tooltip",{version:"1.10.0",options:{content:function(){var t=e(this).attr("title")||"";return e("<a>").text(t).html()},hide:!0,items:"[title]:not([disabled])",position:{my:"left top+15",at:"left bottom",collision:"flipfit flip"},show:!0,tooltipClass:null,track:!1,close:null,open:null},_create:function(){this._on({mouseover:"open",focusin:"open"}),this.tooltips={},this.parents={},this.options.disabled&&this._disable()},_setOption:function(t,n){var r=this;if(t==="disabled"){this[n?"_disable":"_enable"](),this.options[t]=n;return}this._super(t,n),t==="content"&&e.each(this.tooltips,function(e,t){r._updateContent(t)})},_disable:function(){var t=this;e.each(this.tooltips,function(n,r){var i=e.Event("blur");i.target=i.currentTarget=r[0],t.close(i,!0)}),this.element.find(this.options.items).addBack().each(function(){var t=e(this);t.is("[title]")&&t.data("ui-tooltip-title",t.attr("title")).attr("title","")})},_enable:function(){this.element.find(this.options.items).addBack().each(function(){var t=e(this);t.data("ui-tooltip-title")&&t.attr("title",t.data("ui-tooltip-title"))})},open:function(t){var n=this,r=e(t?t.target:this.element).closest(this.options.items);if(!r.length||r.data("ui-tooltip-id"))return;r.attr("title")&&r.data("ui-tooltip-title",r.attr("title")),r.data("ui-tooltip-open",!0),t&&t.type==="mouseover"&&r.parents().each(function(){var t=e(this),r;t.data("ui-tooltip-open")&&(r=e.Event("blur"),r.target=r.currentTarget=this,n.close(r,!0)),t.attr("title")&&(t.uniqueId(),n.parents[this.id]={element:this,title:t.attr("title")},t.attr("title",""))}),this._updateContent(r,t)},_updateContent:function(e,t){var n,r=this.options.content,i=this,s=t?t.type:null;if(typeof r=="string")return this._open(t,e,r);n=r.call(e[0],function(n){if(!e.data("ui-tooltip-open"))return;i._delay(function(){t&&(t.type=s),this._open(t,e,n)})}),n&&this._open(t,e,n)},_open:function(n,r,i){function s(e){f.of=e;if(o.is(":hidden"))return;o.position(f)}var o,u,a,f=e.extend({},this.options.position);if(!i)return;o=this._find(r);if(o.length){o.find(".ui-tooltip-content").html(i);return}r.is("[title]")&&(n&&n.type==="mouseover"?r.attr("title",""):r.removeAttr("title")),o=this._tooltip(r),t(r,o.attr("id")),o.find(".ui-tooltip-content").html(i),this.options.track&&n&&/^mouse/.test(n.type)?(this._on(this.document,{mousemove:s}),s(n)):o.position(e.extend({of:r},this.options.position)),o.hide(),this._show(o,this.options.show),this.options.show&&this.options.show.delay&&(a=this.delayedShow=setInterval(function(){o.is(":visible")&&(s(f.of),clearInterval(a))},e.fx.interval)),this._trigger("open",n,{tooltip:o}),u={keyup:function(t){if(t.keyCode===e.ui.keyCode.ESCAPE){var n=e.Event(t);n.currentTarget=r[0],this.close(n,!0)}},remove:function(){this._removeTooltip(o)}};if(!n||n.type==="mouseover")u.mouseleave="close";if(!n||n.type==="focusin")u.focusout="close";this._on(!0,r,u)},close:function(t){var r=this,i=e(t?t.currentTarget:this.element),s=this._find(i);if(this.closing)return;clearInterval(this.delayedShow),i.data("ui-tooltip-title")&&i.attr("title",i.data("ui-tooltip-title")),n(i),s.stop(!0),this._hide(s,this.options.hide,function(){r._removeTooltip(e(this))}),i.removeData("ui-tooltip-open"),this._off(i,"mouseleave focusout keyup"),i[0]!==this.element[0]&&this._off(i,"remove"),this._off(this.document,"mousemove"),t&&t.type==="mouseleave"&&e.each(this.parents,function(t,n){e(n.element).attr("title",n.title),delete r.parents[t]}),this.closing=!0,this._trigger("close",t,{tooltip:s}),this.closing=!1},_tooltip:function(t){var n="ui-tooltip-"+r++,i=e("<div>").attr({id:n,role:"tooltip"}).addClass("ui-tooltip ui-widget ui-corner-all ui-widget-content "+(this.options.tooltipClass||""));return e("<div>").addClass("ui-tooltip-content").appendTo(i),i.appendTo(this.document[0].body),this.tooltips[n]=t,i},_find:function(t){var n=t.data("ui-tooltip-id");return n?e("#"+n):e()},_removeTooltip:function(e){e.remove(),delete this.tooltips[e.attr("id")]},_destroy:function(){var t=this;e.each(this.tooltips,function(n,r){var i=e.Event("blur");i.target=i.currentTarget=r[0],t.close(i,!0),e("#"+n).remove(),r.data("ui-tooltip-title")&&(r.attr("title",r.data("ui-tooltip-title")),r.removeData("ui-tooltip-title"))})}})})(jQuery);jQuery.effects||function(e,t){var n="ui-effects-";e.effects={effect:{}},function(e,t){function n(e,t,n){var r=l[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 r(t){var n=a(),r=n._rgba=[];return t=t.toLowerCase(),d(u,function(e,i){var s,o=i.re.exec(t),u=o&&i.parse(o),a=i.space||"rgba";if(u)return s=n[a](u),n[f[a].cache]=s[f[a].cache],r=n._rgba=s._rgba,!1}),r.length?(r.join()==="0,0,0,0"&&e.extend(r,p.transparent),n):p[t]}function i(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 s="backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor",o=/^([\-+])=\s*(\d+\.?\d*)/,u=[{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]]}}],a=e.Color=function(t,n,r,i){return new e.Color.fn.parse(t,n,r,i)},f={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"}}}},l={"byte":{floor:!0,max:255},percent:{max:1},degrees:{mod:360,floor:!0}},c=a.support={},h=e("<p>")[0],p,d=e.each;h.style.cssText="background-color:rgba(1,1,1,.5)",c.rgba=h.style.backgroundColor.indexOf("rgba")>-1,d(f,function(e,t){t.cache="_"+e,t.props.alpha={idx:3,type:"percent",def:1}}),a.fn=e.extend(a.prototype,{parse:function(i,s,o,u){if(i===t)return this._rgba=[null,null,null,null],this;if(i.jquery||i.nodeType)i=e(i).css(s),s=t;var l=this,c=e.type(i),h=this._rgba=[];s!==t&&(i=[i,s,o,u],c="array");if(c==="string")return this.parse(r(i)||p._default);if(c==="array")return d(f.rgba.props,function(e,t){h[t.idx]=n(i[t.idx],t)}),this;if(c==="object")return i instanceof a?d(f,function(e,t){i[t.cache]&&(l[t.cache]=i[t.cache].slice())}):d(f,function(t,r){var s=r.cache;d(r.props,function(e,t){if(!l[s]&&r.to){if(e==="alpha"||i[e]==null)return;l[s]=r.to(l._rgba)}l[s][t.idx]=n(i[e],t,!0)}),l[s]&&e.inArray(null,l[s].slice(0,3))<0&&(l[s][3]=1,r.from&&(l._rgba=r.from(l[s])))}),this},is:function(e){var t=a(e),n=!0,r=this;return d(f,function(e,i){var s,o=t[i.cache];return o&&(s=r[i.cache]||i.to&&i.to(r._rgba)||[],d(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 d(f,function(n,r){t[r.cache]&&e.push(n)}),e.pop()},transition:function(e,t){var r=a(e),i=r._space(),s=f[i],o=this.alpha()===0?a("transparent"):this,u=o[s.cache]||s.to(o._rgba),c=u.slice();return r=r[s.cache],d(s.props,function(e,i){var s=i.idx,o=u[s],a=r[s],f=l[i.type]||{};if(a===null)return;o===null?c[s]=a:(f.mod&&(a-o>f.mod/2?o+=f.mod:o-a>f.mod/2&&(o-=f.mod)),c[s]=n((a-o)*t+o,i))}),this[i](c)},blend:function(t){if(this._rgba[3]===1)return this;var n=this._rgba.slice(),r=n.pop(),i=a(t)._rgba;return a(e.map(n,function(e,t){return(1-r)*i[t]+r*e}))},toRgbaString:function(){var t="rgba(",n=e.map(this._rgba,function(e,t){return e==null?t>2?1:0:e});return n[3]===1&&(n.pop(),t="rgb("),t+n.join()+")"},toHslaString:function(){var t="hsla(",n=e.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(),t="hsl("),t+n.join()+")"},toHexString:function(t){var n=this._rgba.slice(),r=n.pop();return t&&n.push(~~(r*255)),"#"+e.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()}}),a.fn.parse.prototype=a.fn,f.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,u===0?c=0:f<=.5?c=u/a:c=u/(2-a),[Math.round(l)%360,c,f,i==null?1:i]},f.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],s=e[3],o=r<=.5?r*(1+n):r+n-r*n,u=2*r-o;return[Math.round(i(u,o,t+1/3)*255),Math.round(i(u,o,t)*255),Math.round(i(u,o,t-1/3)*255),s]},d(f,function(r,i){var s=i.props,u=i.cache,f=i.to,l=i.from;a.fn[r]=function(r){f&&!this[u]&&(this[u]=f(this._rgba));if(r===t)return this[u].slice();var i,o=e.type(r),c=o==="array"||o==="object"?r:arguments,h=this[u].slice();return d(s,function(e,t){var r=c[o==="object"?e:t.idx];r==null&&(r=h[t.idx]),h[t.idx]=n(r,t)}),l?(i=a(l(h)),i[u]=h,i):a(h)},d(s,function(t,n){if(a.fn[t])return;a.fn[t]=function(i){var s=e.type(i),u=t==="alpha"?this._hsla?"hsla":"rgba":r,a=this[u](),f=a[n.idx],l;return s==="undefined"?f:(s==="function"&&(i=i.call(this,f),s=e.type(i)),i==null&&n.empty?this:(s==="string"&&(l=o.exec(i),l&&(i=f+parseFloat(l[2])*(l[1]==="+"?1:-1))),a[n.idx]=i,this[u](a)))}})}),a.hook=function(t){var n=t.split(" ");d(n,function(t,n){e.cssHooks[n]={set:function(t,i){var s,o,u="";if(i!=="transparent"&&(e.type(i)!=="string"||(s=r(i)))){i=a(s||i);if(!c.rgba&&i._rgba[3]!==1){o=n==="backgroundColor"?t.parentNode:t;while((u===""||u==="transparent")&&o&&o.style)try{u=e.css(o,"backgroundColor"),o=o.parentNode}catch(f){}i=i.blend(u&&u!=="transparent"?u:"_default")}i=i.toRgbaString()}try{t.style[n]=i}catch(f){}}},e.fx.step[n]=function(t){t.colorInit||(t.start=a(t.elem,n),t.end=a(t.end),t.colorInit=!0),e.cssHooks[n].set(t.elem,t.start.transition(t.end,t.pos))}})},a.hook(s),e.cssHooks.borderColor={expand:function(e){var t={};return d(["Top","Right","Bottom","Left"],function(n,r){t["border"+r+"Color"]=e}),t}},p=e.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(t){var n,r,i=t.ownerDocument.defaultView?t.ownerDocument.defaultView.getComputedStyle(t,null):t.currentStyle,s={};if(i&&i.length&&i[0]&&i[i[0]]){r=i.length;while(r--)n=i[r],typeof i[n]=="string"&&(s[e.camelCase(n)]=i[n])}else for(n in i)typeof i[n]=="string"&&(s[n]=i[n]);return s}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.fn.addBack||(e.fn.addBack=function(e){return this.add(e==null?this.prevObject:this.prevObject.filter(e))}),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("*").addBack():s;f=f.map(function(){var t=e(this);return{el:t,start:n(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(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=e.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 r(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 i(t){return!t||typeof t=="number"||e.fx.speeds[t]?!0:typeof t=="string"&&!e.effects.effect[t]}e.extend(e.effects,{version:"1.10.0",save:function(e,t){for(var r=0;r<t.length;r++)t[r]!==null&&e.data(n+t[r],e[0].style[t[r]])},restore:function(e,r){var i,s;for(s=0;s<r.length;s++)r[s]!==null&&(i=e.data(n+r[s]),i===t&&(i=""),e.css(r[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 r(){e.isFunction(s)&&s.call(i[0]),e.isFunction(t)&&t()}var i=e(this),s=n.complete,u=n.mode;(i.is(":hidden")?u==="hide":u==="show")?r():o.call(i[0],n,r)}var n=r.apply(this,arguments),i=n.mode,s=n.queue,o=e.effects.effect[n.effect];return e.fx.off||!o?i?this[i](n.duration,n.complete):this.each(function(){n.complete&&n.complete.call(this)}):s===!1?this.each(t):this.queue(s||"fx",t)},_show:e.fn.show,show:function(e){if(i(e))return this._show.apply(this,arguments);var t=r.apply(this,arguments);return t.mode="show",this.effect.call(this,t)},_hide:e.fn.hide,hide:function(e){if(i(e))return this._hide.apply(this,arguments);var t=r.apply(this,arguments);return t.mode="hide",this.effect.call(this,t)},__toggle:e.fn.toggle,toggle:function(t){if(i(t)||typeof t=="boolean"||e.isFunction(t))return this.__toggle.apply(this,arguments);var n=r.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)
|
% Generated by roxygen2 (4.1.1): do not edit by hand
% Please edit documentation in R/mxnet_generated.R
\name{mx.symbol.LinearRegressionOutput}
\alias{mx.symbol.LinearRegressionOutput}
\title{Use linear regression for final output, this is used on final output of a net.}
\usage{
mx.symbol.LinearRegressionOutput(...)
}
\arguments{
\item{data}{Symbol
Input data to function.}
\item{label}{Symbol
Input label to function.}
\item{name}{string, optional
Name of the resulting symbol.}
}
\value{
out The result mx.symbol
}
\description{
Use linear regression for final output, this is used on final output of a net.
}
|
/R-package/man/mx.symbol.LinearRegressionOutput.Rd
|
permissive
|
XinliangZhu/mxnet
|
R
| false | false | 617 |
rd
|
% Generated by roxygen2 (4.1.1): do not edit by hand
% Please edit documentation in R/mxnet_generated.R
\name{mx.symbol.LinearRegressionOutput}
\alias{mx.symbol.LinearRegressionOutput}
\title{Use linear regression for final output, this is used on final output of a net.}
\usage{
mx.symbol.LinearRegressionOutput(...)
}
\arguments{
\item{data}{Symbol
Input data to function.}
\item{label}{Symbol
Input label to function.}
\item{name}{string, optional
Name of the resulting symbol.}
}
\value{
out The result mx.symbol
}
\description{
Use linear regression for final output, this is used on final output of a net.
}
|
## Put comments here that give an overall description of what your
## functions do
## This function creates a special "matrix" object that can cache
## its inverse.
makeCacheMatrix <- function(x = matrix()) {
inv <- NULL
set <- function(y) {
x <<- y
inv <<- NULL
}
get <- function() x
setinv <- function() {
inv <<- solve(x)
}
getinv <- function() inv
list(set = set, get = get,
setinv = setinv,
getinv = getinv)
}
## This function computes the inverse of the special "matrix"
## returned by makeCacheMatrix above. If the inverse has already
## been calculated (and the matrix has not changed), then cacheSolve
## should retrieve the inverse from the cache.
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
inv <- x$getinv()
if(!is.null(inv)) {
message("getting cached data")
return(inv)
}
data <- x$get()
inv <- solve(data, ...)
x$setinv(x)
inv
}
|
/cachematrix.R
|
no_license
|
LouayMalatili/ProgrammingAssignment2
|
R
| false | false | 1,017 |
r
|
## Put comments here that give an overall description of what your
## functions do
## This function creates a special "matrix" object that can cache
## its inverse.
makeCacheMatrix <- function(x = matrix()) {
inv <- NULL
set <- function(y) {
x <<- y
inv <<- NULL
}
get <- function() x
setinv <- function() {
inv <<- solve(x)
}
getinv <- function() inv
list(set = set, get = get,
setinv = setinv,
getinv = getinv)
}
## This function computes the inverse of the special "matrix"
## returned by makeCacheMatrix above. If the inverse has already
## been calculated (and the matrix has not changed), then cacheSolve
## should retrieve the inverse from the cache.
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
inv <- x$getinv()
if(!is.null(inv)) {
message("getting cached data")
return(inv)
}
data <- x$get()
inv <- solve(data, ...)
x$setinv(x)
inv
}
|
context("sampler2_cpp")
test_that("sampler_cpp2", {
set.seed(4711)
N <- 1000
D <- 17
V <- 31
K <- 10
P <- 3
state_df <- data.frame(doc = sample(1:D, size = N, replace = TRUE),
type = sample(1:V, size = N, replace = TRUE),
topic = sample(1:K, size = N, replace = TRUE),
party = sample(1:P, size = N, replace = TRUE),
perspective = sample(0:1, size = N, replace = TRUE))
constants <- list(D = length(unique(state_df$doc)),
V = length(unique(state_df$type)),
K = length(unique(state_df$topic)),
P = length(unique(state_df$party)),
N = nrow(state_df))
expect_silent(
stopifnot(constants$D == D,
constants$V == V,
constants$K == K,
constants$P == P,
constants$N == N)
)
icrcpp1 <- PerspectiveTopicModel:::init_count_cpp(state_df, constants)
icrcpp1[["n_kp"]] <- apply(icrcpp1$n_kpx, MARGIN=c(1, 2), sum)
icrcpp1[["n_kx"]] <- apply(icrcpp1$n_kpx, MARGIN=c(1, 3), sum)
expect_silent(
stopifnot(all(icrcpp1$n_dk >= 0),
all(icrcpp1$n_vkpx >= 0),
all(icrcpp1$n_kpx >= 0),
all(icrcpp1$n_kp >= 0),
all(icrcpp1$n_kx >= 0))
)
icrcpp2 <- PerspectiveTopicModel:::init_count2_cpp(state_df, constants)
icrcpp2[["n_pk"]] <- t(apply(icrcpp2$n_kpx, MARGIN=c(1, 2), sum))
icrcpp2[["n_xk"]] <- t(apply(icrcpp2$n_kpx, MARGIN=c(1, 3), sum))
expect_silent(
stopifnot(all(icrcpp2$n_dk >= 0),
all(icrcpp2$n_kvpx >= 0),
all(icrcpp2$n_kpx >= 0),
all(icrcpp2$n_pk >= 0),
all(icrcpp2$n_xk >= 0))
)
priors <- list(alpha = 0.1,
betax0 = 0.01,
betax1 = 0.05,
alpha_pi = 0.15,
beta_pi = 0.20)
set.seed(4712)
expect_silent(
state_it1_r <- PerspectiveTopicModel:::per_sampler_r(state = state_df, count_matrices = icrcpp1, priors = priors, constants = constants)
)
set.seed(4712)
expect_silent(
state_it1_cpp <- PerspectiveTopicModel:::per_sampler2_cpp(state = state_df, count_matrices = icrcpp2, priors = priors, constants = constants)
)
icrcpp_it1 <- PerspectiveTopicModel:::init_count2_cpp(state_it1_cpp[[1]], constants)
icrcpp_it1[["n_pk"]] <- t(apply(icrcpp_it1$n_kpx, MARGIN=c(1, 2), sum))
icrcpp_it1[["n_xk"]] <- t(apply(icrcpp_it1$n_kpx, MARGIN=c(1, 3), sum))
expect_silent(
stopifnot(sum(state_it1_cpp$count_matrices$n_dk) == sum(state_it1_cpp$count_matrices$n_kvpx),
sum(state_it1_cpp$count_matrices$n_kpx) == sum(state_it1_cpp$count_matrices$n_kvpx))
)
expect_silent(
stopifnot(all(icrcpp_it1$n_dk == state_it1_cpp$count_matrices$n_dk),
all(icrcpp_it1$n_kvpx == state_it1_cpp$count_matrices$n_kvpx),
all(icrcpp_it1$n_kpx == state_it1_cpp$count_matrices$n_kpx),
all(icrcpp_it1$n_pk == state_it1_cpp$count_matrices$n_pk),
all(icrcpp_it1$n_xk == state_it1_cpp$count_matrices$n_xk))
)
expect_silent(
stopifnot(all(state_it1_r$state == state_it1_cpp$state),
all(state_it1_r$count_matrices$n_dk == state_it1_cpp$count_matrices$n_dk),
all(state_it1_r$count_matrices$n_kpx == state_it1_cpp$count_matrices$n_kpx),
all(state_it1_r$count_matrices$n_kp == t(state_it1_cpp$count_matrices$n_pk)),
all(state_it1_r$count_matrices$n_kx == t(state_it1_cpp$count_matrices$n_xk)))
)
})
|
/tests/testthat/test-sampler2_cpp.R
|
no_license
|
MansMeg/PerspectiveTopicModel
|
R
| false | false | 3,598 |
r
|
context("sampler2_cpp")
test_that("sampler_cpp2", {
set.seed(4711)
N <- 1000
D <- 17
V <- 31
K <- 10
P <- 3
state_df <- data.frame(doc = sample(1:D, size = N, replace = TRUE),
type = sample(1:V, size = N, replace = TRUE),
topic = sample(1:K, size = N, replace = TRUE),
party = sample(1:P, size = N, replace = TRUE),
perspective = sample(0:1, size = N, replace = TRUE))
constants <- list(D = length(unique(state_df$doc)),
V = length(unique(state_df$type)),
K = length(unique(state_df$topic)),
P = length(unique(state_df$party)),
N = nrow(state_df))
expect_silent(
stopifnot(constants$D == D,
constants$V == V,
constants$K == K,
constants$P == P,
constants$N == N)
)
icrcpp1 <- PerspectiveTopicModel:::init_count_cpp(state_df, constants)
icrcpp1[["n_kp"]] <- apply(icrcpp1$n_kpx, MARGIN=c(1, 2), sum)
icrcpp1[["n_kx"]] <- apply(icrcpp1$n_kpx, MARGIN=c(1, 3), sum)
expect_silent(
stopifnot(all(icrcpp1$n_dk >= 0),
all(icrcpp1$n_vkpx >= 0),
all(icrcpp1$n_kpx >= 0),
all(icrcpp1$n_kp >= 0),
all(icrcpp1$n_kx >= 0))
)
icrcpp2 <- PerspectiveTopicModel:::init_count2_cpp(state_df, constants)
icrcpp2[["n_pk"]] <- t(apply(icrcpp2$n_kpx, MARGIN=c(1, 2), sum))
icrcpp2[["n_xk"]] <- t(apply(icrcpp2$n_kpx, MARGIN=c(1, 3), sum))
expect_silent(
stopifnot(all(icrcpp2$n_dk >= 0),
all(icrcpp2$n_kvpx >= 0),
all(icrcpp2$n_kpx >= 0),
all(icrcpp2$n_pk >= 0),
all(icrcpp2$n_xk >= 0))
)
priors <- list(alpha = 0.1,
betax0 = 0.01,
betax1 = 0.05,
alpha_pi = 0.15,
beta_pi = 0.20)
set.seed(4712)
expect_silent(
state_it1_r <- PerspectiveTopicModel:::per_sampler_r(state = state_df, count_matrices = icrcpp1, priors = priors, constants = constants)
)
set.seed(4712)
expect_silent(
state_it1_cpp <- PerspectiveTopicModel:::per_sampler2_cpp(state = state_df, count_matrices = icrcpp2, priors = priors, constants = constants)
)
icrcpp_it1 <- PerspectiveTopicModel:::init_count2_cpp(state_it1_cpp[[1]], constants)
icrcpp_it1[["n_pk"]] <- t(apply(icrcpp_it1$n_kpx, MARGIN=c(1, 2), sum))
icrcpp_it1[["n_xk"]] <- t(apply(icrcpp_it1$n_kpx, MARGIN=c(1, 3), sum))
expect_silent(
stopifnot(sum(state_it1_cpp$count_matrices$n_dk) == sum(state_it1_cpp$count_matrices$n_kvpx),
sum(state_it1_cpp$count_matrices$n_kpx) == sum(state_it1_cpp$count_matrices$n_kvpx))
)
expect_silent(
stopifnot(all(icrcpp_it1$n_dk == state_it1_cpp$count_matrices$n_dk),
all(icrcpp_it1$n_kvpx == state_it1_cpp$count_matrices$n_kvpx),
all(icrcpp_it1$n_kpx == state_it1_cpp$count_matrices$n_kpx),
all(icrcpp_it1$n_pk == state_it1_cpp$count_matrices$n_pk),
all(icrcpp_it1$n_xk == state_it1_cpp$count_matrices$n_xk))
)
expect_silent(
stopifnot(all(state_it1_r$state == state_it1_cpp$state),
all(state_it1_r$count_matrices$n_dk == state_it1_cpp$count_matrices$n_dk),
all(state_it1_r$count_matrices$n_kpx == state_it1_cpp$count_matrices$n_kpx),
all(state_it1_r$count_matrices$n_kp == t(state_it1_cpp$count_matrices$n_pk)),
all(state_it1_r$count_matrices$n_kx == t(state_it1_cpp$count_matrices$n_xk)))
)
})
|
library(bigsnpr)
gen <- function(n, m) {
I <- 1:m
p <- I / (2 * m + 1)
mat <- outer(I, I, FUN = function(i, j) {
1 / (abs(i - j) + 1)
})
bindata::rmvbin(n, p, bincorr = mat) +
bindata::rmvbin(n, p, bincorr = mat)
}
N <- 200
M <- 500
fake <- snp_fake(N, M)
G <- fake$genotypes
G[] <- rep(gen(N, M / 20), 20)
nbNA <- VGAM::rbetabinom.ab(M, size = N, shape1 = 0.6, shape2 = 20)
indNA <- cbind(
unlist(
lapply(nbNA, function(nb) {
`if`(nb > 0, sample(N, size = nb), NULL)
})
),
rep(cols_along(G), nbNA)
)
G[indNA] <- as.raw(3)
fake$map$chromosome <- sort(sample(1:2, M, TRUE))
snp_writeBed(fake, "inst/extdata/example-missing.bed")
|
/data-raw/example-missing.R
|
no_license
|
privefl/bigsnpr
|
R
| false | false | 673 |
r
|
library(bigsnpr)
gen <- function(n, m) {
I <- 1:m
p <- I / (2 * m + 1)
mat <- outer(I, I, FUN = function(i, j) {
1 / (abs(i - j) + 1)
})
bindata::rmvbin(n, p, bincorr = mat) +
bindata::rmvbin(n, p, bincorr = mat)
}
N <- 200
M <- 500
fake <- snp_fake(N, M)
G <- fake$genotypes
G[] <- rep(gen(N, M / 20), 20)
nbNA <- VGAM::rbetabinom.ab(M, size = N, shape1 = 0.6, shape2 = 20)
indNA <- cbind(
unlist(
lapply(nbNA, function(nb) {
`if`(nb > 0, sample(N, size = nb), NULL)
})
),
rep(cols_along(G), nbNA)
)
G[indNA] <- as.raw(3)
fake$map$chromosome <- sort(sample(1:2, M, TRUE))
snp_writeBed(fake, "inst/extdata/example-missing.bed")
|
# ------------------------------------------------------------------
# This material is distributed under the GNU General Public License
# Version 2. You may review the terms of this license at
# http://www.gnu.org/licenses/gpl-2.0.html
#
# Copyright (c) 2012-2013, Michel Lang, Helena Kotthaus,
# TU Dortmund University
#
# All rights reserved.
#
# Simple linear regression using the stats package with default parameters
# USEAGE: Rscript [scriptfile] [problem-number] [number of replications]
# Output: unadjusted R^2
# ------------------------------------------------------------------
library(stats)
type <- "regression"
args <- commandArgs(TRUE)
if (length(args)) {
num <- as.integer(args[1])
repls <- as.integer(args[2])
}
load(file.path("problems", sprintf("%s_%02i.RData", type, num)))
R2 <- numeric(repls)
for (repl in seq_len(repls)) {
set.seed(repl)
train <- sample(nrow(problem)) < floor(2/3 * nrow(problem))
mod <- lm(y ~ ., data = problem[train, ])
y <- problem[!train, "y"]
y.hat <- predict(mod, problem[!train, ])
R2[repl] <- 1 - sum((y - y.hat)^2) / sum((y - mean(y))^2)
}
message(round(mean(R2), 4))
|
/MachineLearningAlg/main_functions/lm.R
|
no_license
|
allr/benchR
|
R
| false | false | 1,139 |
r
|
# ------------------------------------------------------------------
# This material is distributed under the GNU General Public License
# Version 2. You may review the terms of this license at
# http://www.gnu.org/licenses/gpl-2.0.html
#
# Copyright (c) 2012-2013, Michel Lang, Helena Kotthaus,
# TU Dortmund University
#
# All rights reserved.
#
# Simple linear regression using the stats package with default parameters
# USEAGE: Rscript [scriptfile] [problem-number] [number of replications]
# Output: unadjusted R^2
# ------------------------------------------------------------------
library(stats)
type <- "regression"
args <- commandArgs(TRUE)
if (length(args)) {
num <- as.integer(args[1])
repls <- as.integer(args[2])
}
load(file.path("problems", sprintf("%s_%02i.RData", type, num)))
R2 <- numeric(repls)
for (repl in seq_len(repls)) {
set.seed(repl)
train <- sample(nrow(problem)) < floor(2/3 * nrow(problem))
mod <- lm(y ~ ., data = problem[train, ])
y <- problem[!train, "y"]
y.hat <- predict(mod, problem[!train, ])
R2[repl] <- 1 - sum((y - y.hat)^2) / sum((y - mean(y))^2)
}
message(round(mean(R2), 4))
|
#####################
# Oct 26, 2018
# Making sure that I can clone and comit R scripts with Git via the terminal
# doing this as a test
######################
setwd("Z:/GitHub/hello-world")
main.dir<-"Z:/GitHub/"
# in terminal:
git clone https://github.com/StewartResearch/hello-world.git
# now make some changes
# git commit-m
# add a git message
# git commit
# add to repository
# git push
# push/sync with github.com
# git pull
# pulls down from github
# git clone
# clones the git repositories
# git branch
# check which branch you are on
######################################## the above only works within the directory of each repository
# git add
# git addA
# git
# tells you all of the git commands
##########################################
# an example from the terminal:
# with my mistakes imbedded
# generally type:
# git add .
# git commit -m "[your message here]"
# git push
# the above will update all files in the repository
# but the message will be specific to anything that is changed
# you can then double check the push by going to the GitHub URL for that repository
# OR, you can go to GitKraken or some other platform you may be using.
# ALWAYS REMEMBER TO SAVE YOUR FILES IN R/RSTUDIO
# Git will only update what has been saved.
########################################################
# Making sure Git Repositories are properly set up ----
########################################################
# 1. Go to a selected repository on GitHub.com
### fork the repository
### copy the clone/download URL
# 2. If using GitKraken - go to your GitKraken desktop app
### clone the repository
#### do this from GitHub
#### State where you'd like this "local" version of the repostory saved on your machine
### On the remote tab, state the original repostory you went to in stage #1 on Github, and name this "upstream"
# 3. Go to RStudio
### Restart R-studio (ctrl-Shift-F10)
### in the files section, open the folder that you have added to GitKraken (step #2)
### Select the Git tab to look at the changes you've made
### goahead, make changes, and commit them
#######################################
# Getting Git installed with RStudio ----
#######################################
# you need to have Git on your desktop to make git communicate with GitKraken and/or RStudio
# install Git from the website
# then in R studio go to Tools Global or Project options
# select the file of git (git.exe) that you downloaded
# click apply
# this should get a Git tab on the upper right hand corner of your RStudio
# this allows you to use this tab rather than cloning, commiting, and pushing RStudio changes
# to Git via the terminal command lines (phew!)
|
/Hello-World.R
|
no_license
|
StewartResearch/hello-world
|
R
| false | false | 2,705 |
r
|
#####################
# Oct 26, 2018
# Making sure that I can clone and comit R scripts with Git via the terminal
# doing this as a test
######################
setwd("Z:/GitHub/hello-world")
main.dir<-"Z:/GitHub/"
# in terminal:
git clone https://github.com/StewartResearch/hello-world.git
# now make some changes
# git commit-m
# add a git message
# git commit
# add to repository
# git push
# push/sync with github.com
# git pull
# pulls down from github
# git clone
# clones the git repositories
# git branch
# check which branch you are on
######################################## the above only works within the directory of each repository
# git add
# git addA
# git
# tells you all of the git commands
##########################################
# an example from the terminal:
# with my mistakes imbedded
# generally type:
# git add .
# git commit -m "[your message here]"
# git push
# the above will update all files in the repository
# but the message will be specific to anything that is changed
# you can then double check the push by going to the GitHub URL for that repository
# OR, you can go to GitKraken or some other platform you may be using.
# ALWAYS REMEMBER TO SAVE YOUR FILES IN R/RSTUDIO
# Git will only update what has been saved.
########################################################
# Making sure Git Repositories are properly set up ----
########################################################
# 1. Go to a selected repository on GitHub.com
### fork the repository
### copy the clone/download URL
# 2. If using GitKraken - go to your GitKraken desktop app
### clone the repository
#### do this from GitHub
#### State where you'd like this "local" version of the repostory saved on your machine
### On the remote tab, state the original repostory you went to in stage #1 on Github, and name this "upstream"
# 3. Go to RStudio
### Restart R-studio (ctrl-Shift-F10)
### in the files section, open the folder that you have added to GitKraken (step #2)
### Select the Git tab to look at the changes you've made
### goahead, make changes, and commit them
#######################################
# Getting Git installed with RStudio ----
#######################################
# you need to have Git on your desktop to make git communicate with GitKraken and/or RStudio
# install Git from the website
# then in R studio go to Tools Global or Project options
# select the file of git (git.exe) that you downloaded
# click apply
# this should get a Git tab on the upper right hand corner of your RStudio
# this allows you to use this tab rather than cloning, commiting, and pushing RStudio changes
# to Git via the terminal command lines (phew!)
|
library(testthat)
test_check("gmo")
|
/tests/testthat.R
|
permissive
|
jan-glx/gmo
|
R
| false | false | 36 |
r
|
library(testthat)
test_check("gmo")
|
# Example of Machine Learning algorithm using "Decision trees"
# with R's carot package.
# MAIN IDEAS
#
# *Iteratively split variables into groups
# *Eval homogeneity with each group
# *Split again if necessary
# BASIC ALGORITHM
#
# 1.- Start with all variables in one group
# 2.- Find variable that best separates outcomes
# 3.- Divide data into two leaves on that node.
# 4.- Within each node, find best variables that separates outcomes
# 5.- Continue until the groups are too small or suff pure
# MEASURE OF IMPURITY
#
# \hat{p}_{mk}=\frac{1}{N_m}\sum_{xi in Leaf m}Xi_{y_i=k}
#
# Misclassification error:
# 1- \hat{p}_{mk}
#
# 0 is perfect purity and 0.5 if no purity.
# Use the iris data
data(iris)
install.packages('ggplot2')
install.packages('caret', dependencies = TRUE)
library(ggplot2)
library(caret)
# Variable names
names(iris)
# Find how many obs of each species
table(iris$Species)
# We try to predict species
# Split the data into training and testing
inTrain <- createDataPartition(iris$Species,
p=0.7,
list=FALSE)
training <- iris[inTrain, ]
testing <- iris[-inTrain, ]
# Next plot training data by sepal&petal width
# color by species
qplot(Petal.Width, Sepal.Width,
colour=Species,
data=training)
# Do a model fit
modFit <- train(Species~.,
method="rpart",
data=training)
print(modFit$finalModel)
# Take a look at classification tree
plot(modFit$finalModel,
uniform=TRUE,
main="Classification Tree")
text(modFit$finalModel,
use.n = TRUE,
all = TRUE,
cex = 0.8)
# Now make prediction on testing data
preds <- predict(modFit, newdata = testing)
# check how many wrong predictions and where they appear
sum(preds != testing$Species)
which(preds != testing$Species)
|
/8_machine/decision_trees.R
|
no_license
|
chuymtz/datasciencecoursera
|
R
| false | false | 1,873 |
r
|
# Example of Machine Learning algorithm using "Decision trees"
# with R's carot package.
# MAIN IDEAS
#
# *Iteratively split variables into groups
# *Eval homogeneity with each group
# *Split again if necessary
# BASIC ALGORITHM
#
# 1.- Start with all variables in one group
# 2.- Find variable that best separates outcomes
# 3.- Divide data into two leaves on that node.
# 4.- Within each node, find best variables that separates outcomes
# 5.- Continue until the groups are too small or suff pure
# MEASURE OF IMPURITY
#
# \hat{p}_{mk}=\frac{1}{N_m}\sum_{xi in Leaf m}Xi_{y_i=k}
#
# Misclassification error:
# 1- \hat{p}_{mk}
#
# 0 is perfect purity and 0.5 if no purity.
# Use the iris data
data(iris)
install.packages('ggplot2')
install.packages('caret', dependencies = TRUE)
library(ggplot2)
library(caret)
# Variable names
names(iris)
# Find how many obs of each species
table(iris$Species)
# We try to predict species
# Split the data into training and testing
inTrain <- createDataPartition(iris$Species,
p=0.7,
list=FALSE)
training <- iris[inTrain, ]
testing <- iris[-inTrain, ]
# Next plot training data by sepal&petal width
# color by species
qplot(Petal.Width, Sepal.Width,
colour=Species,
data=training)
# Do a model fit
modFit <- train(Species~.,
method="rpart",
data=training)
print(modFit$finalModel)
# Take a look at classification tree
plot(modFit$finalModel,
uniform=TRUE,
main="Classification Tree")
text(modFit$finalModel,
use.n = TRUE,
all = TRUE,
cex = 0.8)
# Now make prediction on testing data
preds <- predict(modFit, newdata = testing)
# check how many wrong predictions and where they appear
sum(preds != testing$Species)
which(preds != testing$Species)
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/sagemaker_operations.R
\name{sagemaker_create_experiment}
\alias{sagemaker_create_experiment}
\title{Creates an Amazon SageMaker \emph{experiment}}
\usage{
sagemaker_create_experiment(ExperimentName, DisplayName, Description,
Tags)
}
\arguments{
\item{ExperimentName}{[required] The name of the experiment. The name must be unique in your AWS account
and is not case-sensitive.}
\item{DisplayName}{The name of the experiment as displayed. The name doesn\'t need to be
unique. If you don\'t specify \code{DisplayName}, the value in
\code{ExperimentName} is displayed.}
\item{Description}{The description of the experiment.}
\item{Tags}{A list of tags to associate with the experiment. You can use Search API
to search on the tags.}
}
\description{
Creates an Amazon SageMaker \emph{experiment}. An experiment is a collection
of \emph{trials} that are observed, compared and evaluated as a group. A
trial is a set of steps, called \emph{trial components}, that produce a
machine learning model.
}
\details{
The goal of an experiment is to determine the components that produce
the best model. Multiple trials are performed, each one isolating and
measuring the impact of a change to one or more inputs, while keeping
the remaining inputs constant.
When you use Amazon SageMaker Studio or the Amazon SageMaker Python SDK,
all experiments, trials, and trial components are automatically tracked,
logged, and indexed. When you use the AWS SDK for Python (Boto), you
must use the logging APIs provided by the SDK.
You can add tags to experiments, trials, trial components and then use
the Search API to search for the tags.
To add a description to an experiment, specify the optional
\code{Description} parameter. To add a description later, or to change the
description, call the UpdateExperiment API.
To get a list of all your experiments, call the ListExperiments API. To
view an experiment\'s properties, call the DescribeExperiment API. To
get a list of all the trials associated with an experiment, call the
ListTrials API. To create a trial call the CreateTrial API.
}
\section{Request syntax}{
\preformatted{svc$create_experiment(
ExperimentName = "string",
DisplayName = "string",
Description = "string",
Tags = list(
list(
Key = "string",
Value = "string"
)
)
)
}
}
\keyword{internal}
|
/cran/paws.machine.learning/man/sagemaker_create_experiment.Rd
|
permissive
|
johnnytommy/paws
|
R
| false | true | 2,407 |
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/sagemaker_operations.R
\name{sagemaker_create_experiment}
\alias{sagemaker_create_experiment}
\title{Creates an Amazon SageMaker \emph{experiment}}
\usage{
sagemaker_create_experiment(ExperimentName, DisplayName, Description,
Tags)
}
\arguments{
\item{ExperimentName}{[required] The name of the experiment. The name must be unique in your AWS account
and is not case-sensitive.}
\item{DisplayName}{The name of the experiment as displayed. The name doesn\'t need to be
unique. If you don\'t specify \code{DisplayName}, the value in
\code{ExperimentName} is displayed.}
\item{Description}{The description of the experiment.}
\item{Tags}{A list of tags to associate with the experiment. You can use Search API
to search on the tags.}
}
\description{
Creates an Amazon SageMaker \emph{experiment}. An experiment is a collection
of \emph{trials} that are observed, compared and evaluated as a group. A
trial is a set of steps, called \emph{trial components}, that produce a
machine learning model.
}
\details{
The goal of an experiment is to determine the components that produce
the best model. Multiple trials are performed, each one isolating and
measuring the impact of a change to one or more inputs, while keeping
the remaining inputs constant.
When you use Amazon SageMaker Studio or the Amazon SageMaker Python SDK,
all experiments, trials, and trial components are automatically tracked,
logged, and indexed. When you use the AWS SDK for Python (Boto), you
must use the logging APIs provided by the SDK.
You can add tags to experiments, trials, trial components and then use
the Search API to search for the tags.
To add a description to an experiment, specify the optional
\code{Description} parameter. To add a description later, or to change the
description, call the UpdateExperiment API.
To get a list of all your experiments, call the ListExperiments API. To
view an experiment\'s properties, call the DescribeExperiment API. To
get a list of all the trials associated with an experiment, call the
ListTrials API. To create a trial call the CreateTrial API.
}
\section{Request syntax}{
\preformatted{svc$create_experiment(
ExperimentName = "string",
DisplayName = "string",
Description = "string",
Tags = list(
list(
Key = "string",
Value = "string"
)
)
)
}
}
\keyword{internal}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/getAllAreaData.R
\name{getAllAreaData}
\alias{getAllAreaData}
\title{Get All Area Data}
\usage{
getAllAreaData()
}
\description{
Description
}
|
/man/getAllAreaData.Rd
|
no_license
|
SWS-Methodology/faoswsSeed
|
R
| false | true | 222 |
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/getAllAreaData.R
\name{getAllAreaData}
\alias{getAllAreaData}
\title{Get All Area Data}
\usage{
getAllAreaData()
}
\description{
Description
}
|
% Generated by roxygen2 (4.0.1): do not edit by hand
\name{NetworkModel}
\alias{NetworkModel}
\title{Instantiates an object of class NetworkModel}
\usage{
NetworkModel(model_params = set_model_param())
}
\arguments{
\item{model_params}{[list; DEFAULT = \code{\link{set_model_param}}()] :: Model parameters}
}
\value{
[NetworkModel] :: A representation of a model generated as specified
}
\description{
Instantiates an object of class NetworkModel
}
|
/netcompLib/man/NetworkModel.Rd
|
no_license
|
minghao2016/netcompLib
|
R
| false | false | 450 |
rd
|
% Generated by roxygen2 (4.0.1): do not edit by hand
\name{NetworkModel}
\alias{NetworkModel}
\title{Instantiates an object of class NetworkModel}
\usage{
NetworkModel(model_params = set_model_param())
}
\arguments{
\item{model_params}{[list; DEFAULT = \code{\link{set_model_param}}()] :: Model parameters}
}
\value{
[NetworkModel] :: A representation of a model generated as specified
}
\description{
Instantiates an object of class NetworkModel
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/get_more.R
\name{get_primary}
\alias{get_primary}
\title{Primary room size (primærrom)}
\usage{
get_primary(x)
}
\arguments{
\item{x}{HTML code}
}
\description{
Primary room size (primærrom)
}
|
/man/get_primary.Rd
|
no_license
|
ybkamaleri/boligfinn
|
R
| false | true | 273 |
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/get_more.R
\name{get_primary}
\alias{get_primary}
\title{Primary room size (primærrom)}
\usage{
get_primary(x)
}
\arguments{
\item{x}{HTML code}
}
\description{
Primary room size (primærrom)
}
|
# FUNCTIONS IN THIS FILE:
# improve
# isUnimodal
# isMonotoneR
# isMonotoneL
# isBoundedL
# isBoundedR
#*****************************************************************************************
#*** improve *****************************************************************************
#*****************************************************************************************
#' Move points closer to a target while maintaining a constraint.
#'
#' \code{improve(startValue, x, confun)} uses a greedy algorithm to move the elements of a
#' user-supplied vector \code{startValue} closer to their target values \code{x}, while
#' continually satisfying the constraint-checking function \code{confun}.
#'
#' The algorithm implemented here is the one in Wolters (2012), "A Greedy Algorithm for Unimodal
#' Kernel Density Estimation by Data Sharpening," \emph{Journal of Statistical Software}, 47(6).
#' It could conceivably be useful as a part of other gradient-free optimization schemes where
#' we have an infeasible point and a feasible one, and we seek a point that is on
#' the constraint boundary near the infeasible one.
#'
#' @param startValue The vector of starting values for the search. Must satisfy
#' \code{confun(startValue) == TRUE}
#' @param x The target values.
#' @param confun The constraint-checking function. \code{confun(y)} must return a Boolean value
#' that is invariant to permutations of its vector argument \code{y}.
#' @param verbose A logical value indicating whether or not information about iteration progress
#' should be printed to the console.
#' @param maxpasses The maximum allowable number of sweeps through the data points. At each pass,
#' every point that is not pinned at the constraint boundary is moved toward its target point in a
#' stepping-out procedure.
#' @param tol Numerical tolerance for constraint checking. A point is considered to be at the
#' constraint boundary if adding \code{tol} to it causes the constraint to be violated. If \code{tol}
#' is too large, the algorithm will terminate prematurely. If it is too small, run time will be
#' increased with no discernible benefit in the result.
#'
#' @return A vector of the same length as \code{startValue}, with elements closer to \code{x}.
#' @export
#'
#' @examples
#' #Constrain points to be inside the hypercube with vertices at -1 and +1.
#' #The target point is a vector of independent random standard normal variates.
#' #Start at rep(0,n) and "improve" the solution toward the target.
#' n <- 20
#' incube <- function(x) all(x <= 1 & x >= -1)
#' x0 <- rep(0,n)
#' target <- sort(rnorm(n))
#' xstar <- improve(x0, target, incube, verbose=TRUE)
#' dist <- abs(target - xstar)
#' zapsmall(cbind(target, xstar, dist), 4)
improve<-function(startValue, x, confun, verbose=FALSE, maxpasses=500,
tol=diff(range(c(startValue, x)) / 1e5)){
#=== PRELIMINARIES ================================================
#--- Input checking ---------------------------
stopifnot(
is.vector(startValue, mode='numeric'), !any(is.na(startValue)),
is.vector(x, mode='numeric'), !any(is.na(x)),
length(startValue)==length(x),
length(maxpasses)==1, maxpasses>=1,
length(tol)==1 && tol>0,
is.function(confun)
)
if (!confun(startValue))
stop("The initial solution does not satisfy the constraint.")
#--- Initialize objects -----------------------
# During the search, we want y to be matched to x such that the jth smallest value of y
# has the jth smallest value of x as its target. But we also must prevent cycling. Work
# with x sorted in ascending order. Then order(y) gives the sort order to bring y into
# a matched state. And actually doing the matching is just a sort(y) operation. Save
# rank(x) for putting the final y back into matching state with the original x.
n <- length(startValue)
idx <- 1:n
count <- 1
ranks_of_x <- rank(x, ties.method="first")
x <- sort(x)
y <- sort(startValue)
ordermem <- matrix(0, nrow=maxpasses+1, ncol=n)
ordermem[1, ] <- order(y)
unitvec <- function(a,b) (b-a)/sqrt(sum((b-a)^2)) #-unit vector from a to b.
#--- Find the set of moveable points ----------
D <- abs(x-y) #-Distances between elements of x and y.
S <- sign(x-y) #-Sign of move from y to x.
home <- D<=tol
nothome <- idx[!home]
pinned <- rep(FALSE,n)
for (i in 1:length(nothome)) {
tst <- y;
j <- nothome[i]
tst[j] <- tst[j] + tol*S[j]
if (!confun(tst)) {
pinned[j] <- TRUE
}
}
moveable <- !(home | pinned)
m <- sum(moveable)
#=== RUN THE ALGORITHM ============================================
# Perform repeated passes through the data points. At each pass, try to move each point
# toward home by stepping out from its current location. The step size is a proportion
# of the distance |y(j) - x(j)|; this proportion starts at 1 (step all the way) and is
# reduced by factors of 2 whenever no moves can be made.
#--- Set the sweep order ----------------------
# Sweep in descending order of distance from home.
pts <- idx[moveable]
ix <- order(D[moveable], decreasing = TRUE)
pts <- pts[ix] #-The ordered set of moveables.
#--- SWEEP UNTIL NO MOVEABLE POINTS -----------
steps <- 1
while (m>0 && count<maxpasses) {
nmoved <- 0 #-move counter.
#--- A SINGLE PASS THROUGH THE POINTS -------
for (i in 1:m) {
j <- pts[i]
A <- y[j] #-The current moveable point.
B <- x[j] #-The target of the current point.
D <- abs(B-A) #-Distance between the points.
S <- sign(B-A) #-Sign of the move from A to B.
k <- 0 #-Counter for number of successful steps.
stepsize <- max(D/steps, tol) #-Min poss step size is equal to tol.
stop <- FALSE
while (!stop && (k+1)*stepsize<=D) {
# Start stepping out. Stop once constraint is violated or B is reached.
y[j] <- A + (k+1)*stepsize*S
if (confun(y)) {
k <- k + 1;
} else {
stop <- TRUE
}
}
y[j] <- A + k*stepsize*S #-Set y[j] to last feasible step.
if (k>0) {
nmoved <- nmoved + 1
}
}
#--- Show progress if requested -------------
if (verbose) {
cat('Sweep:', count, ' moves:', nmoved, ' moveable:', m, ' steps:', steps, '\n')
}
#--- Prepare for the next sweep -------------
# Increment the sweep counter and the order memory. If points have been moved,
# re-match the points as necessary. If not, halve the step size.
count <- count + 1
if (nmoved > 0) {
#--- Re-sort points -----------------------
thisorder <- order(y)
hasmatch <- any(apply(ordermem, 1, function(v,w) all(v==w), thisorder))
if (!hasmatch) {
y <- sort(y)
ordermem[count, ] <- thisorder
}
#--- Re-find the moveable points ----------
D <- abs(x-y)
S <- sign(x-y)
home <- D<=tol
nothome <- idx[!home]
pinned <- rep(FALSE,n)
for (i in 1:length(nothome)) {
tst <- y;
j <- nothome[i]
tst[j] <- tst[j] + tol*S[j]
if (!confun(tst)) {
pinned[j] <- TRUE
}
}
moveable <- !(home | pinned)
m <- sum(moveable)
#--- Re-set sweep order -------------------
pts <- idx[moveable]
ix <- order(D[moveable], decreasing = TRUE)
pts <- pts[ix]
} else {
steps <- 2*steps
}
}
#=== RETURN OUTPUTS ===============================================
if (m>0) {
warning("Search stopped because maxpasses was reached.")
}
y[ranks_of_x]
}
#*****************************************************************************************
#*** isUnimodal **************************************************************************
#*****************************************************************************************
#' Check for unimodality of function values.
#'
#' Given a set of function values for increasing abscissa values, we call this unimodal if
#' there are zero or one values that are greater than all of their neighbors. Before
#' checking for modes, the values are scaled to fill [0, 1] and then rounded to four
#' decimal places. This eliminates unwanted detection of tiny differences as modes.
#'
#' This function is intended to be called from other functions in the scdensity package.
#' It does not implement any argument checking.
#'
#' @param f A vector of function values for increasing abscissa values.
#'
#' @return A logical value indicating if unimodality is satisfied.
#'
#' @keywords internal
isUnimodal = function(f) {
f <- (f - min(f))/(max(f) - min(f))
f <- round(f, 4)
d = diff(f)
d = d[d!=0];
chgs = sum(diff(sign(d))!=0); #-Number of sign changes.
chgs<=1; #-Chgs could be 0 for monotone, 1 for unimodal.
}
#*****************************************************************************************
#*** isMonotoneR *************************************************************************
#*****************************************************************************************
#' Check for monotonicity of function values in the right tail.
#'
#' Given a vector of n function values and an index ix, determines whether the function
#' values having indices greater than or equal to ix are non-decreasing or non-increasing.
#' Returns TRUE if they are, FALSE otherwise.
#'
#' As in \code{isUnimodal}, the values are first scaled to fill [0, 1] and then rounded to
#' four decimal places. This eliminates unwanted detection of tiny differences as modes.
#'
#' This function is intended to be called from other functions in the scdensity package.
#' It does not implement any argument checking.
#'
#' @param f A vector of function values for increasing abscissa values.
#' @param ix An index giving the cutoff for checking monotonicity.
#'
#' @return A logical value indicating if the constraint is satisfied.
#'
#' @keywords internal
isMonotoneR = function(f, ix) {
f <- (f - min(f))/(max(f) - min(f))
f <- round(f, 4)
n <- length(f)
d = diff(f[ix:n])
d = d[d!=0];
chgs = sum(diff(sign(d))!=0); #-Number of sign changes.
chgs<=0; #-Chgs must be 0 for monotone.
}
#*****************************************************************************************
#*** isMonotoneL *************************************************************************
#*****************************************************************************************
#' Check for monotonicity of function values in the left tail.
#'
#' Given a vector of n function values and an index ix, determines whether the function
#' values having indices less than or equal to ix are non-decreasing or non-increasing.
#' Returns TRUE if they are, FALSE otherwise.
#'
#' As in \code{isUnimodal}, the values are first scaled to fill [0, 1] and then rounded to
#' four decimal places. This eliminates unwanted detection of tiny differences as modes.
#'
#' This function is intended to be called from other functions in the scdensity package.
#' It does not implement any argument checking.
#'
#' @param f A vector of function values for increasing abscissa values.
#' @param ix An index giving the cutoff for checking monotonicity.
#'
#' @return A logical value indicating if the constraint is satisfied.
#'
#' @keywords internal
isMonotoneL = function(f, ix) {
f <- (f - min(f))/(max(f) - min(f))
f <- round(f, 4)
n <- length(f)
d = diff(f[1:ix])
d = d[d!=0];
chgs = sum(diff(sign(d))!=0); #-Number of sign changes.
chgs<=0; #-Chgs must be 0 for monotone.
}
#*****************************************************************************************
#*** isBoundedL *************************************************************************
#*****************************************************************************************
#' Check for zeros at the left side of a vector of function values.
#'
#' Given a vector of n function values and an index ix, check whether values 1:ix are zero.
#' Returns TRUE if they are, FALSE otherwise.
#'
#' As in \code{isUnimodal}, the values are first scaled to fill [0, 1] and then rounded to
#' four decimal places. Because of this it is still possible to use the "bounded support"
#' constraints with the Gaussian kernel.
#'
#' This function is intended to be called from other functions in the scdensity package.
#' It does not implement any argument checking.
#'
#' @param f A vector of function values for increasing abscissa values.
#' @param ix An index giving the cutoff for checking for zero.
#'
#' @return A logical value indicating if the constraint is satisfied.
#'
#' @keywords internal
isBoundedL = function(f, ix) {
f <- (f - min(f))/(max(f) - min(f))
f <- round(f, 4)
all(f[1:ix]==0)
}
#*****************************************************************************************
#*** isBoundedR *************************************************************************
#*****************************************************************************************
#' Check for zeros at the right side of a vector of function values.
#'
#' Given a vector of n function values and an index ix, check whether values with indices
#' greater than or equal to ix are zero. Returns TRUE if they are, FALSE otherwise.
#'
#' As in \code{isUnimodal}, the values are first scaled to fill [0, 1] and then rounded to
#' four decimal places. Because of this it is still possible to use the "bounded support"
#' constraints with the Gaussian kernel.
#'
#' This function is intended to be called from other functions in the scdensity package.
#' It does not implement any argument checking.
#'
#' @param f A vector of function values for increasing abscissa values.
#' @param ix An index giving the cutoff for checking for zero.
#'
#' @return A logical value indicating if the constraint is satisfied.
#'
#' @keywords internal
isBoundedR = function(f, ix) {
f <- (f - min(f))/(max(f) - min(f))
f <- round(f, 4)
n <- length(f)
all(f[ix:n]==0)
}
|
/R/sharpenedKDE.R
|
no_license
|
cran/scdensity
|
R
| false | false | 14,730 |
r
|
# FUNCTIONS IN THIS FILE:
# improve
# isUnimodal
# isMonotoneR
# isMonotoneL
# isBoundedL
# isBoundedR
#*****************************************************************************************
#*** improve *****************************************************************************
#*****************************************************************************************
#' Move points closer to a target while maintaining a constraint.
#'
#' \code{improve(startValue, x, confun)} uses a greedy algorithm to move the elements of a
#' user-supplied vector \code{startValue} closer to their target values \code{x}, while
#' continually satisfying the constraint-checking function \code{confun}.
#'
#' The algorithm implemented here is the one in Wolters (2012), "A Greedy Algorithm for Unimodal
#' Kernel Density Estimation by Data Sharpening," \emph{Journal of Statistical Software}, 47(6).
#' It could conceivably be useful as a part of other gradient-free optimization schemes where
#' we have an infeasible point and a feasible one, and we seek a point that is on
#' the constraint boundary near the infeasible one.
#'
#' @param startValue The vector of starting values for the search. Must satisfy
#' \code{confun(startValue) == TRUE}
#' @param x The target values.
#' @param confun The constraint-checking function. \code{confun(y)} must return a Boolean value
#' that is invariant to permutations of its vector argument \code{y}.
#' @param verbose A logical value indicating whether or not information about iteration progress
#' should be printed to the console.
#' @param maxpasses The maximum allowable number of sweeps through the data points. At each pass,
#' every point that is not pinned at the constraint boundary is moved toward its target point in a
#' stepping-out procedure.
#' @param tol Numerical tolerance for constraint checking. A point is considered to be at the
#' constraint boundary if adding \code{tol} to it causes the constraint to be violated. If \code{tol}
#' is too large, the algorithm will terminate prematurely. If it is too small, run time will be
#' increased with no discernible benefit in the result.
#'
#' @return A vector of the same length as \code{startValue}, with elements closer to \code{x}.
#' @export
#'
#' @examples
#' #Constrain points to be inside the hypercube with vertices at -1 and +1.
#' #The target point is a vector of independent random standard normal variates.
#' #Start at rep(0,n) and "improve" the solution toward the target.
#' n <- 20
#' incube <- function(x) all(x <= 1 & x >= -1)
#' x0 <- rep(0,n)
#' target <- sort(rnorm(n))
#' xstar <- improve(x0, target, incube, verbose=TRUE)
#' dist <- abs(target - xstar)
#' zapsmall(cbind(target, xstar, dist), 4)
improve<-function(startValue, x, confun, verbose=FALSE, maxpasses=500,
tol=diff(range(c(startValue, x)) / 1e5)){
#=== PRELIMINARIES ================================================
#--- Input checking ---------------------------
stopifnot(
is.vector(startValue, mode='numeric'), !any(is.na(startValue)),
is.vector(x, mode='numeric'), !any(is.na(x)),
length(startValue)==length(x),
length(maxpasses)==1, maxpasses>=1,
length(tol)==1 && tol>0,
is.function(confun)
)
if (!confun(startValue))
stop("The initial solution does not satisfy the constraint.")
#--- Initialize objects -----------------------
# During the search, we want y to be matched to x such that the jth smallest value of y
# has the jth smallest value of x as its target. But we also must prevent cycling. Work
# with x sorted in ascending order. Then order(y) gives the sort order to bring y into
# a matched state. And actually doing the matching is just a sort(y) operation. Save
# rank(x) for putting the final y back into matching state with the original x.
n <- length(startValue)
idx <- 1:n
count <- 1
ranks_of_x <- rank(x, ties.method="first")
x <- sort(x)
y <- sort(startValue)
ordermem <- matrix(0, nrow=maxpasses+1, ncol=n)
ordermem[1, ] <- order(y)
unitvec <- function(a,b) (b-a)/sqrt(sum((b-a)^2)) #-unit vector from a to b.
#--- Find the set of moveable points ----------
D <- abs(x-y) #-Distances between elements of x and y.
S <- sign(x-y) #-Sign of move from y to x.
home <- D<=tol
nothome <- idx[!home]
pinned <- rep(FALSE,n)
for (i in 1:length(nothome)) {
tst <- y;
j <- nothome[i]
tst[j] <- tst[j] + tol*S[j]
if (!confun(tst)) {
pinned[j] <- TRUE
}
}
moveable <- !(home | pinned)
m <- sum(moveable)
#=== RUN THE ALGORITHM ============================================
# Perform repeated passes through the data points. At each pass, try to move each point
# toward home by stepping out from its current location. The step size is a proportion
# of the distance |y(j) - x(j)|; this proportion starts at 1 (step all the way) and is
# reduced by factors of 2 whenever no moves can be made.
#--- Set the sweep order ----------------------
# Sweep in descending order of distance from home.
pts <- idx[moveable]
ix <- order(D[moveable], decreasing = TRUE)
pts <- pts[ix] #-The ordered set of moveables.
#--- SWEEP UNTIL NO MOVEABLE POINTS -----------
steps <- 1
while (m>0 && count<maxpasses) {
nmoved <- 0 #-move counter.
#--- A SINGLE PASS THROUGH THE POINTS -------
for (i in 1:m) {
j <- pts[i]
A <- y[j] #-The current moveable point.
B <- x[j] #-The target of the current point.
D <- abs(B-A) #-Distance between the points.
S <- sign(B-A) #-Sign of the move from A to B.
k <- 0 #-Counter for number of successful steps.
stepsize <- max(D/steps, tol) #-Min poss step size is equal to tol.
stop <- FALSE
while (!stop && (k+1)*stepsize<=D) {
# Start stepping out. Stop once constraint is violated or B is reached.
y[j] <- A + (k+1)*stepsize*S
if (confun(y)) {
k <- k + 1;
} else {
stop <- TRUE
}
}
y[j] <- A + k*stepsize*S #-Set y[j] to last feasible step.
if (k>0) {
nmoved <- nmoved + 1
}
}
#--- Show progress if requested -------------
if (verbose) {
cat('Sweep:', count, ' moves:', nmoved, ' moveable:', m, ' steps:', steps, '\n')
}
#--- Prepare for the next sweep -------------
# Increment the sweep counter and the order memory. If points have been moved,
# re-match the points as necessary. If not, halve the step size.
count <- count + 1
if (nmoved > 0) {
#--- Re-sort points -----------------------
thisorder <- order(y)
hasmatch <- any(apply(ordermem, 1, function(v,w) all(v==w), thisorder))
if (!hasmatch) {
y <- sort(y)
ordermem[count, ] <- thisorder
}
#--- Re-find the moveable points ----------
D <- abs(x-y)
S <- sign(x-y)
home <- D<=tol
nothome <- idx[!home]
pinned <- rep(FALSE,n)
for (i in 1:length(nothome)) {
tst <- y;
j <- nothome[i]
tst[j] <- tst[j] + tol*S[j]
if (!confun(tst)) {
pinned[j] <- TRUE
}
}
moveable <- !(home | pinned)
m <- sum(moveable)
#--- Re-set sweep order -------------------
pts <- idx[moveable]
ix <- order(D[moveable], decreasing = TRUE)
pts <- pts[ix]
} else {
steps <- 2*steps
}
}
#=== RETURN OUTPUTS ===============================================
if (m>0) {
warning("Search stopped because maxpasses was reached.")
}
y[ranks_of_x]
}
#*****************************************************************************************
#*** isUnimodal **************************************************************************
#*****************************************************************************************
#' Check for unimodality of function values.
#'
#' Given a set of function values for increasing abscissa values, we call this unimodal if
#' there are zero or one values that are greater than all of their neighbors. Before
#' checking for modes, the values are scaled to fill [0, 1] and then rounded to four
#' decimal places. This eliminates unwanted detection of tiny differences as modes.
#'
#' This function is intended to be called from other functions in the scdensity package.
#' It does not implement any argument checking.
#'
#' @param f A vector of function values for increasing abscissa values.
#'
#' @return A logical value indicating if unimodality is satisfied.
#'
#' @keywords internal
isUnimodal = function(f) {
f <- (f - min(f))/(max(f) - min(f))
f <- round(f, 4)
d = diff(f)
d = d[d!=0];
chgs = sum(diff(sign(d))!=0); #-Number of sign changes.
chgs<=1; #-Chgs could be 0 for monotone, 1 for unimodal.
}
#*****************************************************************************************
#*** isMonotoneR *************************************************************************
#*****************************************************************************************
#' Check for monotonicity of function values in the right tail.
#'
#' Given a vector of n function values and an index ix, determines whether the function
#' values having indices greater than or equal to ix are non-decreasing or non-increasing.
#' Returns TRUE if they are, FALSE otherwise.
#'
#' As in \code{isUnimodal}, the values are first scaled to fill [0, 1] and then rounded to
#' four decimal places. This eliminates unwanted detection of tiny differences as modes.
#'
#' This function is intended to be called from other functions in the scdensity package.
#' It does not implement any argument checking.
#'
#' @param f A vector of function values for increasing abscissa values.
#' @param ix An index giving the cutoff for checking monotonicity.
#'
#' @return A logical value indicating if the constraint is satisfied.
#'
#' @keywords internal
isMonotoneR = function(f, ix) {
f <- (f - min(f))/(max(f) - min(f))
f <- round(f, 4)
n <- length(f)
d = diff(f[ix:n])
d = d[d!=0];
chgs = sum(diff(sign(d))!=0); #-Number of sign changes.
chgs<=0; #-Chgs must be 0 for monotone.
}
#*****************************************************************************************
#*** isMonotoneL *************************************************************************
#*****************************************************************************************
#' Check for monotonicity of function values in the left tail.
#'
#' Given a vector of n function values and an index ix, determines whether the function
#' values having indices less than or equal to ix are non-decreasing or non-increasing.
#' Returns TRUE if they are, FALSE otherwise.
#'
#' As in \code{isUnimodal}, the values are first scaled to fill [0, 1] and then rounded to
#' four decimal places. This eliminates unwanted detection of tiny differences as modes.
#'
#' This function is intended to be called from other functions in the scdensity package.
#' It does not implement any argument checking.
#'
#' @param f A vector of function values for increasing abscissa values.
#' @param ix An index giving the cutoff for checking monotonicity.
#'
#' @return A logical value indicating if the constraint is satisfied.
#'
#' @keywords internal
isMonotoneL = function(f, ix) {
f <- (f - min(f))/(max(f) - min(f))
f <- round(f, 4)
n <- length(f)
d = diff(f[1:ix])
d = d[d!=0];
chgs = sum(diff(sign(d))!=0); #-Number of sign changes.
chgs<=0; #-Chgs must be 0 for monotone.
}
#*****************************************************************************************
#*** isBoundedL *************************************************************************
#*****************************************************************************************
#' Check for zeros at the left side of a vector of function values.
#'
#' Given a vector of n function values and an index ix, check whether values 1:ix are zero.
#' Returns TRUE if they are, FALSE otherwise.
#'
#' As in \code{isUnimodal}, the values are first scaled to fill [0, 1] and then rounded to
#' four decimal places. Because of this it is still possible to use the "bounded support"
#' constraints with the Gaussian kernel.
#'
#' This function is intended to be called from other functions in the scdensity package.
#' It does not implement any argument checking.
#'
#' @param f A vector of function values for increasing abscissa values.
#' @param ix An index giving the cutoff for checking for zero.
#'
#' @return A logical value indicating if the constraint is satisfied.
#'
#' @keywords internal
isBoundedL = function(f, ix) {
f <- (f - min(f))/(max(f) - min(f))
f <- round(f, 4)
all(f[1:ix]==0)
}
#*****************************************************************************************
#*** isBoundedR *************************************************************************
#*****************************************************************************************
#' Check for zeros at the right side of a vector of function values.
#'
#' Given a vector of n function values and an index ix, check whether values with indices
#' greater than or equal to ix are zero. Returns TRUE if they are, FALSE otherwise.
#'
#' As in \code{isUnimodal}, the values are first scaled to fill [0, 1] and then rounded to
#' four decimal places. Because of this it is still possible to use the "bounded support"
#' constraints with the Gaussian kernel.
#'
#' This function is intended to be called from other functions in the scdensity package.
#' It does not implement any argument checking.
#'
#' @param f A vector of function values for increasing abscissa values.
#' @param ix An index giving the cutoff for checking for zero.
#'
#' @return A logical value indicating if the constraint is satisfied.
#'
#' @keywords internal
isBoundedR = function(f, ix) {
f <- (f - min(f))/(max(f) - min(f))
f <- round(f, 4)
n <- length(f)
all(f[ix:n]==0)
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/sdwis_enforcement_action.R
\name{sdwis_enforcement_action}
\alias{sdwis_enforcement_action}
\title{Retrieve enforcement action data from sdwis database}
\usage{
sdwis_enforcement_action(PWSID = NULL, ENFORCEMENT_ID = NULL,
ORIGINATOR_CODE = NULL, ENFORCEMENT_DATE = NULL,
ENFORCEMENT_ACTION_TYPE_CODE = NULL, ENFORCEMENT_COMMENT_TEXT = NULL)
}
\arguments{
\item{PWSID}{e.g. '010106001'. See Details.}
\item{ENFORCEMENT_ID}{e.g. '0106001IF9/27/2010'. See Details.}
\item{ORIGINATOR_CODE}{e.g. 'R'. See Details.}
\item{ENFORCEMENT_DATE}{e.g. '27-SEP-10'. See Details.}
\item{ENFORCEMENT_ACTION_TYPE_CODE}{e.g. 'EIF'. See Details.}
\item{ENFORCEMENT_COMMENT_TEXT}{e.g. 'Lead and Copper Results Notification - Action auto-generated by DIME based upon Public Notice records.'. See Details.}
}
\description{
Retrieve enforcement action data from sdwis database
}
|
/man/sdwis_enforcement_action.Rd
|
no_license
|
markwh/envirofacts
|
R
| false | true | 944 |
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/sdwis_enforcement_action.R
\name{sdwis_enforcement_action}
\alias{sdwis_enforcement_action}
\title{Retrieve enforcement action data from sdwis database}
\usage{
sdwis_enforcement_action(PWSID = NULL, ENFORCEMENT_ID = NULL,
ORIGINATOR_CODE = NULL, ENFORCEMENT_DATE = NULL,
ENFORCEMENT_ACTION_TYPE_CODE = NULL, ENFORCEMENT_COMMENT_TEXT = NULL)
}
\arguments{
\item{PWSID}{e.g. '010106001'. See Details.}
\item{ENFORCEMENT_ID}{e.g. '0106001IF9/27/2010'. See Details.}
\item{ORIGINATOR_CODE}{e.g. 'R'. See Details.}
\item{ENFORCEMENT_DATE}{e.g. '27-SEP-10'. See Details.}
\item{ENFORCEMENT_ACTION_TYPE_CODE}{e.g. 'EIF'. See Details.}
\item{ENFORCEMENT_COMMENT_TEXT}{e.g. 'Lead and Copper Results Notification - Action auto-generated by DIME based upon Public Notice records.'. See Details.}
}
\description{
Retrieve enforcement action data from sdwis database
}
|
#' Calculate amount excreted (typically in urine or feces)
#'
#' @param conc The concentration in the sample
#' @param volume The volume (or mass) of the sample
#' @param check Should the concentration and volume data be checked?
#' @return The amount excreted during the interval
#' @details The units for the concentration and volume should match such
#' that \code{sum(conc*volume)} has units of mass or moles.
#' @seealso \code{\link{pk.calc.clr}}, \code{\link{pk.calc.fe}}
#' @export
pk.calc.ae <- function(conc, volume, check=TRUE) {
sum(conc*volume)
}
add.interval.col("ae",
FUN="pk.calc.ae",
values=c(FALSE, TRUE),
desc="The amount excreted (typically into urine or feces)")
PKNCA.set.summary("ae", business.geomean, business.geocv)
#' Calculate renal clearance
#'
#' @param ae The amount excreted in urine (as a numeric scalar or
#' vector)
#' @param auc The area under the curve (as a numeric scalar or vector)
#' @return The renal clearance as a number
#' @details The units for the \code{ae} and \code{auc} should match such
#' that \code{ae/auc} has units of volume/time.
#' @seealso \code{\link{pk.calc.ae}}, \code{\link{pk.calc.fe}}
#' @export
pk.calc.clr <- function(ae, auc) {
sum(ae)/auc
}
add.interval.col("clr.last",
FUN="pk.calc.clr",
values=c(FALSE, TRUE),
formalsmap=list(auc="auclast"),
desc="The renal clearance calculated using AUClast")
PKNCA.set.summary("clr.last", business.geomean, business.geocv)
add.interval.col("clr.obs",
FUN="pk.calc.clr",
values=c(FALSE, TRUE),
formalsmap=list(auc="aucinf.obs"),
desc="The renal clearance calculated using AUCinf,obs")
PKNCA.set.summary("clr.obs", business.geomean, business.geocv)
add.interval.col("clr.pred",
FUN="pk.calc.clr",
values=c(FALSE, TRUE),
formalsmap=list(auc="aucinf.pred"),
desc="The renal clearance calculated using AUCinf,pred")
PKNCA.set.summary("clr.pred", business.geomean, business.geocv)
#' Calculate fraction excreted (typically in urine or feces)
#'
#' @param ae The amount excreted (as a numeric scalar or vector)
#' @param dose The dose (as a numeric scalar or vector)
#' @return The fraction of dose excreted.
#' @details The units for \code{ae} and \code{dose} should be the same
#' so that \code{ae/dose} is a unitless fraction.
#' @seealso \code{\link{pk.calc.ae}}, \code{\link{pk.calc.clr}}
#' @export
pk.calc.fe <- function(ae, dose) {
sum(ae)/dose
}
add.interval.col("fe",
FUN="pk.calc.fe",
values=c(FALSE, TRUE),
desc="The fraction of the dose excreted")
PKNCA.set.summary("fe", business.geomean, business.geocv)
|
/R/pk.calc.urine.R
|
no_license
|
ksl31/pknca
|
R
| false | false | 2,844 |
r
|
#' Calculate amount excreted (typically in urine or feces)
#'
#' @param conc The concentration in the sample
#' @param volume The volume (or mass) of the sample
#' @param check Should the concentration and volume data be checked?
#' @return The amount excreted during the interval
#' @details The units for the concentration and volume should match such
#' that \code{sum(conc*volume)} has units of mass or moles.
#' @seealso \code{\link{pk.calc.clr}}, \code{\link{pk.calc.fe}}
#' @export
pk.calc.ae <- function(conc, volume, check=TRUE) {
sum(conc*volume)
}
add.interval.col("ae",
FUN="pk.calc.ae",
values=c(FALSE, TRUE),
desc="The amount excreted (typically into urine or feces)")
PKNCA.set.summary("ae", business.geomean, business.geocv)
#' Calculate renal clearance
#'
#' @param ae The amount excreted in urine (as a numeric scalar or
#' vector)
#' @param auc The area under the curve (as a numeric scalar or vector)
#' @return The renal clearance as a number
#' @details The units for the \code{ae} and \code{auc} should match such
#' that \code{ae/auc} has units of volume/time.
#' @seealso \code{\link{pk.calc.ae}}, \code{\link{pk.calc.fe}}
#' @export
pk.calc.clr <- function(ae, auc) {
sum(ae)/auc
}
add.interval.col("clr.last",
FUN="pk.calc.clr",
values=c(FALSE, TRUE),
formalsmap=list(auc="auclast"),
desc="The renal clearance calculated using AUClast")
PKNCA.set.summary("clr.last", business.geomean, business.geocv)
add.interval.col("clr.obs",
FUN="pk.calc.clr",
values=c(FALSE, TRUE),
formalsmap=list(auc="aucinf.obs"),
desc="The renal clearance calculated using AUCinf,obs")
PKNCA.set.summary("clr.obs", business.geomean, business.geocv)
add.interval.col("clr.pred",
FUN="pk.calc.clr",
values=c(FALSE, TRUE),
formalsmap=list(auc="aucinf.pred"),
desc="The renal clearance calculated using AUCinf,pred")
PKNCA.set.summary("clr.pred", business.geomean, business.geocv)
#' Calculate fraction excreted (typically in urine or feces)
#'
#' @param ae The amount excreted (as a numeric scalar or vector)
#' @param dose The dose (as a numeric scalar or vector)
#' @return The fraction of dose excreted.
#' @details The units for \code{ae} and \code{dose} should be the same
#' so that \code{ae/dose} is a unitless fraction.
#' @seealso \code{\link{pk.calc.ae}}, \code{\link{pk.calc.clr}}
#' @export
pk.calc.fe <- function(ae, dose) {
sum(ae)/dose
}
add.interval.col("fe",
FUN="pk.calc.fe",
values=c(FALSE, TRUE),
desc="The fraction of the dose excreted")
PKNCA.set.summary("fe", business.geomean, business.geocv)
|
#Importing Data
train <- read.csv(file.choose(), na.strings = c(""," ",NA))
#Finding missing values
sort(colSums(is.na(train)), decreasing = TRUE)
#Data Exploration
library(ggplot2)
library(dplyr)
data <- train
# Total Number of Passengers: 891
NROW(data$PassengerId)
#Total Number of Passengers - Dead:549 Live:342
table(data$Survived)
ggplot(data , aes(x=Survived, fill = Sex)) + geom_bar() + labs(x = 'Dead and Survived') + geom_text(stat='count', aes(label=..count..), vjust=1.50, size=4, color="white",fontface = "bold")
#Total Number of 1st,2nd,3rd class people:216,184,491
table(data$Pclass)
#Total Number of 1st, 2nd, 3rd class people that are survived:136,87,119
count(data[which(data$Survived==1 & data$Pclass==1),])
count(data[which(data$Survived==1 & data$Pclass==2),])
count(data[which(data$Survived==1 & data$Pclass==3),])
ggplot(data, aes(x=Pclass, fill = as.character(Survived))) + geom_bar() + labs(x = 'Passengers class') + geom_text(stat='count', aes(label=..count..), vjust=-0.25, size=4)
# Number of Males:577 Females:314
table(data$Sex)
# Number of Males:109/468 Females:233/81 (survived/dead)
table(data$Sex,data$Survived)
ggplot(data, aes(x=Sex, fill = as.character(Survived))) + geom_bar() + geom_text(stat='count', aes(label=..count..), vjust=-0.25, size=4)
# Number of people under Age 0-10:64 10-20:115 20-30:229 30-40:153 40-50:84 50-60:42 60-70:17 70-80:4 80-90:0 Unknown:177
count(data[which(data$Age>=0 & data$Age<=10),])
count(data[which(data$Age>=11 & data$Age<=20),])
count(data[which(data$Age>=21 & data$Age<=30),])
count(data[which(data$Age>=31 & data$Age<=40),])
count(data[which(data$Age>=41 & data$Age<=50),])
count(data[which(data$Age>=51 & data$Age<=60),])
count(data[which(data$Age>=61 & data$Age<=70),])
count(data[which(data$Age>=71 & data$Age<=80),])
count(data[which(data$Age==999),])
ggplot(data, aes(x=Age, fill = as.character(Survived))) + geom_histogram(binwidth = 10) + geom_text(stat='count', aes(label=..count..), vjust=-0.25, size=4)
# Number of people that are survived under Age 0-10:38 10-20:44 20-30:84 30-40:69 40-50:33 50-60:17 60-70:4 70-80:1 unknown:52
count(data[which((data$Age>=0 & data$Age<=10) & data$Survived==1),])
count(data[which((data$Age>=11 & data$Age<=20) & data$Survived==1),])
count(data[which((data$Age>=21 & data$Age<=30) & data$Survived==1),])
count(data[which((data$Age>=31 & data$Age<=40) & data$Survived==1),])
count(data[which((data$Age>=41 & data$Age<=50) & data$Survived==1),])
count(data[which((data$Age>=51 & data$Age<=60) & data$Survived==1),])
count(data[which((data$Age>=61 & data$Age<=70) & data$Survived==1),])
count(data[which((data$Age>=71 & data$Age<=80) & data$Survived==1),])
count(data[which((data$Age>=81 & data$Age<=90) & data$Survived==1),])
count(data[which(data$Age==999 & data$Survived==1),])
# Total Number of a,b,c,d,e,f,g cabins:15, 47, 59, 33, 32, 13, 4 Missing:687
NROW(grep("^A", data$Cabin, value = TRUE))
NROW(grep("^B", data$Cabin, value = TRUE))
NROW(grep("^C", data$Cabin, value = TRUE))
NROW(grep("^D", data$Cabin, value = TRUE))
NROW(grep("^E", data$Cabin, value = TRUE))
NROW(grep("^F", data$Cabin, value = TRUE))
NROW(grep("^G", data$Cabin, value = TRUE))
# Number of people embarked in Cherbourg, Qeenstown, Southampton: 168, 77, 644
Summary(data)
# Number of people survived embarked in Cherbourg, Qeenstown, Southampton: 93, 30, 217
count(data[which(data$Embarked=='C' & data$Survived==1),])
count(data[which(data$Embarked=='Q' & data$Survived==1),])
count(data[which(data$Embarked=='S' & data$Survived==1),])
count(data[which(is.na(data$Embarked) & data$Survived==1),])
ggplot(data, aes(x=Embarked, fill = as.character(Survived))) + geom_bar() + geom_text(stat='count', aes(label=..count..), vjust=-0.25, size=4)
# Number of people survived with sibblings/spouses: __
# 0 1
# 0 398 210
# 1 97 112
# 2 15 13
# 3 12 4
# 4 15 3
# 5 5 0
# 8 7 0
table(data$SibSp,data$Survived)
ggplot(data, aes(x=SibSp, fill = as.character(Survived))) + geom_bar() + geom_text(stat='count', aes(label=..count..), vjust=-0.25, size=4)
# Number of people survived with Parents/children: __
# 0 1
# 0 445 233
# 1 53 65
# 2 40 40
# 3 2 3
# 4 4 0
# 5 4 1
# 6 1 0
table(data$Parch,data$Survived)
ggplot(data, aes(x=Parch, fill = as.character(Survived))) + geom_bar() + geom_text(stat='count', aes(label=..count..), vjust=-0.25, size=4)
#Finding total number of values in cabin
NROW(train$Cabin)
#Since cabin has more than 50% of missing values
#we can Remove cabin variable
train$Cabin <- NULL
#variables in trainset
names(train)
#Imputing missing values using missForst
#missForest builds a random forest model for each variable.
#Then it uses the model to predict missing values in the variable with the help of observed values
#install.packages('missForest')
library('missForest')
train.imp <- missForest(train[,c(1,2,3,6,11)])
train[,c(1,2,3,6,11)] <- train.imp$ximp
#Error in missing values
train.imp$OOBerror
#converting catogorical variables in to numeric
train$Name <- factor(as.numeric(train$Name))
train$Sex <- factor(train$Sex, labels = c(0,1), levels = c('female','male'))
train$Embarked <- factor(train$Embarked, labels = c(1,2,3), levels = c('C','Q','S'))
train$Ticket <- factor(as.numeric(train$Ticket))
#Converting character variables to numeric
train$Name <- as.integer(train$Name)
train$Sex <- as.integer(train$Sex)
train$Ticket <- as.integer(train$Ticket)
train$Embarked <- as.integer(train$Embarked)
#Feature Scaling
library(caret)
preObj <- preProcess(train[,c(1,3,4,5,6,7,8,9,10,11)], method=c("center", "scale"))
training <- predict(preObj, train[,c(1,3,4,5,6,7,8,9,10,11)])
training$Survived <- train$Survived
#Finding Outliers
plot(train)
#Splitting train data in to two datasets for validation
library(caTools)
set.seed(123)
split <- sample.split(training$Survived, SplitRatio = 0.80)
trainset <- subset(training, split == TRUE)
testset <- subset(training, split == FALSE)
#Taking dependent and indpendent variables
x_train <- trainset[-11]
y_train <- trainset[,11]
x_test <- testset[-11]
y_test <- testset[,11]
#Feature Selection
f_train <- trainset[,c(2,4,5,6,7,9,10,11)]
#Fitting training data to KNN
library(class)
knn_classifier <- knn(train =x_train , test = x_test, cl = y_train, k=5, prob = TRUE)
#Fitting training data to SVM
library(e1071)
svm_classifier = svm(formula = Survived ~ .,
data = f_train,
type = 'C-classification',
kernel = 'sigmoid')
#Fitting training data to naive bayes
library(caret)
nb_classifier = train(x_train, as.factor(y_train), 'nb',trControl=trainControl(method='cv',number=10))
#Fitting training data to decision tree
library(rpart)
dt_classifier <- rpart(formula = Survived ~ ., data = trainset, method = "class")
#Fitting training data to Random Forest
library(randomForest)
set.seed(123)
rf_classifier <- randomForest(x = x_train, y = y_train, ntree = 500)
#Fitting training data to XGBoost Model
library(xgboost)
xg_classifier <- xgboost(data = as.matrix(x_train), label = y_train, nrounds = 10)
#Fitting training data to Gradient boost model
library(gbm)
gb_classifier <- gbm(Survived ~ ., data = trainset,distribution = "gaussian",n.trees = 10000, interaction.depth = 4, shrinkage = 0.01)
#cross validation
library(caret)
train_control<- trainControl(method="cv", number=10, savePredictions = TRUE)
model<- train(Survived~., data=trainset, trControl=train_control, method="rpart")
#Predicting the test results
svm_pred <- predict(svm_classifier, newdata = x_test)
nb_pred <- predict(nb_classifier, newdata = x_test)
dt_pred <- predict(dt_classifier, newdata = x_test, type='class')
rf_pred <- predict(rf_classifier, newdata = x_test)
xg_pred <- predict(xg_classifier, newdata = as.matrix(x_test))
xg_pred <- ifelse(xg_pred >= 0.5, 1,0)
n.trees = seq(from=100 ,to=10000, by=100)
gb_pred <- predict(gb_classifier, newdata = x_test, n.trees = n.trees,na.action = na.pass)
kf_pred <- predict(model, newdata = x_test)
#confusion matrix
cm_knn <- table(y_test,knn_classifier) #64% before scalling, After scaling 79%
cm_svm <- table(y_test, svm_pred) #61% before scalling, After Scaling 73%, After feature selection 72%
cm_nb <- table(y_test, nb_pred) #80% accuracy
cm_dt <- table(y_test, dt_pred) #79% accuracy before feature selection
rf_log <- ifelse(rf_pred > 0.50, "YES", "NO")
cm_rf <- table(y_test, rf_log) #84% accuracy before feature selection
kf_log <- ifelse(kf_pred > 0.50, "YES", "NO")
cm_kf <- table(y_test, kf_log) #76% accuracy before feature selection
cm_xg <- table(y_test, xg_pred) #82.5 accuracy before feature selection
# gb_log <- ifelse(gb_pred > 0.50, "YES", "NO")
# cm_gb <- table(y_test, gb_log)
|
/Titanic.R
|
no_license
|
Hemanthkaruturi/Titanic
|
R
| false | false | 8,910 |
r
|
#Importing Data
train <- read.csv(file.choose(), na.strings = c(""," ",NA))
#Finding missing values
sort(colSums(is.na(train)), decreasing = TRUE)
#Data Exploration
library(ggplot2)
library(dplyr)
data <- train
# Total Number of Passengers: 891
NROW(data$PassengerId)
#Total Number of Passengers - Dead:549 Live:342
table(data$Survived)
ggplot(data , aes(x=Survived, fill = Sex)) + geom_bar() + labs(x = 'Dead and Survived') + geom_text(stat='count', aes(label=..count..), vjust=1.50, size=4, color="white",fontface = "bold")
#Total Number of 1st,2nd,3rd class people:216,184,491
table(data$Pclass)
#Total Number of 1st, 2nd, 3rd class people that are survived:136,87,119
count(data[which(data$Survived==1 & data$Pclass==1),])
count(data[which(data$Survived==1 & data$Pclass==2),])
count(data[which(data$Survived==1 & data$Pclass==3),])
ggplot(data, aes(x=Pclass, fill = as.character(Survived))) + geom_bar() + labs(x = 'Passengers class') + geom_text(stat='count', aes(label=..count..), vjust=-0.25, size=4)
# Number of Males:577 Females:314
table(data$Sex)
# Number of Males:109/468 Females:233/81 (survived/dead)
table(data$Sex,data$Survived)
ggplot(data, aes(x=Sex, fill = as.character(Survived))) + geom_bar() + geom_text(stat='count', aes(label=..count..), vjust=-0.25, size=4)
# Number of people under Age 0-10:64 10-20:115 20-30:229 30-40:153 40-50:84 50-60:42 60-70:17 70-80:4 80-90:0 Unknown:177
count(data[which(data$Age>=0 & data$Age<=10),])
count(data[which(data$Age>=11 & data$Age<=20),])
count(data[which(data$Age>=21 & data$Age<=30),])
count(data[which(data$Age>=31 & data$Age<=40),])
count(data[which(data$Age>=41 & data$Age<=50),])
count(data[which(data$Age>=51 & data$Age<=60),])
count(data[which(data$Age>=61 & data$Age<=70),])
count(data[which(data$Age>=71 & data$Age<=80),])
count(data[which(data$Age==999),])
ggplot(data, aes(x=Age, fill = as.character(Survived))) + geom_histogram(binwidth = 10) + geom_text(stat='count', aes(label=..count..), vjust=-0.25, size=4)
# Number of people that are survived under Age 0-10:38 10-20:44 20-30:84 30-40:69 40-50:33 50-60:17 60-70:4 70-80:1 unknown:52
count(data[which((data$Age>=0 & data$Age<=10) & data$Survived==1),])
count(data[which((data$Age>=11 & data$Age<=20) & data$Survived==1),])
count(data[which((data$Age>=21 & data$Age<=30) & data$Survived==1),])
count(data[which((data$Age>=31 & data$Age<=40) & data$Survived==1),])
count(data[which((data$Age>=41 & data$Age<=50) & data$Survived==1),])
count(data[which((data$Age>=51 & data$Age<=60) & data$Survived==1),])
count(data[which((data$Age>=61 & data$Age<=70) & data$Survived==1),])
count(data[which((data$Age>=71 & data$Age<=80) & data$Survived==1),])
count(data[which((data$Age>=81 & data$Age<=90) & data$Survived==1),])
count(data[which(data$Age==999 & data$Survived==1),])
# Total Number of a,b,c,d,e,f,g cabins:15, 47, 59, 33, 32, 13, 4 Missing:687
NROW(grep("^A", data$Cabin, value = TRUE))
NROW(grep("^B", data$Cabin, value = TRUE))
NROW(grep("^C", data$Cabin, value = TRUE))
NROW(grep("^D", data$Cabin, value = TRUE))
NROW(grep("^E", data$Cabin, value = TRUE))
NROW(grep("^F", data$Cabin, value = TRUE))
NROW(grep("^G", data$Cabin, value = TRUE))
# Number of people embarked in Cherbourg, Qeenstown, Southampton: 168, 77, 644
Summary(data)
# Number of people survived embarked in Cherbourg, Qeenstown, Southampton: 93, 30, 217
count(data[which(data$Embarked=='C' & data$Survived==1),])
count(data[which(data$Embarked=='Q' & data$Survived==1),])
count(data[which(data$Embarked=='S' & data$Survived==1),])
count(data[which(is.na(data$Embarked) & data$Survived==1),])
ggplot(data, aes(x=Embarked, fill = as.character(Survived))) + geom_bar() + geom_text(stat='count', aes(label=..count..), vjust=-0.25, size=4)
# Number of people survived with sibblings/spouses: __
# 0 1
# 0 398 210
# 1 97 112
# 2 15 13
# 3 12 4
# 4 15 3
# 5 5 0
# 8 7 0
table(data$SibSp,data$Survived)
ggplot(data, aes(x=SibSp, fill = as.character(Survived))) + geom_bar() + geom_text(stat='count', aes(label=..count..), vjust=-0.25, size=4)
# Number of people survived with Parents/children: __
# 0 1
# 0 445 233
# 1 53 65
# 2 40 40
# 3 2 3
# 4 4 0
# 5 4 1
# 6 1 0
table(data$Parch,data$Survived)
ggplot(data, aes(x=Parch, fill = as.character(Survived))) + geom_bar() + geom_text(stat='count', aes(label=..count..), vjust=-0.25, size=4)
#Finding total number of values in cabin
NROW(train$Cabin)
#Since cabin has more than 50% of missing values
#we can Remove cabin variable
train$Cabin <- NULL
#variables in trainset
names(train)
#Imputing missing values using missForst
#missForest builds a random forest model for each variable.
#Then it uses the model to predict missing values in the variable with the help of observed values
#install.packages('missForest')
library('missForest')
train.imp <- missForest(train[,c(1,2,3,6,11)])
train[,c(1,2,3,6,11)] <- train.imp$ximp
#Error in missing values
train.imp$OOBerror
#converting catogorical variables in to numeric
train$Name <- factor(as.numeric(train$Name))
train$Sex <- factor(train$Sex, labels = c(0,1), levels = c('female','male'))
train$Embarked <- factor(train$Embarked, labels = c(1,2,3), levels = c('C','Q','S'))
train$Ticket <- factor(as.numeric(train$Ticket))
#Converting character variables to numeric
train$Name <- as.integer(train$Name)
train$Sex <- as.integer(train$Sex)
train$Ticket <- as.integer(train$Ticket)
train$Embarked <- as.integer(train$Embarked)
#Feature Scaling
library(caret)
preObj <- preProcess(train[,c(1,3,4,5,6,7,8,9,10,11)], method=c("center", "scale"))
training <- predict(preObj, train[,c(1,3,4,5,6,7,8,9,10,11)])
training$Survived <- train$Survived
#Finding Outliers
plot(train)
#Splitting train data in to two datasets for validation
library(caTools)
set.seed(123)
split <- sample.split(training$Survived, SplitRatio = 0.80)
trainset <- subset(training, split == TRUE)
testset <- subset(training, split == FALSE)
#Taking dependent and indpendent variables
x_train <- trainset[-11]
y_train <- trainset[,11]
x_test <- testset[-11]
y_test <- testset[,11]
#Feature Selection
f_train <- trainset[,c(2,4,5,6,7,9,10,11)]
#Fitting training data to KNN
library(class)
knn_classifier <- knn(train =x_train , test = x_test, cl = y_train, k=5, prob = TRUE)
#Fitting training data to SVM
library(e1071)
svm_classifier = svm(formula = Survived ~ .,
data = f_train,
type = 'C-classification',
kernel = 'sigmoid')
#Fitting training data to naive bayes
library(caret)
nb_classifier = train(x_train, as.factor(y_train), 'nb',trControl=trainControl(method='cv',number=10))
#Fitting training data to decision tree
library(rpart)
dt_classifier <- rpart(formula = Survived ~ ., data = trainset, method = "class")
#Fitting training data to Random Forest
library(randomForest)
set.seed(123)
rf_classifier <- randomForest(x = x_train, y = y_train, ntree = 500)
#Fitting training data to XGBoost Model
library(xgboost)
xg_classifier <- xgboost(data = as.matrix(x_train), label = y_train, nrounds = 10)
#Fitting training data to Gradient boost model
library(gbm)
gb_classifier <- gbm(Survived ~ ., data = trainset,distribution = "gaussian",n.trees = 10000, interaction.depth = 4, shrinkage = 0.01)
#cross validation
library(caret)
train_control<- trainControl(method="cv", number=10, savePredictions = TRUE)
model<- train(Survived~., data=trainset, trControl=train_control, method="rpart")
#Predicting the test results
svm_pred <- predict(svm_classifier, newdata = x_test)
nb_pred <- predict(nb_classifier, newdata = x_test)
dt_pred <- predict(dt_classifier, newdata = x_test, type='class')
rf_pred <- predict(rf_classifier, newdata = x_test)
xg_pred <- predict(xg_classifier, newdata = as.matrix(x_test))
xg_pred <- ifelse(xg_pred >= 0.5, 1,0)
n.trees = seq(from=100 ,to=10000, by=100)
gb_pred <- predict(gb_classifier, newdata = x_test, n.trees = n.trees,na.action = na.pass)
kf_pred <- predict(model, newdata = x_test)
#confusion matrix
cm_knn <- table(y_test,knn_classifier) #64% before scalling, After scaling 79%
cm_svm <- table(y_test, svm_pred) #61% before scalling, After Scaling 73%, After feature selection 72%
cm_nb <- table(y_test, nb_pred) #80% accuracy
cm_dt <- table(y_test, dt_pred) #79% accuracy before feature selection
rf_log <- ifelse(rf_pred > 0.50, "YES", "NO")
cm_rf <- table(y_test, rf_log) #84% accuracy before feature selection
kf_log <- ifelse(kf_pred > 0.50, "YES", "NO")
cm_kf <- table(y_test, kf_log) #76% accuracy before feature selection
cm_xg <- table(y_test, xg_pred) #82.5 accuracy before feature selection
# gb_log <- ifelse(gb_pred > 0.50, "YES", "NO")
# cm_gb <- table(y_test, gb_log)
|
#Load required packages
library(forecast)
library(xts)
library(lubridate)
seaice<-read.csv("seaice.csv",header = TRUE,stringsAsFactors = FALSE)
str(seaice)
north_hemi<-seaice[seaice$hemisphere=='north',]
seaice$Date<-as.Date(paste(seaice$Year,seaice$Month,seaice$Day,sep = '-'))
#create initial time series object
seaice.xts<-xts(x=seaice$Extent, order.by = seaice$Date)
seaice.monthly<-apply.monthly(seaice.xts,mean)
#split the data into train and test sets
div_index<-floor(0.8*length(seaice.monthly))
seaice.train<-seaice.monthly[1:div_index,]
seaice.test<-seaice.monthly[(div_index+1):length(seaice.monthly),]
#convert xts train/test data to ts objects
?ts
seaice.start<-c(year(start(seaice.train)),month(start(seaice.train)))
seaice.end<-c(year(end(seaice.train)),month(end(seaice.train)))
seaice.train<-ts(as.numeric(seaice.train),seaice.start,seaice.end,frequency = 12)
seaice.start<-c(year(start(seaice.test)),month(start(seaice.test)))
seaice.end<-c(year(end(seaice.test)),month(end(seaice.test)))
seaice.test<-ts(as.numeric(seaice.test),seaice.start,seaice.end,frequency = 12)
#use variable to track forecast horizon
forecast.horizon<-length(seaice.test)
cycle(seaice.train)
plot(aggregate(seaice.train))
boxplot(seaice.test~cycle(seaice.test))
decompose(seaice.test)
plot(decompose(seaice.test))
# Sea ice in May month
seaice.may<-window(seaice.test,start<-c(2008,5),freq=TRUE)
plot(seaice.may)
#forecast seaice extent
fs<-forecast(seaice.test)
attributes(fs)
plot(fs)
#HoltWinters objects
plot(HoltWinters(seaice.test))
seaice.predict<-predict(HoltWinters(seaice.test), n.ahead = 10*12)
plot(seaice.predict)
ts.plot(seaice.test,seaice.predict,lty=1:2)
|
/time_series_pred.R
|
no_license
|
bhisecj/Time_Series_Prediction
|
R
| false | false | 1,680 |
r
|
#Load required packages
library(forecast)
library(xts)
library(lubridate)
seaice<-read.csv("seaice.csv",header = TRUE,stringsAsFactors = FALSE)
str(seaice)
north_hemi<-seaice[seaice$hemisphere=='north',]
seaice$Date<-as.Date(paste(seaice$Year,seaice$Month,seaice$Day,sep = '-'))
#create initial time series object
seaice.xts<-xts(x=seaice$Extent, order.by = seaice$Date)
seaice.monthly<-apply.monthly(seaice.xts,mean)
#split the data into train and test sets
div_index<-floor(0.8*length(seaice.monthly))
seaice.train<-seaice.monthly[1:div_index,]
seaice.test<-seaice.monthly[(div_index+1):length(seaice.monthly),]
#convert xts train/test data to ts objects
?ts
seaice.start<-c(year(start(seaice.train)),month(start(seaice.train)))
seaice.end<-c(year(end(seaice.train)),month(end(seaice.train)))
seaice.train<-ts(as.numeric(seaice.train),seaice.start,seaice.end,frequency = 12)
seaice.start<-c(year(start(seaice.test)),month(start(seaice.test)))
seaice.end<-c(year(end(seaice.test)),month(end(seaice.test)))
seaice.test<-ts(as.numeric(seaice.test),seaice.start,seaice.end,frequency = 12)
#use variable to track forecast horizon
forecast.horizon<-length(seaice.test)
cycle(seaice.train)
plot(aggregate(seaice.train))
boxplot(seaice.test~cycle(seaice.test))
decompose(seaice.test)
plot(decompose(seaice.test))
# Sea ice in May month
seaice.may<-window(seaice.test,start<-c(2008,5),freq=TRUE)
plot(seaice.may)
#forecast seaice extent
fs<-forecast(seaice.test)
attributes(fs)
plot(fs)
#HoltWinters objects
plot(HoltWinters(seaice.test))
seaice.predict<-predict(HoltWinters(seaice.test), n.ahead = 10*12)
plot(seaice.predict)
ts.plot(seaice.test,seaice.predict,lty=1:2)
|
timestamp <- Sys.time()
library(caret)
library(plyr)
library(recipes)
library(dplyr)
model <- "Rborist"
## In case the package or one of its dependencies uses random numbers
## on startup so we'll pre-load the required libraries:
for(i in getModelInfo(model)[[1]]$library)
do.call("require", list(package = i))
#########################################################################
set.seed(2)
training <- twoClassSim(50, linearVars = 2)
testing <- twoClassSim(500, linearVars = 2)
trainX <- training[, -ncol(training)]
trainY <- training$Class
rec_cls <- recipe(Class ~ ., data = training) %>%
step_center(all_predictors()) %>%
step_scale(all_predictors())
seeds <- vector(mode = "list", length = nrow(training) + 1)
seeds <- lapply(seeds, function(x) 1:20)
cctrl1 <- trainControl(method = "cv", number = 3, returnResamp = "all",
classProbs = TRUE,
summaryFunction = twoClassSummary,
seeds = seeds)
cctrl2 <- trainControl(method = "LOOCV",
classProbs = TRUE, summaryFunction = twoClassSummary,
seeds = seeds)
cctrl3 <- trainControl(method = "oob",
seeds = seeds)
cctrl4 <- trainControl(method = "none",
classProbs = TRUE, summaryFunction = twoClassSummary,
seeds = seeds)
cctrlR <- trainControl(method = "cv", number = 3, returnResamp = "all", search = "random")
set.seed(849)
test_class_cv_model <- train(trainX, trainY,
method = "Rborist",
trControl = cctrl1,
metric = "ROC",
preProc = c("center", "scale"),
nTree = 21)
set.seed(849)
test_class_cv_form <- train(Class ~ ., data = training,
method = "Rborist",
trControl = cctrl1,
metric = "ROC",
preProc = c("center", "scale"),
nTree = 21)
test_class_pred <- predict(test_class_cv_model, testing[, -ncol(testing)])
test_class_prob <- predict(test_class_cv_model, testing[, -ncol(testing)], type = "prob")
test_class_pred_form <- predict(test_class_cv_form, testing[, -ncol(testing)])
test_class_prob_form <- predict(test_class_cv_form, testing[, -ncol(testing)], type = "prob")
set.seed(849)
test_class_loo_model <- train(trainX, trainY,
method = "Rborist",
trControl = cctrl2,
metric = "ROC",
preProc = c("center", "scale"),
nTree = 21)
test_levels <- levels(test_class_cv_model)
if(!all(levels(trainY) %in% test_levels))
cat("wrong levels")
set.seed(849)
test_class_rand <- train(trainX, trainY,
method = "Rborist",
trControl = cctrlR,
tuneLength = 4,
nTree = 21)
set.seed(849)
test_class_oob_model <- train(trainX, trainY,
method = "Rborist",
trControl = cctrl3,
nTree = 21)
set.seed(849)
test_class_none_model <- train(trainX, trainY,
method = "Rborist",
trControl = cctrl4,
tuneGrid = test_class_cv_model$bestTune,
metric = "ROC",
preProc = c("center", "scale"),
nTree = 21)
test_class_none_pred <- predict(test_class_none_model, testing[, -ncol(testing)])
test_class_none_prob <- predict(test_class_none_model, testing[, -ncol(testing)], type = "prob")
set.seed(849)
test_class_rec <- train(recipe = rec_cls,
data = training,
method = "Rborist",
trControl = cctrl1,
metric = "ROC",
nTree = 21)
if(
!isTRUE(
all.equal(test_class_cv_model$results,
test_class_rec$results))
)
stop("CV weights not giving the same results")
test_class_pred_rec <- predict(test_class_rec, testing[, -ncol(testing)])
test_class_prob_rec <- predict(test_class_rec, testing[, -ncol(testing)],
type = "prob")
#########################################################################
library(caret)
library(plyr)
library(recipes)
library(dplyr)
set.seed(1)
training <- SLC14_1(30)
testing <- SLC14_1(100)
trainX <- training[, -ncol(training)]
trainY <- training$y
rec_reg <- recipe(y ~ ., data = training) %>%
step_center(all_predictors()) %>%
step_scale(all_predictors())
testX <- trainX[, -ncol(training)]
testY <- trainX$y
rctrl1 <- trainControl(method = "cv", number = 3, returnResamp = "all", seeds = seeds)
rctrl2 <- trainControl(method = "LOOCV", seeds = seeds)
rctrl3 <- trainControl(method = "oob", seeds = seeds)
rctrl4 <- trainControl(method = "none", seeds = seeds)
rctrlR <- trainControl(method = "cv", number = 3, returnResamp = "all", search = "random")
set.seed(849)
test_reg_cv_model <- train(trainX, trainY,
method = "Rborist",
trControl = rctrl1,
preProc = c("center", "scale"),
nTree = 21)
test_reg_pred <- predict(test_reg_cv_model, testX)
set.seed(849)
test_reg_cv_form <- train(y ~ ., data = training,
method = "Rborist",
trControl = rctrl1,
preProc = c("center", "scale"),
nTree = 21)
test_reg_pred_form <- predict(test_reg_cv_form, testX)
set.seed(849)
test_reg_loo_model <- train(trainX, trainY,
method = "Rborist",
trControl = rctrl2,
preProc = c("center", "scale"),
nTree = 21)
set.seed(849)
test_reg_rand <- train(trainX, trainY,
method = "Rborist",
trControl = rctrlR,
tuneLength = 4,
nTree = 21)
set.seed(849)
test_reg_oob_model <- train(trainX, trainY,
method = "Rborist",
trControl = rctrl3,
preProc = c("center", "scale"),
nTree = 21)
set.seed(849)
test_reg_none_model <- train(trainX, trainY,
method = "Rborist",
trControl = rctrl4,
tuneGrid = test_reg_cv_model$bestTune,
preProc = c("center", "scale"),
nTree = 21)
test_reg_none_pred <- predict(test_reg_none_model, testX)
set.seed(849)
test_reg_rec <- train(recipe = rec_reg,
data = training,
method = "Rborist",
trControl = rctrl1,
nTree = 21)
if(
!isTRUE(
all.equal(test_reg_cv_model$results,
test_reg_rec$results))
)
stop("CV weights not giving the same results")
test_reg_pred_rec <- predict(test_reg_rec, testing[, -ncol(testing)])
#########################################################################
test_class_predictors1 <- predictors(test_class_cv_model)
test_reg_predictors1 <- predictors(test_reg_cv_model)
#########################################################################
test_class_imp <- varImp(test_class_cv_model)
test_reg_imp <- varImp(test_reg_cv_model)
#########################################################################
tests <- grep("test_", ls(), fixed = TRUE, value = TRUE)
sInfo <- sessionInfo()
timestamp_end <- Sys.time()
save(list = c(tests, "sInfo", "timestamp", "timestamp_end"),
file = file.path(getwd(), paste(model, ".RData", sep = "")))
q("no")
|
/RegressionTests/Code/Rborist.R
|
no_license
|
Weekend-Warrior/caret
|
R
| false | false | 8,069 |
r
|
timestamp <- Sys.time()
library(caret)
library(plyr)
library(recipes)
library(dplyr)
model <- "Rborist"
## In case the package or one of its dependencies uses random numbers
## on startup so we'll pre-load the required libraries:
for(i in getModelInfo(model)[[1]]$library)
do.call("require", list(package = i))
#########################################################################
set.seed(2)
training <- twoClassSim(50, linearVars = 2)
testing <- twoClassSim(500, linearVars = 2)
trainX <- training[, -ncol(training)]
trainY <- training$Class
rec_cls <- recipe(Class ~ ., data = training) %>%
step_center(all_predictors()) %>%
step_scale(all_predictors())
seeds <- vector(mode = "list", length = nrow(training) + 1)
seeds <- lapply(seeds, function(x) 1:20)
cctrl1 <- trainControl(method = "cv", number = 3, returnResamp = "all",
classProbs = TRUE,
summaryFunction = twoClassSummary,
seeds = seeds)
cctrl2 <- trainControl(method = "LOOCV",
classProbs = TRUE, summaryFunction = twoClassSummary,
seeds = seeds)
cctrl3 <- trainControl(method = "oob",
seeds = seeds)
cctrl4 <- trainControl(method = "none",
classProbs = TRUE, summaryFunction = twoClassSummary,
seeds = seeds)
cctrlR <- trainControl(method = "cv", number = 3, returnResamp = "all", search = "random")
set.seed(849)
test_class_cv_model <- train(trainX, trainY,
method = "Rborist",
trControl = cctrl1,
metric = "ROC",
preProc = c("center", "scale"),
nTree = 21)
set.seed(849)
test_class_cv_form <- train(Class ~ ., data = training,
method = "Rborist",
trControl = cctrl1,
metric = "ROC",
preProc = c("center", "scale"),
nTree = 21)
test_class_pred <- predict(test_class_cv_model, testing[, -ncol(testing)])
test_class_prob <- predict(test_class_cv_model, testing[, -ncol(testing)], type = "prob")
test_class_pred_form <- predict(test_class_cv_form, testing[, -ncol(testing)])
test_class_prob_form <- predict(test_class_cv_form, testing[, -ncol(testing)], type = "prob")
set.seed(849)
test_class_loo_model <- train(trainX, trainY,
method = "Rborist",
trControl = cctrl2,
metric = "ROC",
preProc = c("center", "scale"),
nTree = 21)
test_levels <- levels(test_class_cv_model)
if(!all(levels(trainY) %in% test_levels))
cat("wrong levels")
set.seed(849)
test_class_rand <- train(trainX, trainY,
method = "Rborist",
trControl = cctrlR,
tuneLength = 4,
nTree = 21)
set.seed(849)
test_class_oob_model <- train(trainX, trainY,
method = "Rborist",
trControl = cctrl3,
nTree = 21)
set.seed(849)
test_class_none_model <- train(trainX, trainY,
method = "Rborist",
trControl = cctrl4,
tuneGrid = test_class_cv_model$bestTune,
metric = "ROC",
preProc = c("center", "scale"),
nTree = 21)
test_class_none_pred <- predict(test_class_none_model, testing[, -ncol(testing)])
test_class_none_prob <- predict(test_class_none_model, testing[, -ncol(testing)], type = "prob")
set.seed(849)
test_class_rec <- train(recipe = rec_cls,
data = training,
method = "Rborist",
trControl = cctrl1,
metric = "ROC",
nTree = 21)
if(
!isTRUE(
all.equal(test_class_cv_model$results,
test_class_rec$results))
)
stop("CV weights not giving the same results")
test_class_pred_rec <- predict(test_class_rec, testing[, -ncol(testing)])
test_class_prob_rec <- predict(test_class_rec, testing[, -ncol(testing)],
type = "prob")
#########################################################################
library(caret)
library(plyr)
library(recipes)
library(dplyr)
set.seed(1)
training <- SLC14_1(30)
testing <- SLC14_1(100)
trainX <- training[, -ncol(training)]
trainY <- training$y
rec_reg <- recipe(y ~ ., data = training) %>%
step_center(all_predictors()) %>%
step_scale(all_predictors())
testX <- trainX[, -ncol(training)]
testY <- trainX$y
rctrl1 <- trainControl(method = "cv", number = 3, returnResamp = "all", seeds = seeds)
rctrl2 <- trainControl(method = "LOOCV", seeds = seeds)
rctrl3 <- trainControl(method = "oob", seeds = seeds)
rctrl4 <- trainControl(method = "none", seeds = seeds)
rctrlR <- trainControl(method = "cv", number = 3, returnResamp = "all", search = "random")
set.seed(849)
test_reg_cv_model <- train(trainX, trainY,
method = "Rborist",
trControl = rctrl1,
preProc = c("center", "scale"),
nTree = 21)
test_reg_pred <- predict(test_reg_cv_model, testX)
set.seed(849)
test_reg_cv_form <- train(y ~ ., data = training,
method = "Rborist",
trControl = rctrl1,
preProc = c("center", "scale"),
nTree = 21)
test_reg_pred_form <- predict(test_reg_cv_form, testX)
set.seed(849)
test_reg_loo_model <- train(trainX, trainY,
method = "Rborist",
trControl = rctrl2,
preProc = c("center", "scale"),
nTree = 21)
set.seed(849)
test_reg_rand <- train(trainX, trainY,
method = "Rborist",
trControl = rctrlR,
tuneLength = 4,
nTree = 21)
set.seed(849)
test_reg_oob_model <- train(trainX, trainY,
method = "Rborist",
trControl = rctrl3,
preProc = c("center", "scale"),
nTree = 21)
set.seed(849)
test_reg_none_model <- train(trainX, trainY,
method = "Rborist",
trControl = rctrl4,
tuneGrid = test_reg_cv_model$bestTune,
preProc = c("center", "scale"),
nTree = 21)
test_reg_none_pred <- predict(test_reg_none_model, testX)
set.seed(849)
test_reg_rec <- train(recipe = rec_reg,
data = training,
method = "Rborist",
trControl = rctrl1,
nTree = 21)
if(
!isTRUE(
all.equal(test_reg_cv_model$results,
test_reg_rec$results))
)
stop("CV weights not giving the same results")
test_reg_pred_rec <- predict(test_reg_rec, testing[, -ncol(testing)])
#########################################################################
test_class_predictors1 <- predictors(test_class_cv_model)
test_reg_predictors1 <- predictors(test_reg_cv_model)
#########################################################################
test_class_imp <- varImp(test_class_cv_model)
test_reg_imp <- varImp(test_reg_cv_model)
#########################################################################
tests <- grep("test_", ls(), fixed = TRUE, value = TRUE)
sInfo <- sessionInfo()
timestamp_end <- Sys.time()
save(list = c(tests, "sInfo", "timestamp", "timestamp_end"),
file = file.path(getwd(), paste(model, ".RData", sep = "")))
q("no")
|
# #The goal of this script is to run enrichment analysi on the leading edges of different clusters
listOfFiles = list.files("03_extractedData/190321_KO-RNAseq/GSEA/leadingEdges/")
#Load transcriptome and keep only genes expressed in at least one sample.
expressedTranscriptome = read.table("01_rawData/190321_KO-RNAseq/normalizedCounts/rpmCounts_allRuns_matrix.tsv", header = T)
expressedTranscriptome[is.na(expressedTranscriptome)] = 0
expressedTranscriptome = expressedTranscriptome[rowSums(expressedTranscriptome[3:ncol(expressedTranscriptome)]) > 0, ]
#generate background and convert names
background = as.character(expressedTranscriptome$GeneSymbol)
background = bitr(background, fromType="SYMBOL", toType=("ENTREZID"), OrgDb="org.Hs.eg.db")
for(currentFile in listOfFiles) {
# #For testing
# currentFile = listOfFiles[2]
#Remove ".txt" to use base of name for file names
currentFile_baseName = strsplit(currentFile, ".txt")
#Load leading edge genes
leadingEdge = read.table(paste("03_extractedData/190321_KO-RNAseq/GSEA/leadingEdges/", currentFile, sep = ""), sep = "\t")
#convert names of the leading edge
leadingEdge = bitr(leadingEdge$V1, fromType="SYMBOL", toType=("ENTREZID"), OrgDb="org.Hs.eg.db")
#compute enrichment analysis - upregulated genes
ego1 <- enrichGO(gene = leadingEdge$ENTREZID,
universe = background$ENTREZID,
OrgDb = org.Hs.eg.db,
ont = "BP",
pAdjustMethod = "fdr",
pvalueCutoff = 1,
qvalueCutoff = 0.25,
readable = TRUE)
ego1.df = data.frame(ego1)
rownames(ego1.df) = NULL
newFileName_GO = paste("03_extractedData/190321_KO-RNAseq/GSEA/enrichmentAnalysisFromClusters/", currentFile_baseName[[1]][1], "_GOenrichment.txt", sep = "")
write.table(ego1.df, file = newFileName_GO, sep = "\t", col.names = TRUE, row.names = FALSE, quote = FALSE)
kk <- enrichKEGG(gene = leadingEdge$ENTREZID,
organism = 'hsa',
pvalueCutoff = 0.25)
kk.df = data.frame(kk)
newFileName_KEGG = paste("03_extractedData/190321_KO-RNAseq/GSEA/enrichmentAnalysisFromClusters/", currentFile_baseName[[1]][1], "_KEGGenrichment.txt", sep = "")
write.table(kk.df, file = newFileName_KEGG, sep = "\t", col.names = TRUE, row.names = FALSE, quote = FALSE)
}
|
/05_scripts/190321_KO-RNAseq/190408_runClusterProfilerOnLeadingEdges.R
|
no_license
|
edatorre/2020_TorreEtAl_data
|
R
| false | false | 2,441 |
r
|
# #The goal of this script is to run enrichment analysi on the leading edges of different clusters
listOfFiles = list.files("03_extractedData/190321_KO-RNAseq/GSEA/leadingEdges/")
#Load transcriptome and keep only genes expressed in at least one sample.
expressedTranscriptome = read.table("01_rawData/190321_KO-RNAseq/normalizedCounts/rpmCounts_allRuns_matrix.tsv", header = T)
expressedTranscriptome[is.na(expressedTranscriptome)] = 0
expressedTranscriptome = expressedTranscriptome[rowSums(expressedTranscriptome[3:ncol(expressedTranscriptome)]) > 0, ]
#generate background and convert names
background = as.character(expressedTranscriptome$GeneSymbol)
background = bitr(background, fromType="SYMBOL", toType=("ENTREZID"), OrgDb="org.Hs.eg.db")
for(currentFile in listOfFiles) {
# #For testing
# currentFile = listOfFiles[2]
#Remove ".txt" to use base of name for file names
currentFile_baseName = strsplit(currentFile, ".txt")
#Load leading edge genes
leadingEdge = read.table(paste("03_extractedData/190321_KO-RNAseq/GSEA/leadingEdges/", currentFile, sep = ""), sep = "\t")
#convert names of the leading edge
leadingEdge = bitr(leadingEdge$V1, fromType="SYMBOL", toType=("ENTREZID"), OrgDb="org.Hs.eg.db")
#compute enrichment analysis - upregulated genes
ego1 <- enrichGO(gene = leadingEdge$ENTREZID,
universe = background$ENTREZID,
OrgDb = org.Hs.eg.db,
ont = "BP",
pAdjustMethod = "fdr",
pvalueCutoff = 1,
qvalueCutoff = 0.25,
readable = TRUE)
ego1.df = data.frame(ego1)
rownames(ego1.df) = NULL
newFileName_GO = paste("03_extractedData/190321_KO-RNAseq/GSEA/enrichmentAnalysisFromClusters/", currentFile_baseName[[1]][1], "_GOenrichment.txt", sep = "")
write.table(ego1.df, file = newFileName_GO, sep = "\t", col.names = TRUE, row.names = FALSE, quote = FALSE)
kk <- enrichKEGG(gene = leadingEdge$ENTREZID,
organism = 'hsa',
pvalueCutoff = 0.25)
kk.df = data.frame(kk)
newFileName_KEGG = paste("03_extractedData/190321_KO-RNAseq/GSEA/enrichmentAnalysisFromClusters/", currentFile_baseName[[1]][1], "_KEGGenrichment.txt", sep = "")
write.table(kk.df, file = newFileName_KEGG, sep = "\t", col.names = TRUE, row.names = FALSE, quote = FALSE)
}
|
% Generated by roxygen2 (4.1.0): do not edit by hand
% Please edit documentation in R/gaussAlgebra.R
\name{linear.gAlg}
\alias{linear.gAlg}
\title{Generates a linear gAlg function}
\usage{
linear.gAlg(k, d = 1)
}
\arguments{
\item{k}{Index of the dimension in which the function is linear}
\item{d}{Dimension in which the function lives}
}
\description{
Creates a gAlg function representing: f(x1,x2,...xd) = xk
}
|
/man/linear.gAlg.Rd
|
no_license
|
kmarchlewski/gaussAlgebra
|
R
| false | false | 416 |
rd
|
% Generated by roxygen2 (4.1.0): do not edit by hand
% Please edit documentation in R/gaussAlgebra.R
\name{linear.gAlg}
\alias{linear.gAlg}
\title{Generates a linear gAlg function}
\usage{
linear.gAlg(k, d = 1)
}
\arguments{
\item{k}{Index of the dimension in which the function is linear}
\item{d}{Dimension in which the function lives}
}
\description{
Creates a gAlg function representing: f(x1,x2,...xd) = xk
}
|
# simulate gaussian rv with correlation 0.5
simulate_x = function(){
cov = matrix(c(1,0.5,0.5,1),nrow=2)
A = t(chol(cov))
e = matrix(rnorm(2),nrow=2)
x = A %*% rnorm(2)
x
}
simulate_path=function(){
T = 365-1
x1 = vector();x2 = vector()
for(i in 1:T){
x = simulate_x()
x1 = c(x1,x[1])
x2 = c(x2,x[2])
}
x = data.frame(x1,x2)
x
}
Revenue = function(){
T = 365
delta_t = 1
h = 0.4
Y = 200*20
n = 50
x=simulate_path()
x1 = x$x1
x2 = x$x2
k = 40000
# initialize
s = vector()
r = vector()
payoff = vector()
PE = vector()
PG = vector()
PE[1] = 20
PG[1] = 24
s[1] = 20-h*24
r[1] = s[1]*Y
payoff[1] = max((k-r[1]),0)
for(i in 1:(T-1)){
PE[i+1] = PE[i]+(0.75*(32-PE[i])-0.29*0.5*PE[i])*delta_t+0.5*PE[i]*x1[i]
PG[i+1] = PG[i]+(0.15*(40-PG[i])-0.175*0.6*PG[i])*delta_t+0.6*PG[i]*x2[i]
s[i+1] = PE[i+1]-h*PG[i+1]
prob = runif(1)
if(s[i+1]>0)
{
if(prob>0.05*exp(-0.7*abs(s[i+1])))
r[i+1] = s[i+1]*Y
else r[i+1] = 0
}
else{
if(prob<0.05*exp(-0.7*abs(s[i+1])))
r[i+1] = s[i+1]*Y
else r[i+1] = 0
}
payoff[i+1] = max((k-r[i+1]),0)
}
df = data.frame(s,r,payoff)
df
}
keke = function(n){
total = vector()
not_operate = vector()
less_than_40K = vector()
payoff1 = vector()
for(i in 1:n){
df = Revenue()
if(i%%100==0)
print(c('i=',i))
payoff1[i] = mean(df$payoff)
}
payoff1
}
|
/StochasticProcess/question4.R
|
no_license
|
fushuyue/Financial_Computing
|
R
| false | false | 1,371 |
r
|
# simulate gaussian rv with correlation 0.5
simulate_x = function(){
cov = matrix(c(1,0.5,0.5,1),nrow=2)
A = t(chol(cov))
e = matrix(rnorm(2),nrow=2)
x = A %*% rnorm(2)
x
}
simulate_path=function(){
T = 365-1
x1 = vector();x2 = vector()
for(i in 1:T){
x = simulate_x()
x1 = c(x1,x[1])
x2 = c(x2,x[2])
}
x = data.frame(x1,x2)
x
}
Revenue = function(){
T = 365
delta_t = 1
h = 0.4
Y = 200*20
n = 50
x=simulate_path()
x1 = x$x1
x2 = x$x2
k = 40000
# initialize
s = vector()
r = vector()
payoff = vector()
PE = vector()
PG = vector()
PE[1] = 20
PG[1] = 24
s[1] = 20-h*24
r[1] = s[1]*Y
payoff[1] = max((k-r[1]),0)
for(i in 1:(T-1)){
PE[i+1] = PE[i]+(0.75*(32-PE[i])-0.29*0.5*PE[i])*delta_t+0.5*PE[i]*x1[i]
PG[i+1] = PG[i]+(0.15*(40-PG[i])-0.175*0.6*PG[i])*delta_t+0.6*PG[i]*x2[i]
s[i+1] = PE[i+1]-h*PG[i+1]
prob = runif(1)
if(s[i+1]>0)
{
if(prob>0.05*exp(-0.7*abs(s[i+1])))
r[i+1] = s[i+1]*Y
else r[i+1] = 0
}
else{
if(prob<0.05*exp(-0.7*abs(s[i+1])))
r[i+1] = s[i+1]*Y
else r[i+1] = 0
}
payoff[i+1] = max((k-r[i+1]),0)
}
df = data.frame(s,r,payoff)
df
}
keke = function(n){
total = vector()
not_operate = vector()
less_than_40K = vector()
payoff1 = vector()
for(i in 1:n){
df = Revenue()
if(i%%100==0)
print(c('i=',i))
payoff1[i] = mean(df$payoff)
}
payoff1
}
|
\name{PKMW}
\alias{PKMW}
\title{Presmoothed Kaplan-Meier weights}
\description{This function returns a vector with the presmoothed Kaplan-Meier weights.}
\usage{
PKMW(time, status)
}
\arguments{
\item{time}{ Survival time of the process.}
\item{status}{Censoring indicator of the survival time of the process; 0 if the survival time is censored and 1 otherwise. }
}
\value{ Vector with presmoothed Kaplan-Meier weights. }
\references{
R. Cao, I. Lopez-de Ullibarri, P. Janssen, and N. Veraverbeke. Presmoothed kaplan-meier and nelsonaalen
estimators. Journal of Nonparametric Statistics, 17:31-56, 2005.
G. Dikta. On semiparametric random censorship models. Journal of Statistical Planning and Inference,
66:253-279, 1998.
E. Kaplan and P. Meier. Nonparametric estimation from incomplete observations. Journal of the
American Statistical Association, 53:457-481, 1958.
}
\author{Luis Meira-Machado, Marta Sestelo and Gustavo Soutinho.}
\seealso{\code{\link{KMW}}}
\examples{
obj <- with(colonIDM, survIDM(time1, event1, Stime, event))
PKMW(time = obj$Stime, status = obj$event)
}
|
/man/PKMW.Rd
|
no_license
|
sestelo/survidm
|
R
| false | false | 1,095 |
rd
|
\name{PKMW}
\alias{PKMW}
\title{Presmoothed Kaplan-Meier weights}
\description{This function returns a vector with the presmoothed Kaplan-Meier weights.}
\usage{
PKMW(time, status)
}
\arguments{
\item{time}{ Survival time of the process.}
\item{status}{Censoring indicator of the survival time of the process; 0 if the survival time is censored and 1 otherwise. }
}
\value{ Vector with presmoothed Kaplan-Meier weights. }
\references{
R. Cao, I. Lopez-de Ullibarri, P. Janssen, and N. Veraverbeke. Presmoothed kaplan-meier and nelsonaalen
estimators. Journal of Nonparametric Statistics, 17:31-56, 2005.
G. Dikta. On semiparametric random censorship models. Journal of Statistical Planning and Inference,
66:253-279, 1998.
E. Kaplan and P. Meier. Nonparametric estimation from incomplete observations. Journal of the
American Statistical Association, 53:457-481, 1958.
}
\author{Luis Meira-Machado, Marta Sestelo and Gustavo Soutinho.}
\seealso{\code{\link{KMW}}}
\examples{
obj <- with(colonIDM, survIDM(time1, event1, Stime, event))
PKMW(time = obj$Stime, status = obj$event)
}
|
# How have emissions from
# motor vehicle sources changed from 1999–2008 in Baltimore City?
# Read the data
setwd("~/40 L&G/Coursera/ExDataAnalysis/Project2")
if (!exists("NEI")) {
# Emissions Data
NEI <- readRDS(paste0(getwd() ,"/Data/summarySCC_PM25.rds"))
}
if (!exists("SCC")) {
# Source Classification Code Table
SCC <- readRDS(paste0(getwd() ,"/Data/Source_Classification_Code.rds"))
}
# Select the SCC codes for vehicle sources
library(dplyr)
vehicles <- SCC %>%
filter(grepl("Mobile", x = SCC.Level.One ,ignore.case = TRUE)) %>%
filter(grepl("vehicle", x = Short.Name, ignore.case = TRUE)) %>%
select(SCC,Short.Name)
#Convert to a vector to use in the filter
vehicles <- vehicles %>% .$SCC
# Start the png driver
png(filename= paste0("plot6.png"), height=295, width=600, bg="white")
# Prepare Data for plot
df <- NEI %>% select(Emissions, year, fips, SCC) %>%
filter(SCC %in% vehicles) %>%
filter(fips == "24510") %>%
group_by(year) %>%
summarise(Total = sum(Emissions))
library(ggplot2)
qplot(x = year, y = Total,
data = df,
geom = c("point", "line"),
xlab="Year",
ylab = "Tons of PM2.5",
main = "Total Annual Vehicle Related Emissions \n Baltimore City, Maryland")
# Export the plot
dev.off()
|
/plot6.R
|
no_license
|
Kbushu/Pollution
|
R
| false | false | 1,342 |
r
|
# How have emissions from
# motor vehicle sources changed from 1999–2008 in Baltimore City?
# Read the data
setwd("~/40 L&G/Coursera/ExDataAnalysis/Project2")
if (!exists("NEI")) {
# Emissions Data
NEI <- readRDS(paste0(getwd() ,"/Data/summarySCC_PM25.rds"))
}
if (!exists("SCC")) {
# Source Classification Code Table
SCC <- readRDS(paste0(getwd() ,"/Data/Source_Classification_Code.rds"))
}
# Select the SCC codes for vehicle sources
library(dplyr)
vehicles <- SCC %>%
filter(grepl("Mobile", x = SCC.Level.One ,ignore.case = TRUE)) %>%
filter(grepl("vehicle", x = Short.Name, ignore.case = TRUE)) %>%
select(SCC,Short.Name)
#Convert to a vector to use in the filter
vehicles <- vehicles %>% .$SCC
# Start the png driver
png(filename= paste0("plot6.png"), height=295, width=600, bg="white")
# Prepare Data for plot
df <- NEI %>% select(Emissions, year, fips, SCC) %>%
filter(SCC %in% vehicles) %>%
filter(fips == "24510") %>%
group_by(year) %>%
summarise(Total = sum(Emissions))
library(ggplot2)
qplot(x = year, y = Total,
data = df,
geom = c("point", "line"),
xlab="Year",
ylab = "Tons of PM2.5",
main = "Total Annual Vehicle Related Emissions \n Baltimore City, Maryland")
# Export the plot
dev.off()
|
# SVR
# Importing the dataset
dataset = read.csv('Position_Salaries.csv')
dataset = dataset[2:3]
# Splitting the dataset into the Training set and Test set
# # install.packages('caTools')
# library(caTools)
# set.seed(123)
# split = sample.split(dataset$Salary, SplitRatio = 2/3)
# training_set = subset(dataset, split == TRUE)
# test_set = subset(dataset, split == FALSE)
# Feature Scaling
# training_set = scale(training_set)
# test_set = scale(test_set)
# Fitting SVR to the dataset
#install.packages('e1071')
library(e1071)
regressor = svm(formula = Salary ~ .,
data = dataset,
type = 'eps-regression',
kernel = 'radial')
# Predicting a new result
y_pred = predict(regressor, data.frame(Level = 6.5))
# Visualising the SVR results
# install.packages('ggplot2')
library(ggplot2)
ggplot() +
geom_point(aes(x = dataset$Level, y = dataset$Salary),
colour = 'red') +
geom_line(aes(x = dataset$Level, y = predict(regressor, newdata = dataset)),
colour = 'blue') +
ggtitle('Truth or Bluff (SVR)') +
xlab('Level') +
ylab('Salary')
# Visualising the SVR results (for higher resolution and smoother curve)
# install.packages('ggplot2')
library(ggplot2)
x_grid = seq(min(dataset$Level), max(dataset$Level), 0.1)
ggplot() +
geom_point(aes(x = dataset$Level, y = dataset$Salary),
colour = 'red') +
geom_line(aes(x = x_grid, y = predict(regressor, newdata = data.frame(Level = x_grid))),
colour = 'blue') +
ggtitle('Truth or Bluff (SVR)') +
xlab('Level') +
ylab('Salary')
|
/Machine Learning A-Z- Udemy/Part 2 - Regression/Section 7 - Support Vector Regression (SVR)/svr.R
|
no_license
|
95anantsingh/Udemy-ML-A-Z
|
R
| false | false | 1,586 |
r
|
# SVR
# Importing the dataset
dataset = read.csv('Position_Salaries.csv')
dataset = dataset[2:3]
# Splitting the dataset into the Training set and Test set
# # install.packages('caTools')
# library(caTools)
# set.seed(123)
# split = sample.split(dataset$Salary, SplitRatio = 2/3)
# training_set = subset(dataset, split == TRUE)
# test_set = subset(dataset, split == FALSE)
# Feature Scaling
# training_set = scale(training_set)
# test_set = scale(test_set)
# Fitting SVR to the dataset
#install.packages('e1071')
library(e1071)
regressor = svm(formula = Salary ~ .,
data = dataset,
type = 'eps-regression',
kernel = 'radial')
# Predicting a new result
y_pred = predict(regressor, data.frame(Level = 6.5))
# Visualising the SVR results
# install.packages('ggplot2')
library(ggplot2)
ggplot() +
geom_point(aes(x = dataset$Level, y = dataset$Salary),
colour = 'red') +
geom_line(aes(x = dataset$Level, y = predict(regressor, newdata = dataset)),
colour = 'blue') +
ggtitle('Truth or Bluff (SVR)') +
xlab('Level') +
ylab('Salary')
# Visualising the SVR results (for higher resolution and smoother curve)
# install.packages('ggplot2')
library(ggplot2)
x_grid = seq(min(dataset$Level), max(dataset$Level), 0.1)
ggplot() +
geom_point(aes(x = dataset$Level, y = dataset$Salary),
colour = 'red') +
geom_line(aes(x = x_grid, y = predict(regressor, newdata = data.frame(Level = x_grid))),
colour = 'blue') +
ggtitle('Truth or Bluff (SVR)') +
xlab('Level') +
ylab('Salary')
|
#Sam Smedinghoff
#7/27/18
#Week 3 - Lab 3
library(SDSFoundations)
post <- PostSurvey
#Question 1
post$hw_hours_diff <- post$hw_hours_HS - post$hw_hours_college
hist(post$hw_hours_diff)
t.test(post$hw_hours_HS,post$hw_hours_college,paired=T,alternative='less')
#Question 2
sleep_greek <- post$sleep_Sat[post$greek == 'yes']
sleep_nongreek <- post$sleep_Sat[post$greek == 'no']
t.test(sleep_greek,sleep_nongreek,alternative='less')
hist(sleep_greek)
hist(sleep_nongreek)
|
/FDA2/lab03.R
|
no_license
|
smeds1/Learning
|
R
| false | false | 490 |
r
|
#Sam Smedinghoff
#7/27/18
#Week 3 - Lab 3
library(SDSFoundations)
post <- PostSurvey
#Question 1
post$hw_hours_diff <- post$hw_hours_HS - post$hw_hours_college
hist(post$hw_hours_diff)
t.test(post$hw_hours_HS,post$hw_hours_college,paired=T,alternative='less')
#Question 2
sleep_greek <- post$sleep_Sat[post$greek == 'yes']
sleep_nongreek <- post$sleep_Sat[post$greek == 'no']
t.test(sleep_greek,sleep_nongreek,alternative='less')
hist(sleep_greek)
hist(sleep_nongreek)
|
checkInputVars <- function (normalizescheme, normalclasswise, replaceNA, replaceclasswise, orglabellvls) {
errors <- vector()
if (!any(normalizescheme == c('none','ztransform', 'iqr', 'sumone'))| length(normalizescheme) != 1) {
errors[length(errors) + 1] <- 3
}
if ((!any(normalclasswise == orglabellvls) & normalclasswise != 'none') | length(normalclasswise) != 1) {
errors[length(errors) + 1] <- 4
}
if (class(replaceNA) != 'logical' | length(replaceNA) != 1) {
errors[length(errors) + 1] <- 5
}
if (class(replaceclasswise) != 'logical' | length(replaceclasswise) != 1) {
errors[length(errors) + 1] <- 6
}
if (length(errors) > 0) {
error(errors)
}
}
checkLVQvars <- function (prototypes, learningrate, epochs, initscheme, distscheme, relevancemode, relevancescheme, LVQscheme, optimisationscheme, relrate, customdist, alfa, show, graphics, plotcurve, labellvls, dimensions) {
errors <- vector()
if (length(prototypes) != length(labellvls) | any(is.na(prototypes[labellvls]))) {
errors[length(errors) + 1] <- 7
}
if (!any(class(prototypes) == c('numeric', 'integer'))) {
errors[length(errors) + 1] <- 8
}
if (any(class(prototypes) == c('numeric', 'integer'))) {
if (any(prototypes <= 0) | any(prototypes %% 1 != 0)) {
errors[length(errors) + 1] <- 9
}
}
if (epochs <= 0 | epochs %% 1 != 0) {
errors[length(errors) + 1] <- 10
}
if (class(learningrate) != 'numeric' | (length(learningrate) != 1 & length(learningrate) != epochs)) {
errors[length(errors) + 1] <- 11
}
if (class(learningrate) == 'numeric') {
if (any(learningrate <= 0) | any(learningrate >= 1)) {
errors[length(errors) + 1] <- 12
}
}
if (class(relrate) != 'numeric' | (length(relrate) != 1 & length(relrate) != epochs)) {
errors[length(errors) + 1] <- 13
}
if (class(relrate) == 'numeric') {
if (any(relrate <= 0) | any(relrate >= 1)) {
errors[length(errors) + 1] <- 14
}
}
if (!any(initscheme == c('randomwindow', 'zero', 'randomsample', 'mean', 'classmean')) | length(initscheme) != 1) {
errors[length(errors) + 1] <- 15
}
if (!any(distscheme == c('euclidean', 'manhattan', 'custom')) | length(distscheme) != 1) {
errors[length(errors) + 1] <- 16
}
if (!any(relevancemode == c('normal', 'relevance', 'matrix')) | length(relevancemode) != 1) {
errors[length(errors) + 1] <- 17
}
if (!any(LVQscheme == c('LVQ1', 'cauchyschwarz', 'renyi')) | length(LVQscheme) != 1) {
errors[length(errors) + 1] <- 18
}
if (!any(class(customdist) == c('numeric', 'integer')) | length(customdist) != 1) {
errors[length(errors) + 1] <- 19
}
if (any(class(customdist) == c('numeric', 'integer'))) {
if (customdist < 1) {
errors[length(errors) + 1] <- 20
}
}
if (class(show) != 'logical' | length(show) != 1) {
errors[length(errors) + 1] <- 21
}
if (class(graphics) != 'logical' | length(graphics) != 1) {
errors[length(errors) + 1] <- 22
}
if (class(graphics) == 'logical' & dimensions != 2) {
if (graphics) {
errors[length(errors) + 1] <- 23
}
}
if (class(plotcurve) != 'logical' | length(plotcurve) != 1) {
errors[length(errors) + 1] <- 25
}
if (!any(class(alfa) == c('numeric', 'integer')) | length(alfa) != 1) {
errors[length(errors) + 1] <- 73
}
if (any(class(alfa) == c('numeric', 'integer'))) {
if (alfa <= 1) {
errors[length(errors) + 1] <- 74
}
}
if (!any(optimisationscheme == c('normal', 'general')) | length(optimisationscheme) != 1) {
errors[length(errors) + 1] <- 75
}
if (any(LVQscheme == c('cauchyschwarz', 'renyi')) & any(initscheme == c('zero'))){
errors[length(errors) + 1] <- 76
}
if (!any(relevancescheme == c('global', 'local', 'classwise')) | length(relevancescheme) != 1) {
errors[length(errors) + 1] <- 87
}
if (any(relevancemode == c('relevance', 'matrix')) & any(LVQscheme == c('cauchyschwarz', 'renyi'))) {
errors[length(errors) + 1] <- 94
}
if (length(errors) > 0) {
error(errors)
}
}
checkValidateVars <- function (validatescheme, nfold, nrdatapoints) {
errors <- vector()
if (!any(validatescheme == c('traintest', 'nfold', 'train')) | length(validatescheme) != 1) {
errors[length(errors) + 1] <- 26
}
if (!any(class(nfold) == c('numeric', 'integer')) | length(nfold) != 1) {
errors[length(errors) + 1] <- 27
}
if (any(class(nfold) == c('numeric', 'integer'))) {
if (validatescheme == 'nfold' & (nfold <= 1 | nfold %% 1 != 0 | nfold > nrdatapoints)) {
errors[length(errors) + 1] <- 28
}
}
if (length(errors) > 0) {
error(errors)
}
}
checkOutputVars <- function (prototypeoutput, relevanceoutput, costcurve, progress, relevanceprogress, trainerror, testerror, trainerrorprogress, testerrorprogress, validatescheme, relevancemode) {
errors <- vector()
if (class(prototypeoutput) != 'logical' | length(prototypeoutput) != 1) {
errors[length(errors) + 1] <- 31
}
if (class(relevanceoutput) != 'logical' | length(relevanceoutput) != 1) {
errors[length(errors) + 1] <- 32
}
if (class(relevanceoutput) == 'logical' & relevancemode != 'relevance' & relevancemode != 'matrix') {
if (relevanceoutput) {
errors[length(errors) + 1] <- 33
}
}
if (class(costcurve) != 'logical' | length(costcurve) != 1) {
errors[length(errors) + 1] <- 34
}
if (class(progress) != 'logical' | length(progress) != 1) {
errors[length(errors) + 1] <- 35
}
if (class(relevanceprogress) != 'logical' | length(relevanceprogress) != 1) {
errors[length(errors) + 1] <- 36
}
if (class(relevanceprogress) == 'logical' & relevancemode != 'relevance' & relevancemode != 'matrix') {
if (relevanceprogress) {
errors[length(errors) + 1] <- 37
}
}
if (class(testerror) != 'logical' | length(testerror) != 1) {
errors[length(errors) + 1] <- 38
}
if (class(testerror) == 'logical' & validatescheme != 'traintest' & validatescheme != 'nfold') {
if (testerror) {
errors[length(errors) + 1] <- 39
}
}
if (class(trainerror) != 'logical' | length(trainerror) != 1) {
errors[length(errors) + 1] <- 59
}
if (class(testerrorprogress) != 'logical' | length(testerrorprogress) != 1) {
errors[length(errors) + 1] <- 62
}
if (class(testerrorprogress) == 'logical' & validatescheme != 'traintest' & validatescheme != 'nfold') {
if (testerrorprogress) {
errors[length(errors) + 1] <- 63
}
}
if (class(trainerrorprogress) != 'logical' | length(trainerrorprogress) != 1) {
errors[length(errors) + 1] <- 64
}
if (length(errors) > 0) {
error(errors)
}
}
checkShowVars <- function(LVQoutput, prototypes, relevances, costcurve, prototypeprogress, relevanceprogress, trainerror, testerror, trainerrorprogress, testerrorprogress, relevancenumber, relevanceprognumber) {
errors <- vector()
if (!any(class(LVQoutput) == c('trainoutput', 'traintestoutput', 'nfoldoutput'))) {
errors[length(errors) + 1] <- 40
}
if (class(prototypes) != 'logical' | length(prototypes) != 1) {
errors[length(errors) + 1] <- 77
}
if (class(relevances) != 'logical' | length(relevances) != 1) {
errors[length(errors) + 1] <- 41
}
if (class(costcurve) != 'logical' | length(costcurve) != 1) {
errors[length(errors) + 1] <- 42
}
if (class(prototypeprogress) != 'logical' | length(prototypeprogress) != 1) {
errors[length(errors) + 1] <- 78
}
if (class(relevanceprogress) != 'logical' | length(relevanceprogress) != 1) {
errors[length(errors) + 1] <- 43
}
if (class(testerror) != 'logical' | length(testerror) != 1) {
errors[length(errors) + 1] <- 44
}
if (class(relevances) == 'logical' & length(relevances) == 1) {
if (relevances & length(attr(LVQoutput, 'relevances')) == 0) {
errors[length(errors) + 1] <- 45
}
}
if (class(costcurve) == 'logical' & length(costcurve) == 1) {
if (costcurve & length(attr(LVQoutput, 'costcurve')) == 0) {
errors[length(errors) + 1] <- 46
}
}
if (class(relevanceprogress) == 'logical' & length(relevanceprogress) == 1) {
if (relevanceprogress & length(attr(LVQoutput, 'relevanceprogress')) == 0) {
errors[length(errors) + 1] <- 47
}
}
if (class(testerror) == 'logical' & length(testerror) == 1) {
if (testerror & length(attr(LVQoutput, 'testerror')) == 0) {
errors[length(errors) + 1] <- 48
}
}
if (class(trainerror) != 'logical' | length(trainerror) != 1) {
errors[length(errors) + 1] <- 60
}
if (class(trainerror) == 'logical' & length(trainerror) == 1) {
if (trainerror & length(attr(LVQoutput, 'trainerror')) == 0) {
errors[length(errors) + 1] <- 61
}
}
if (class(trainerrorprogress) != 'logical' | length(trainerrorprogress) != 1) {
errors[length(errors) + 1] <- 65
}
if (class(trainerrorprogress) == 'logical' & length(trainerrorprogress) == 1) {
if (trainerrorprogress & length(attr(LVQoutput, 'trainerrorprogress')) == 0) {
errors[length(errors) + 1] <- 66
}
}
if (class(testerrorprogress) != 'logical' | length(testerrorprogress) != 1) {
errors[length(errors) + 1] <- 67
}
if (class(testerrorprogress) == 'logical' & length(testerrorprogress) == 1) {
if (testerrorprogress & length(attr(LVQoutput, 'testerrorprogress')) == 0) {
errors[length(errors) + 1] <- 68
}
}
if (!any(class(relevancenumber) == c('numeric', 'integer')) | length(relevancenumber) != 1) {
errors[length(errors) + 1] <- 90
}
if (!any(class(relevanceprognumber) == c('numeric', 'integer')) | length(relevanceprognumber) != 1) {
errors[length(errors) + 1] <- 91
}
if (any(class(relevancenumber) == c('numeric', 'integer'))) {
if (relevancenumber %% 1 != 0 | (relevancenumber != -1 & relevancenumber <= 0 & relevancenumber > attr(LVQoutput, 'nrofrelevances'))) {
errors[length(errors) + 1] <- 92
}
}
if (any(class(relevanceprognumber) == c('numeric', 'integer'))) {
if (relevanceprognumber %% 1 != 0 | (relevanceprognumber != -1 & relevanceprognumber <= 0 & relevanceprognumber > attr(LVQoutput, 'nrofrelevances'))) {
errors[length(errors) + 1] <- 93
}
}
if (length(errors) > 0) {
error(errors)
}
}
checkShowNfoldVars <- function (LVQoutput, protofold, relfold, costfold, protoprogfold, relprogfold, trainerrorfold, testerrorfold) {
errors <- vector()
if (!any(class(protofold) == c('numeric', 'integer')) | length(protofold) != 1) {
errors[length(errors) + 1] <- 79
}
if (!any(class(relfold) == c('numeric', 'integer')) | length(relfold) != 1) {
errors[length(errors) + 1] <- 49
}
if (!any(class(costfold) == c('numeric', 'integer')) | length(costfold) != 1) {
errors[length(errors) + 1] <- 50
}
if (!any(class(relprogfold) == c('numeric', 'integer')) | length(relprogfold) != 1) {
errors[length(errors) + 1] <- 51
}
if (!any(class(protoprogfold) == c('numeric', 'integer')) | length(protoprogfold) != 1) {
errors[length(errors) + 1] <- 80
}
if (any(class(protofold) == c('numeric', 'integer'))) {
if (protofold %% 1 != 0 | (protofold != -1 & protofold <= 0 & protofold > attr(LVQoutput, 'nfold'))) {
errors[length(errors) + 1] <- 81
}
}
if (any(class(relfold) == c('numeric', 'integer'))) {
if (relfold %% 1 != 0 | (relfold != -1 & relfold <= 0 & relfold > attr(LVQoutput, 'nfold'))) {
errors[length(errors) + 1] <- 52
}
}
if (any(class(costfold) == c('numeric', 'integer'))) {
if (costfold %% 1 != 0 | (costfold != -1 & costfold <= 0 & costfold > attr(LVQoutput, 'nfold'))) {
errors[length(errors) + 1] <- 53
}
}
if (any(class(relprogfold) == c('numeric', 'integer'))) {
if (relprogfold %% 1 != 0 | (relprogfold != -1 & relprogfold <= 0 & relprogfold > attr(LVQoutput, 'nfold'))) {
errors[length(errors) + 1] <- 82
}
}
if (any(class(relprogfold) == c('numeric', 'integer'))) {
if (relprogfold %% 1 != 0 | (relprogfold != -1 & relprogfold <= 0 & relprogfold > attr(LVQoutput, 'nfold'))) {
errors[length(errors) + 1] <- 54
}
}
if (!any(class(trainerrorfold) == c('numeric', 'integer')) | length(trainerrorfold) != 1) {
errors[length(errors) + 1] <- 69
}
if (any(class(trainerrorfold) == c('numeric', 'integer'))) {
if (trainerrorfold %% 1 != 0 | (trainerrorfold != -1 & trainerrorfold <= 0 & trainerrorfold > attr(LVQoutput, 'nfold'))) {
errors[length(errors) + 1] <- 70
}
}
if (!any(class(testerrorfold) == c('numeric', 'integer')) | length(testerrorfold) != 1) {
errors[length(errors) + 1] <- 71
}
if (any(class(testerrorfold) == c('numeric', 'integer'))) {
if (testerrorfold %% 1 != 0 | (testerrorfold != -1 & testerrorfold <= 0 & testerrorfold > attr(LVQoutput, 'nfold'))) {
errors[length(errors) + 1] <- 72
}
}
if (length(errors) > 0) {
error(errors)
}
}
checkInput <- function (traininp, testinp) {
errors <- vector()
if (!all(is.na(traininp))) {
if (!class(traininp) == 'matrix') {
errors[length(errors) + 1] <- 55
} else if (dim(traininp)[2] < 2) {
errors[length(errors) + 1] <- 56
}
}
if (!all(is.na(testinp))) {
if (!class(testinp) == 'matrix') {
errors[length(errors) + 1] <- 57
} else if (dim(testinp)[2] < 2) {
errors[length(errors) + 1] <- 58
}
}
if (length(errors) > 0) {
error(errors)
}
}
checkGetVars <- function (LVQout, fold) {
errors <- vector()
if (!is.na(fold)) {
if (class(LVQout) != 'nfoldoutput') {
errors[length(errors) + 1] <- 83
}
if (class(LVQout) == 'nfoldoutput' & any(class(fold) == c('numeric', 'integer'))) {
if ((fold != -1 & fold < 1 & attr(LVQout, 'nfold') > fold) | fold %% 1 != 0) {
errors[length(errors) + 1] <- 84
}
}
if (!any(class(fold) == c('numeric', 'integer'))) {
errors[length(errors) + 1] <- 85
}
}
if (length(errors) > 0) {
error(errors)
}
}
checkData <- function (data, LVQscheme, relevances, relevancescheme) {
errors <- vector()
dimensions <- length(data[1,])-1
if (relevancescheme == 'relevance' & class(relevances) != 'vector' & !is.na(relevances)) {
errors[length(errors) + 1] <-88
}
if (relevancescheme == 'relevance' & class(relevances) != 'matrix' & !is.na(relevances)) {
errors[length(errors) + 1] <- 89
}
if (class(relevances) == 'vector') {
if (length(relevances) != dimensions) {
errors[length(errors) + 1] <- 1
}
}
if (class(relevances) == 'matrix') {
if (dim(relevances)[1] != dimensions | dim(relevances)[2] != dimensions) {
errors[length(errors) + 1] <- 2
}
}
if (class(relevances) == 'list') {
for (i in 1:length(relevances)) {
if (class(relevances[[i]]) == 'vector') {
if (length(relevances) != dimensions) {
errors[length(errors) + 1] <- 1
} else if (class(relevances[[i]]) == 'matrix') {
if (dim(relevances[[i]])[1] != dimensions | dim(relevances[[i]])[2] != dimensions) {
errors[length(errors) + 1] <- 2
}
}
}
}
}
if (!all(is.na(data))) {
if (any(LVQscheme == c('cauchyschwarz', 'renyi')) & (any(data[,1:dimensions] < 0, na.rm = TRUE) | any(rowSums(data[,1:dimensions], na.rm = TRUE) < (1 - 1e-8)) | any(rowSums(data[,1:dimensions], na.rm = TRUE) > (1 + 1e-8)))) {
errors[length(errors) + 1] <- 86
}
}
if (length(errors) > 0) {
error(errors)
}
}
|
/R/check.r
|
no_license
|
MATA62N/LVQTools
|
R
| false | false | 16,076 |
r
|
checkInputVars <- function (normalizescheme, normalclasswise, replaceNA, replaceclasswise, orglabellvls) {
errors <- vector()
if (!any(normalizescheme == c('none','ztransform', 'iqr', 'sumone'))| length(normalizescheme) != 1) {
errors[length(errors) + 1] <- 3
}
if ((!any(normalclasswise == orglabellvls) & normalclasswise != 'none') | length(normalclasswise) != 1) {
errors[length(errors) + 1] <- 4
}
if (class(replaceNA) != 'logical' | length(replaceNA) != 1) {
errors[length(errors) + 1] <- 5
}
if (class(replaceclasswise) != 'logical' | length(replaceclasswise) != 1) {
errors[length(errors) + 1] <- 6
}
if (length(errors) > 0) {
error(errors)
}
}
checkLVQvars <- function (prototypes, learningrate, epochs, initscheme, distscheme, relevancemode, relevancescheme, LVQscheme, optimisationscheme, relrate, customdist, alfa, show, graphics, plotcurve, labellvls, dimensions) {
errors <- vector()
if (length(prototypes) != length(labellvls) | any(is.na(prototypes[labellvls]))) {
errors[length(errors) + 1] <- 7
}
if (!any(class(prototypes) == c('numeric', 'integer'))) {
errors[length(errors) + 1] <- 8
}
if (any(class(prototypes) == c('numeric', 'integer'))) {
if (any(prototypes <= 0) | any(prototypes %% 1 != 0)) {
errors[length(errors) + 1] <- 9
}
}
if (epochs <= 0 | epochs %% 1 != 0) {
errors[length(errors) + 1] <- 10
}
if (class(learningrate) != 'numeric' | (length(learningrate) != 1 & length(learningrate) != epochs)) {
errors[length(errors) + 1] <- 11
}
if (class(learningrate) == 'numeric') {
if (any(learningrate <= 0) | any(learningrate >= 1)) {
errors[length(errors) + 1] <- 12
}
}
if (class(relrate) != 'numeric' | (length(relrate) != 1 & length(relrate) != epochs)) {
errors[length(errors) + 1] <- 13
}
if (class(relrate) == 'numeric') {
if (any(relrate <= 0) | any(relrate >= 1)) {
errors[length(errors) + 1] <- 14
}
}
if (!any(initscheme == c('randomwindow', 'zero', 'randomsample', 'mean', 'classmean')) | length(initscheme) != 1) {
errors[length(errors) + 1] <- 15
}
if (!any(distscheme == c('euclidean', 'manhattan', 'custom')) | length(distscheme) != 1) {
errors[length(errors) + 1] <- 16
}
if (!any(relevancemode == c('normal', 'relevance', 'matrix')) | length(relevancemode) != 1) {
errors[length(errors) + 1] <- 17
}
if (!any(LVQscheme == c('LVQ1', 'cauchyschwarz', 'renyi')) | length(LVQscheme) != 1) {
errors[length(errors) + 1] <- 18
}
if (!any(class(customdist) == c('numeric', 'integer')) | length(customdist) != 1) {
errors[length(errors) + 1] <- 19
}
if (any(class(customdist) == c('numeric', 'integer'))) {
if (customdist < 1) {
errors[length(errors) + 1] <- 20
}
}
if (class(show) != 'logical' | length(show) != 1) {
errors[length(errors) + 1] <- 21
}
if (class(graphics) != 'logical' | length(graphics) != 1) {
errors[length(errors) + 1] <- 22
}
if (class(graphics) == 'logical' & dimensions != 2) {
if (graphics) {
errors[length(errors) + 1] <- 23
}
}
if (class(plotcurve) != 'logical' | length(plotcurve) != 1) {
errors[length(errors) + 1] <- 25
}
if (!any(class(alfa) == c('numeric', 'integer')) | length(alfa) != 1) {
errors[length(errors) + 1] <- 73
}
if (any(class(alfa) == c('numeric', 'integer'))) {
if (alfa <= 1) {
errors[length(errors) + 1] <- 74
}
}
if (!any(optimisationscheme == c('normal', 'general')) | length(optimisationscheme) != 1) {
errors[length(errors) + 1] <- 75
}
if (any(LVQscheme == c('cauchyschwarz', 'renyi')) & any(initscheme == c('zero'))){
errors[length(errors) + 1] <- 76
}
if (!any(relevancescheme == c('global', 'local', 'classwise')) | length(relevancescheme) != 1) {
errors[length(errors) + 1] <- 87
}
if (any(relevancemode == c('relevance', 'matrix')) & any(LVQscheme == c('cauchyschwarz', 'renyi'))) {
errors[length(errors) + 1] <- 94
}
if (length(errors) > 0) {
error(errors)
}
}
checkValidateVars <- function (validatescheme, nfold, nrdatapoints) {
errors <- vector()
if (!any(validatescheme == c('traintest', 'nfold', 'train')) | length(validatescheme) != 1) {
errors[length(errors) + 1] <- 26
}
if (!any(class(nfold) == c('numeric', 'integer')) | length(nfold) != 1) {
errors[length(errors) + 1] <- 27
}
if (any(class(nfold) == c('numeric', 'integer'))) {
if (validatescheme == 'nfold' & (nfold <= 1 | nfold %% 1 != 0 | nfold > nrdatapoints)) {
errors[length(errors) + 1] <- 28
}
}
if (length(errors) > 0) {
error(errors)
}
}
checkOutputVars <- function (prototypeoutput, relevanceoutput, costcurve, progress, relevanceprogress, trainerror, testerror, trainerrorprogress, testerrorprogress, validatescheme, relevancemode) {
errors <- vector()
if (class(prototypeoutput) != 'logical' | length(prototypeoutput) != 1) {
errors[length(errors) + 1] <- 31
}
if (class(relevanceoutput) != 'logical' | length(relevanceoutput) != 1) {
errors[length(errors) + 1] <- 32
}
if (class(relevanceoutput) == 'logical' & relevancemode != 'relevance' & relevancemode != 'matrix') {
if (relevanceoutput) {
errors[length(errors) + 1] <- 33
}
}
if (class(costcurve) != 'logical' | length(costcurve) != 1) {
errors[length(errors) + 1] <- 34
}
if (class(progress) != 'logical' | length(progress) != 1) {
errors[length(errors) + 1] <- 35
}
if (class(relevanceprogress) != 'logical' | length(relevanceprogress) != 1) {
errors[length(errors) + 1] <- 36
}
if (class(relevanceprogress) == 'logical' & relevancemode != 'relevance' & relevancemode != 'matrix') {
if (relevanceprogress) {
errors[length(errors) + 1] <- 37
}
}
if (class(testerror) != 'logical' | length(testerror) != 1) {
errors[length(errors) + 1] <- 38
}
if (class(testerror) == 'logical' & validatescheme != 'traintest' & validatescheme != 'nfold') {
if (testerror) {
errors[length(errors) + 1] <- 39
}
}
if (class(trainerror) != 'logical' | length(trainerror) != 1) {
errors[length(errors) + 1] <- 59
}
if (class(testerrorprogress) != 'logical' | length(testerrorprogress) != 1) {
errors[length(errors) + 1] <- 62
}
if (class(testerrorprogress) == 'logical' & validatescheme != 'traintest' & validatescheme != 'nfold') {
if (testerrorprogress) {
errors[length(errors) + 1] <- 63
}
}
if (class(trainerrorprogress) != 'logical' | length(trainerrorprogress) != 1) {
errors[length(errors) + 1] <- 64
}
if (length(errors) > 0) {
error(errors)
}
}
checkShowVars <- function(LVQoutput, prototypes, relevances, costcurve, prototypeprogress, relevanceprogress, trainerror, testerror, trainerrorprogress, testerrorprogress, relevancenumber, relevanceprognumber) {
errors <- vector()
if (!any(class(LVQoutput) == c('trainoutput', 'traintestoutput', 'nfoldoutput'))) {
errors[length(errors) + 1] <- 40
}
if (class(prototypes) != 'logical' | length(prototypes) != 1) {
errors[length(errors) + 1] <- 77
}
if (class(relevances) != 'logical' | length(relevances) != 1) {
errors[length(errors) + 1] <- 41
}
if (class(costcurve) != 'logical' | length(costcurve) != 1) {
errors[length(errors) + 1] <- 42
}
if (class(prototypeprogress) != 'logical' | length(prototypeprogress) != 1) {
errors[length(errors) + 1] <- 78
}
if (class(relevanceprogress) != 'logical' | length(relevanceprogress) != 1) {
errors[length(errors) + 1] <- 43
}
if (class(testerror) != 'logical' | length(testerror) != 1) {
errors[length(errors) + 1] <- 44
}
if (class(relevances) == 'logical' & length(relevances) == 1) {
if (relevances & length(attr(LVQoutput, 'relevances')) == 0) {
errors[length(errors) + 1] <- 45
}
}
if (class(costcurve) == 'logical' & length(costcurve) == 1) {
if (costcurve & length(attr(LVQoutput, 'costcurve')) == 0) {
errors[length(errors) + 1] <- 46
}
}
if (class(relevanceprogress) == 'logical' & length(relevanceprogress) == 1) {
if (relevanceprogress & length(attr(LVQoutput, 'relevanceprogress')) == 0) {
errors[length(errors) + 1] <- 47
}
}
if (class(testerror) == 'logical' & length(testerror) == 1) {
if (testerror & length(attr(LVQoutput, 'testerror')) == 0) {
errors[length(errors) + 1] <- 48
}
}
if (class(trainerror) != 'logical' | length(trainerror) != 1) {
errors[length(errors) + 1] <- 60
}
if (class(trainerror) == 'logical' & length(trainerror) == 1) {
if (trainerror & length(attr(LVQoutput, 'trainerror')) == 0) {
errors[length(errors) + 1] <- 61
}
}
if (class(trainerrorprogress) != 'logical' | length(trainerrorprogress) != 1) {
errors[length(errors) + 1] <- 65
}
if (class(trainerrorprogress) == 'logical' & length(trainerrorprogress) == 1) {
if (trainerrorprogress & length(attr(LVQoutput, 'trainerrorprogress')) == 0) {
errors[length(errors) + 1] <- 66
}
}
if (class(testerrorprogress) != 'logical' | length(testerrorprogress) != 1) {
errors[length(errors) + 1] <- 67
}
if (class(testerrorprogress) == 'logical' & length(testerrorprogress) == 1) {
if (testerrorprogress & length(attr(LVQoutput, 'testerrorprogress')) == 0) {
errors[length(errors) + 1] <- 68
}
}
if (!any(class(relevancenumber) == c('numeric', 'integer')) | length(relevancenumber) != 1) {
errors[length(errors) + 1] <- 90
}
if (!any(class(relevanceprognumber) == c('numeric', 'integer')) | length(relevanceprognumber) != 1) {
errors[length(errors) + 1] <- 91
}
if (any(class(relevancenumber) == c('numeric', 'integer'))) {
if (relevancenumber %% 1 != 0 | (relevancenumber != -1 & relevancenumber <= 0 & relevancenumber > attr(LVQoutput, 'nrofrelevances'))) {
errors[length(errors) + 1] <- 92
}
}
if (any(class(relevanceprognumber) == c('numeric', 'integer'))) {
if (relevanceprognumber %% 1 != 0 | (relevanceprognumber != -1 & relevanceprognumber <= 0 & relevanceprognumber > attr(LVQoutput, 'nrofrelevances'))) {
errors[length(errors) + 1] <- 93
}
}
if (length(errors) > 0) {
error(errors)
}
}
checkShowNfoldVars <- function (LVQoutput, protofold, relfold, costfold, protoprogfold, relprogfold, trainerrorfold, testerrorfold) {
errors <- vector()
if (!any(class(protofold) == c('numeric', 'integer')) | length(protofold) != 1) {
errors[length(errors) + 1] <- 79
}
if (!any(class(relfold) == c('numeric', 'integer')) | length(relfold) != 1) {
errors[length(errors) + 1] <- 49
}
if (!any(class(costfold) == c('numeric', 'integer')) | length(costfold) != 1) {
errors[length(errors) + 1] <- 50
}
if (!any(class(relprogfold) == c('numeric', 'integer')) | length(relprogfold) != 1) {
errors[length(errors) + 1] <- 51
}
if (!any(class(protoprogfold) == c('numeric', 'integer')) | length(protoprogfold) != 1) {
errors[length(errors) + 1] <- 80
}
if (any(class(protofold) == c('numeric', 'integer'))) {
if (protofold %% 1 != 0 | (protofold != -1 & protofold <= 0 & protofold > attr(LVQoutput, 'nfold'))) {
errors[length(errors) + 1] <- 81
}
}
if (any(class(relfold) == c('numeric', 'integer'))) {
if (relfold %% 1 != 0 | (relfold != -1 & relfold <= 0 & relfold > attr(LVQoutput, 'nfold'))) {
errors[length(errors) + 1] <- 52
}
}
if (any(class(costfold) == c('numeric', 'integer'))) {
if (costfold %% 1 != 0 | (costfold != -1 & costfold <= 0 & costfold > attr(LVQoutput, 'nfold'))) {
errors[length(errors) + 1] <- 53
}
}
if (any(class(relprogfold) == c('numeric', 'integer'))) {
if (relprogfold %% 1 != 0 | (relprogfold != -1 & relprogfold <= 0 & relprogfold > attr(LVQoutput, 'nfold'))) {
errors[length(errors) + 1] <- 82
}
}
if (any(class(relprogfold) == c('numeric', 'integer'))) {
if (relprogfold %% 1 != 0 | (relprogfold != -1 & relprogfold <= 0 & relprogfold > attr(LVQoutput, 'nfold'))) {
errors[length(errors) + 1] <- 54
}
}
if (!any(class(trainerrorfold) == c('numeric', 'integer')) | length(trainerrorfold) != 1) {
errors[length(errors) + 1] <- 69
}
if (any(class(trainerrorfold) == c('numeric', 'integer'))) {
if (trainerrorfold %% 1 != 0 | (trainerrorfold != -1 & trainerrorfold <= 0 & trainerrorfold > attr(LVQoutput, 'nfold'))) {
errors[length(errors) + 1] <- 70
}
}
if (!any(class(testerrorfold) == c('numeric', 'integer')) | length(testerrorfold) != 1) {
errors[length(errors) + 1] <- 71
}
if (any(class(testerrorfold) == c('numeric', 'integer'))) {
if (testerrorfold %% 1 != 0 | (testerrorfold != -1 & testerrorfold <= 0 & testerrorfold > attr(LVQoutput, 'nfold'))) {
errors[length(errors) + 1] <- 72
}
}
if (length(errors) > 0) {
error(errors)
}
}
checkInput <- function (traininp, testinp) {
errors <- vector()
if (!all(is.na(traininp))) {
if (!class(traininp) == 'matrix') {
errors[length(errors) + 1] <- 55
} else if (dim(traininp)[2] < 2) {
errors[length(errors) + 1] <- 56
}
}
if (!all(is.na(testinp))) {
if (!class(testinp) == 'matrix') {
errors[length(errors) + 1] <- 57
} else if (dim(testinp)[2] < 2) {
errors[length(errors) + 1] <- 58
}
}
if (length(errors) > 0) {
error(errors)
}
}
checkGetVars <- function (LVQout, fold) {
errors <- vector()
if (!is.na(fold)) {
if (class(LVQout) != 'nfoldoutput') {
errors[length(errors) + 1] <- 83
}
if (class(LVQout) == 'nfoldoutput' & any(class(fold) == c('numeric', 'integer'))) {
if ((fold != -1 & fold < 1 & attr(LVQout, 'nfold') > fold) | fold %% 1 != 0) {
errors[length(errors) + 1] <- 84
}
}
if (!any(class(fold) == c('numeric', 'integer'))) {
errors[length(errors) + 1] <- 85
}
}
if (length(errors) > 0) {
error(errors)
}
}
checkData <- function (data, LVQscheme, relevances, relevancescheme) {
errors <- vector()
dimensions <- length(data[1,])-1
if (relevancescheme == 'relevance' & class(relevances) != 'vector' & !is.na(relevances)) {
errors[length(errors) + 1] <-88
}
if (relevancescheme == 'relevance' & class(relevances) != 'matrix' & !is.na(relevances)) {
errors[length(errors) + 1] <- 89
}
if (class(relevances) == 'vector') {
if (length(relevances) != dimensions) {
errors[length(errors) + 1] <- 1
}
}
if (class(relevances) == 'matrix') {
if (dim(relevances)[1] != dimensions | dim(relevances)[2] != dimensions) {
errors[length(errors) + 1] <- 2
}
}
if (class(relevances) == 'list') {
for (i in 1:length(relevances)) {
if (class(relevances[[i]]) == 'vector') {
if (length(relevances) != dimensions) {
errors[length(errors) + 1] <- 1
} else if (class(relevances[[i]]) == 'matrix') {
if (dim(relevances[[i]])[1] != dimensions | dim(relevances[[i]])[2] != dimensions) {
errors[length(errors) + 1] <- 2
}
}
}
}
}
if (!all(is.na(data))) {
if (any(LVQscheme == c('cauchyschwarz', 'renyi')) & (any(data[,1:dimensions] < 0, na.rm = TRUE) | any(rowSums(data[,1:dimensions], na.rm = TRUE) < (1 - 1e-8)) | any(rowSums(data[,1:dimensions], na.rm = TRUE) > (1 + 1e-8)))) {
errors[length(errors) + 1] <- 86
}
}
if (length(errors) > 0) {
error(errors)
}
}
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/profile_functions.R
\name{edit_profile}
\alias{edit_profile}
\title{Edit your profile function}
\usage{
edit_profile()
}
\description{
Edit your profile function
}
|
/man/edit_profile.Rd
|
no_license
|
Giappo/jap
|
R
| false | true | 242 |
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/profile_functions.R
\name{edit_profile}
\alias{edit_profile}
\title{Edit your profile function}
\usage{
edit_profile()
}
\description{
Edit your profile function
}
|
#' Generate a PDF field guide using the ALA's field guide generator
#'
#' @references \url{http://fieldguide.ala.org.au/}
#' @param guids character: vector of GUIDs
#' @param title string: title to use in the field guide PDF
#' @param filename string: filename for the PDF document
#' @param overwrite logical: overwrite the file if it already exists?
#'
#' @return filename
#'
#' @seealso \code{\link{search_guids}}
#'
#' @examples
#' \dontrun{
#' fieldguide(guids=
#' c("urn:lsid:biodiversity.org.au:afd.taxon:95773568-053d-44de-a624-5699f0ac4a59",
#' "http://id.biodiversity.org.au/node/apni/2890970"))
#' }
#'
# @export # no api in NBN for this?
fieldguide <- function(guids,title="Field guide",filename=tempfile(fileext=".pdf"),overwrite=FALSE) {
ALA4R::fieldguide(guids,title,filename,overwrite)
}
|
/R/fieldguide.R
|
no_license
|
fozy81/NBN4R
|
R
| false | false | 823 |
r
|
#' Generate a PDF field guide using the ALA's field guide generator
#'
#' @references \url{http://fieldguide.ala.org.au/}
#' @param guids character: vector of GUIDs
#' @param title string: title to use in the field guide PDF
#' @param filename string: filename for the PDF document
#' @param overwrite logical: overwrite the file if it already exists?
#'
#' @return filename
#'
#' @seealso \code{\link{search_guids}}
#'
#' @examples
#' \dontrun{
#' fieldguide(guids=
#' c("urn:lsid:biodiversity.org.au:afd.taxon:95773568-053d-44de-a624-5699f0ac4a59",
#' "http://id.biodiversity.org.au/node/apni/2890970"))
#' }
#'
# @export # no api in NBN for this?
fieldguide <- function(guids,title="Field guide",filename=tempfile(fileext=".pdf"),overwrite=FALSE) {
ALA4R::fieldguide(guids,title,filename,overwrite)
}
|
stsp<-function(data,Ntimesteps,Q)
# Function to compute the space time separation for a data set
# S=stsp(data,Ntimesteps,Q)
# data - data set
# Ntimesteps - number of time lags
# Q a row vector of quartiles, e.g. [25 50 95] to get 25th, median
# and 95th seperations
{
N<-length(data)
S=vector()
for (i in 1:Ntimesteps)
{
S=cbind(S,quantile(sqrt((data[1:(N-i)]-data[(1+i):N])^2),Q*0.01))
}
return(S)
}
|
/Hailiang-Du/stsp.R
|
no_license
|
JUJUup/SummerSchool2021_MLAS
|
R
| false | false | 404 |
r
|
stsp<-function(data,Ntimesteps,Q)
# Function to compute the space time separation for a data set
# S=stsp(data,Ntimesteps,Q)
# data - data set
# Ntimesteps - number of time lags
# Q a row vector of quartiles, e.g. [25 50 95] to get 25th, median
# and 95th seperations
{
N<-length(data)
S=vector()
for (i in 1:Ntimesteps)
{
S=cbind(S,quantile(sqrt((data[1:(N-i)]-data[(1+i):N])^2),Q*0.01))
}
return(S)
}
|
### R code from vignette source 'caper.rnw'
### Encoding: UTF-8
###################################################
### code chunk number 1: setup
###################################################
library(caper)
## whilst code is being tested, load most recent versions from the pkg repository
for(f in dir('../../R', full=TRUE)) (source(f))
###################################################
### code chunk number 2: whycaper
###################################################
par(mfrow=c(2,2), mar=c(3,3,1,1), mgp=c(2,0.7,0))
plot(c(0,13),c(0,10), typ="n", bty="n", xaxt="n",yaxt="n", xlab="", ylab="", xaxs="i",yaxs="i")
lines(c(0,7), c(5,8.5))
lines(c(0,7), c(5,1.5))
lines(c(3.5,7), c(3.25,5))
polygon(c(7,10,10), y=c(8.5,10,7))
polygon(c(7,10,10), y=c(5,6.5,3.5))
polygon(c(7,10,10), y=c(1.5,3,0))
points( c(0.5,1.5) +0.5, c(5,5), cex=1, col=1:2)
points(c(7.5,8.5)+0.5, c(8.5,8.5), cex=1, col=1:2)
points(c(4,5)+0.5, c(3.25,3.25), cex=1.5, col=1:2)
points(c(7.5,8.5)+0.5, c(5,5), cex=1.5, col=1:2)
points(c(7.5,8.5)+0.5, c(1.5,1.5), cex=2, col=1:2)
rect(11 - c(.3,.2,.1), c(0,3.5,7), 11 + c(.3,.2,.1) , c(3,6.5,10))
rect(12 - c(.3,.2,.1), c(0,3.5,7), 12 + c(.3,.2,.1) , c(3,6.5,10), border="red")
par(usr=c(0,1,0,1)); text(0.1,0.9, cex=2,"a")
dat <- data.frame(x = rnorm(120, mean= rep(2:4, each=40), sd=0.5),
y = rnorm(120, mean= rep(2:4, each=40), sd=0.5),
tx = gl(3,40))
plot(y~x, col=unclass(tx), data=dat, xaxt="n", xlab="", ylab="")
axis(1, col.axis="red")
abline(lm(y~x, data=dat))
for(sub in split(dat, dat$tx)) abline(lm(y~x, data=sub), col=unclass(sub$tx)[1], lty=2)
plot(c(0,13),c(0,10), typ="n", bty="n", xaxt="n",yaxt="n", xlab="", ylab="", xaxs="i",yaxs="i")
lines(c(0,7), c(5,8.5))
lines(c(0,7), c(5,1.5))
lines(c(3.5,7), c(3.25,5))
polygon(c(7,10,10), y=c(8.5,10,7))
polygon(c(7,10,10), y=c(5,6.5,3.5))
polygon(c(7,10,10), y=c(1.5,3,0))
points(c(0.5,1.5)+0.5, c(5,5), cex=1, col=1:2)
points(c(7.5,8.5)+0.5, c(8.5,8.5), cex=1, col=1:2)
points(c(4,5)+0.5, c(3.25,3.25), cex=c(1,1.5), col=1:2)
points(c(7.5,8.5)+0.5, c(5,5), cex=c(1,1.5), col=1:2)
points(c(7.5,8.5)+0.5, c(1.5,1.5), cex=c(1,2), col=1:2)
polygon(11 + c(-0,-0.1,0.1,0), c(3,0,0,3))
polygon(12 + c(-0.2,-0.3,0.3,0.2), c(3,0,0,3), border="red")
polygon(11 + c(-0,-0.1,0.1,0), c(6.5,3.5,3.5,6.5))
polygon(12 + c(-0.1,-0.2,0.2,0.1), c(6.5,3.5,3.5,6.5), border="red")
polygon(11 + c(-0,-0.1,0.1,0), c(10,7.5,7.5,10))
polygon(12 + c(-0.0,-0.1,0.1,0.), c(10,7.5,7.5,10), border="red")
par(usr=c(0,1,0,1)); text(0.1,0.9, cex=2, "b")
dat <- data.frame(x = rnorm(120, mean= rep(2:4, each=40), sd=0.5),
tx = gl(3,40))
dat$y <- dat$x - rnorm(120, mean= rep(0:2, each=40), sd=0.5)
plot(y~x, col=unclass(tx), data=dat, xaxt="n", xlab="", ylab="")
axis(1, col.axis="red")
abline(lm(y~x, data=dat))
for(sub in split(dat, dat$tx)) abline(lm(y~x, data=sub), col=unclass(sub$tx)[1], lty=2)
###################################################
### code chunk number 3: comparative.data
###################################################
phy <- read.tree(text='(((B:2,A:2):1,D:3):1,(C:1,E:1):3);')
dat <- data.frame(
taxa=c("A","B","C","D","E"),
n.species=c(5,9,12,1,13), mass=c(4.1,4.5,5.9,3.0,6.0)
)
cdat <- comparative.data(data=dat, phy=phy, names.col="taxa")
print(cdat)
###################################################
### code chunk number 4: na.omit
###################################################
data(perissodactyla)
(perisso <- comparative.data(perissodactyla.tree, perissodactyla.data, Binomial))
# but this can be turned off
(perissoFull <- comparative.data(perissodactyla.tree, perissodactyla.data, Binomial, na.omit=FALSE))
na.omit(perisso)
###################################################
### code chunk number 5: na.omit2
###################################################
comparative.data(perissodactyla.tree, perissodactyla.data, Binomial, scope= log.female.wt ~ log.gestation.length)
na.omit(perissoFull, scope=log.female.wt ~ log.gestation.length + Territoriality)
###################################################
### code chunk number 6: subset
###################################################
subset(perissoFull, subset=! is.na(Territoriality))
subset(perissoFull, subset=log.female.wt > 5.5, select=c(log.female.wt, log.gestation.length))
###################################################
### code chunk number 7: squarebracket
###################################################
horses <- grep('Equus', perissoFull$phy$tip.label)
perissoFull[horses,]
perissoFull[horses, 2:3]
###################################################
### code chunk number 8: pglsSetup
###################################################
## demo tree
z <- structure(list(edge = structure(c(11L, 15L, 18L, 18L, 15L, 16L,
16L, 11L, 12L, 13L, 13L, 19L, 19L, 12L, 14L, 14L, 17L, 17L, 15L,
18L, 1L, 2L, 16L, 3L, 4L, 12L, 13L, 5L, 19L, 6L, 7L, 14L, 8L,
17L, 9L, 10L), .Dim = c(18L, 2L)), edge.length = c(5.723, 2.186,
1.09, 1.09, 0.627, 2.649, 2.649, 1.049, 1.411, 6.54, 5.538, 1.001,
1.001, 1.863, 6.088, 4.777, 1.312, 1.312), tip.label = c("t8",
"t6", "t4", "t10", "t9", "t5", "t7", "t1", "t3", "t2"), Nnode = 9L), .Names = c("edge",
"edge.length", "tip.label", "Nnode"), class = "phylo", order = "cladewise")
V <- VCV.array(z)
###################################################
### code chunk number 9: vcvFig
###################################################
ec <- rep('grey50', 18)
ec[c(1,5,7)] <- 'red'
ec[c(8,14)] <- 'blue'
plot(z, no.margin=TRUE, cex=0.6, label.offset=0.3, edge.col=ec)
###################################################
### code chunk number 10: bltrans
###################################################
## internal branch lengths
internal <- z$edge[,2] > 10
vlines <- 9 * c(0, 0.5, 1, 1.5)
zz <- z
# layout
layout(matrix(c(1:9), ncol=3))
par(mar=c(0,0.5,2,0.5))
cx <- 0.8
ln <- 0.5
xl <- c(0,15)
# lambda
pvals <- c(1.4, 0.5)
ec <- ifelse(internal,'red', 'grey30')
## zz$edge.length <- ifelse(internal, z$edge.length*pvals[1], z$edge.length)
## plot(zz, edge.col=ec, x.lim=xl, label.offset=0.2)
## mtext(bquote(lambda == .(pvals[1])), side=3, cex=cx, line=ln)
## abline(v=vlines, lty=2, col='grey')
##
## plot(z, edge.col=ec, x.lim=xl, label.offset=0.2)
## abline(v=vlines, lty=2, col='grey')
## mtext(expression(lambda == 1), side=3, cex=cx, line=ln)
##
## zz$edge.length <- ifelse(internal, z$edge.length*pvals[2], z$edge.length)
## plot(zz, edge.col=ec, x.lim=xl, label.offset=0.2)
## mtext(bquote(lambda == .(pvals[2])), side=3, cex=cx, line=ln)
## abline(v=vlines, lty=2, col='grey')
# get the branching structure back from the matrix
dd <- ifelse(lower.tri(V) | upper.tri(V), V * pvals[1], V)
ddh <- as.phylo(hclust(dist(dd)))
plot(ddh, edge.col = 'red', x.lim=xl, label.offset=0.2)
mtext(bquote(lambda == .(pvals[1])), side=3, cex=cx, line=ln)
abline(v=vlines, lty=2, col='grey')
plot(z, edge.col=ec, x.lim=xl, label.offset=0.2)
abline(v=vlines, lty=2, col='grey')
mtext(expression(lambda == 1), side=3, cex=cx, line=ln)
dd <- ifelse(lower.tri(V) | upper.tri(V), V * pvals[2], V)
ddh <- as.phylo(hclust(dist(dd)))
plot(ddh, edge.col = 'red', x.lim=xl, label.offset=0.2)
mtext(bquote(lambda == .(pvals[2])), side=3, cex=cx, line=ln)
abline(v=vlines, lty=2, col='grey')
# delta:
pvals <- c(1.2, 0.5)
# get the branching structure back from the matrix
dd <- V ^ pvals[1]
ddh <- as.phylo(hclust(dist(dd)))
plot(ddh, edge.col = 'red', x.lim=xl, label.offset=0.2)
mtext(bquote(delta == .(pvals[1])), side=3, cex=cx, line=ln)
abline(v=vlines, lty=2, col='grey')
plot(z, edge.col='red', x.lim=xl, label.offset=0.2)
abline(v=vlines, lty=2, col='grey')
mtext(expression(delta == 1), side=3, cex=cx, line=ln)
dd <- V ^ pvals[2]
ddh <- as.phylo(hclust(dist(dd)))
plot(ddh, edge.col='red', x.lim=xl, label.offset=0.2)
mtext(bquote(delta == .(pvals[2])), cex=cx, line=ln)
abline(v=vlines, lty=2, col='grey')
# kappa
pvals <- c(1.2, 0.0)
ec <- ifelse(internal,'red', 'grey30')
zz$edge.length <- z$edge.length^pvals[1]
plot(zz, edge.col = 'red', x.lim=xl, label.offset=0.2)
mtext(bquote(kappa == .(pvals[1])), side=3, cex=cx, line=ln)
abline(v=vlines, lty=2, col='grey')
plot(z, edge.col='red', x.lim=xl, label.offset=0.2)
abline(v=vlines, lty=2, col='grey')
mtext(expression(kappa == 1), side=3, cex=cx, line=ln)
zz$edge.length <- z$edge.length^pvals[2]
plot(zz, edge.col='red', x.lim=xl, label.offset=0.2)
mtext(bquote(kappa == .(pvals[1])), cex=cx, line=ln)
abline(v=vlines, lty=2, col='grey')
###################################################
### code chunk number 11: basicPGLS
###################################################
data(shorebird)
shorebird <- comparative.data(shorebird.tree, shorebird.data, Species, vcv=TRUE)
mod <- pgls(log(Egg.Mass) ~ log(M.Mass), shorebird)
print(mod)
summary(mod)
###################################################
### code chunk number 12: lambdaOpt
###################################################
data(shorebird)
shorebird <- comparative.data(shorebird.tree, shorebird.data, Species, vcv=TRUE, vcv.dim=3)
mod <- pgls(log(Egg.Mass) ~ log(M.Mass), shorebird, lambda='ML')
summary(mod)
mod.l <- pgls.profile(mod, 'lambda')
mod.d <- pgls.profile(mod, 'delta')
mod.k <- pgls.profile(mod, 'kappa')
plot(mod.l); plot(mod.d); plot(mod.k)
###################################################
### code chunk number 13: lambdaOptPlot
###################################################
par(mar=c(4.5,3,1,1), mfrow=c(1,3), mgp=c(1.8,0.8,0), tcl=-0.2)
plot(mod.l); plot(mod.d); plot(mod.k)
###################################################
### code chunk number 14: pglsPlotCmd
###################################################
par(mfrow=c(2,2), mar=c(3,3,1,1), mgp=c(2,0.7,0), tcl=-0.2)
plot(mod)
###################################################
### code chunk number 15: pglsCrit
###################################################
mod1 <- pgls(log(Egg.Mass) ~ log(M.Mass) * log(F.Mass), shorebird)
anova(mod1)
mod2 <- pgls(log(Egg.Mass) ~ log(M.Mass) + log(F.Mass), shorebird)
mod3 <- pgls(log(Egg.Mass) ~ log(M.Mass) , shorebird)
mod4 <- pgls(log(Egg.Mass) ~ 1, shorebird)
anova(mod1, mod2, mod3, mod4)
AIC(mod1, mod2, mod3, mod4)
###################################################
### code chunk number 16: crunchExample
###################################################
data(shorebird)
shorebird.data$lgEgg.Mass <- log(shorebird.data$Egg.Mass)
shorebird.data$lgM.Mass <- log(shorebird.data$M.Mass)
shorebird.data$lgF.Mass <- log(shorebird.data$F.Mass)
shorebird <- comparative.data(shorebird.tree, shorebird.data, Species)
crunchMod <- crunch(lgEgg.Mass ~ lgF.Mass + lgM.Mass, data=shorebird)
summary(crunchMod)
###################################################
### code chunk number 17: brunchExample
###################################################
perisso <- comparative.data(perissodactyla.tree, perissodactyla.data, Binomial)
brunchMod <- brunch(log.female.wt ~ Territoriality, data=perisso)
caic.table(brunchMod)
###################################################
### code chunk number 18: brunchPlot
###################################################
bwd <- rep(1,15)
bwd[c(5,6,11,12,9,13,14,15)] <- 3
plot(perisso$phy, 'cladogram', use.edge.length=FALSE, label.offset=0.4, show.node=TRUE, cex=0.7, show.tip=FALSE, x.lim=c(0,12), no.margin=TRUE, edge.width=bwd)
points(rep(8.25,9), 1:9, pch=ifelse(perisso$data$Terr=='Yes', 1,19))
text(rep(8.5,9), 1:9, perisso$phy$tip.label, font=3, adj=0)
###################################################
### code chunk number 19: macrocaicExample
###################################################
data(IsaacEtAl)
primates <- comparative.data(primates.tree, primates.data, binomial, na.omit=FALSE)
primatesBodySize <- macrocaic(species.rich ~ body.mass, data=primates)
summary(primatesBodySize)
###################################################
### code chunk number 20: phylodScale
###################################################
data(BritishBirds)
BritishBirds <- comparative.data(BritishBirds.tree, BritishBirds.data, binomial)
redPD <- phylo.d(BritishBirds, binvar=Red_list)
par(mar=c(3,3,2,1), mgp=c(1.8,0.8,0), tcl=-0.3)
plot(density(redPD$Permutations$random, bw=0.5), main='', xlim=c(10,55), col='blue', xlab='Sum of character change')
lines(density(redPD$Permutations$brownian,bw=0.5), col='red')
abline(v=redPD$Parameters$Observed)
abline(v=redPD$Parameters$Observed, col='grey')
abline(v=redPD$Parameters$MeanRandom, col='blue')
abline(v=redPD$Parameters$MeanBrownian, col='red')
with(redPD$Parameters, axis(3, at=c(MeanBrownian, Observed, MeanRandom), labels=c(0, round(redPD$DEstimate,2),1), mgp=c(1.5,0.7,0.25)))
mtext(expression(italic(D)==phantom(x)), side=3, at=25, line=1.2)
###################################################
### code chunk number 21: phylodDemo
###################################################
data(BritishBirds)
BritishBirds <- comparative.data(BritishBirds.tree, BritishBirds.data, binomial)
redPhyloD <- phylo.d(BritishBirds, binvar=Red_list)
print(redPhyloD)
###################################################
### code chunk number 22: caicDiagExample
###################################################
par(mfrow=c(2,3))
shorebird <- comparative.data(shorebird.tree, shorebird.data, Species)
crunchMod <- crunch(Egg.Mass ~ M.Mass, data=shorebird)
caic.diagnostics(crunchMod)
shorebird.data$lgEgg.Mass <- log(shorebird.data$Egg.Mass)
shorebird.data$lgM.Mass <- log(shorebird.data$M.Mass)
shorebird <- comparative.data(shorebird.tree, shorebird.data, Species)
crunchMod2 <- crunch(lgEgg.Mass ~ lgM.Mass, data=shorebird)
caic.diagnostics(crunchMod2)
###################################################
### code chunk number 23: caicDiagExamplePlot
###################################################
par(mfrow=c(2,3), mar=c(3,3,1,1), mgp=c(2,0.7,0), tcl=-0.2)
shorebird <- comparative.data(shorebird.tree, shorebird.data, Species)
# need to store the output of caic diagnostics to stop it
# showing up in the float
crunchMod <- crunch(Egg.Mass ~ M.Mass, data=shorebird)
x <- caic.diagnostics(crunchMod)
crunchMod2 <- crunch(lgEgg.Mass ~ lgM.Mass, data=shorebird)
x <- caic.diagnostics(crunchMod2)
###################################################
### code chunk number 24: caicRobustExample
###################################################
data(shorebird)
shorebird <- comparative.data(shorebird.tree, shorebird.data, Species)
crunchMod <- crunch(Egg.Mass ~ M.Mass, data=shorebird)
caic.diagnostics(crunchMod)
crunchModRobust <- caic.robust(crunchMod)
caic.diagnostics(crunchModRobust, outlier=2)
###################################################
### code chunk number 25: caicRobustExamplePlot
###################################################
par(mfrow=c(2,3), mar=c(3,3,1,1), mgp=c(2,0.7,0), tcl=-0.2)
data(shorebird)
shorebird <- comparative.data(shorebird.tree, shorebird.data, Species)
# need to store the output of caic diagnostics to stop ip showing up in the float
crunchMod <- crunch(Egg.Mass ~ M.Mass, data=shorebird)
x <-caic.diagnostics(crunchMod)
crunchModRobust <- caic.robust(crunchMod)
x <-caic.diagnostics(crunchModRobust, outlier=2)
###################################################
### code chunk number 26: modelCrit
###################################################
data(shorebird)
shorebird.data$lgEgg.Mass <- log(shorebird.data$Egg.Mass)
shorebird.data$lgM.Mass <- log(shorebird.data$M.Mass)
shorebird.data$lgF.Mass <- log(shorebird.data$F.Mass)
shorebird <- comparative.data(shorebird.tree, shorebird.data, Species)
crunchMod <- crunch(lgEgg.Mass ~ lgF.Mass + lgM.Mass, data=shorebird)
par(mfrow=c(2,2))
plot(crunchMod)
###################################################
### code chunk number 27: modelCritPlot
###################################################
par(mfrow=c(2,2), mar=c(3,3,2,1), mgp=c(2,0.7,0), tcl=-0.2)
data(shorebird)
crunchMod <- crunch(lgEgg.Mass ~ lgF.Mass + lgM.Mass, data=shorebird)
plot(crunchMod)
###################################################
### code chunk number 28: modelComparison
###################################################
shorebird.data$lgEgg.Mass <- log(shorebird.data$Egg.Mass)
shorebird.data$lgM.Mass <- log(shorebird.data$M.Mass)
shorebird.data$lgF.Mass <- log(shorebird.data$F.Mass)
shorebird <- comparative.data(shorebird.tree, shorebird.data, Species)
cMod1 <- crunch(lgEgg.Mass ~ lgM.Mass * lgF.Mass, data=shorebird)
cMod2 <- crunch(lgEgg.Mass ~ lgM.Mass + lgF.Mass, data=shorebird)
cMod3 <- crunch(lgEgg.Mass ~ lgM.Mass , data=shorebird)
anova(cMod1, cMod2, cMod3)
AIC(cMod1, cMod2, cMod3)
###################################################
### code chunk number 29: fuscoDemo
###################################################
data(syrphidae)
syrphidae <- comparative.data(phy=syrphidaeTree, dat=syrphidaeRich, names.col=genus)
summary(fusco.test(syrphidae, rich=nSpp))
summary(fusco.test(syrphidae, tipsAsSpecies=TRUE))
###################################################
### code chunk number 30: pdExample
###################################################
data(BritishBirds)
BritishBirds.cm <- clade.matrix(BritishBirds.tree)
redListSpecies <- with(BritishBirds.data, binomial[Red_list==1])
obs <- pd.calc(BritishBirds.cm, redListSpecies, method="TBL")
rand <- pd.bootstrap(BritishBirds.cm, ntips=length(redListSpecies), rep=1000, method="TBL")
plot(density(rand), main='Total branch length for random sets of 32 species.')
abline(v=obs, col='red')
###################################################
### code chunk number 31: pdMeasurePlot
###################################################
tree <- read.tree(text="((((A:1,B:1):1.5,C:2.5):0.5,(D:0.6,E:0.6):2.4):0.5,((F:1.9,G:1.9):0.8,(H:1.6,I:1.6):1.1):0.8):0.2;")
clmat <- clade.matrix(tree)
tips <- c("A","C","D","E","G","H")
par(mfrow=c(2,3), mar=rep(1,4))
tip.col <- rep('grey', length=length(tree$tip.label))
tip.col[c(1,3,4,5,7,8)] <- 'black'
# TBL
cl <- rep('black', length=length(tree$edge.length))
cl[c(1,2,3,4,6,7,8,9,10,11,13,14,15)] <- 'red'
plot(tree, label.offset=0.1, cex=1.2, tip.color=tip.col, x.lim=3.8, edge.col=cl)
text(0.2,8.5, "TBL", cex=1.2, adj=c(0,0))
# UEH
cl <- rep('black', length=length(tree$edge.length))
cl[c(3,4,6,8,9,11,14,13,15)] <- 'red'
plot(tree, label.offset=0.1, cex=1.2, tip.color=tip.col, x.lim=3.8, edge.col=cl)
text(0.2,8.5, "UEH", cex=1.2, adj=c(0,0))
# SBL
cl <- rep('black', length=length(tree$edge.length))
cl[c(1,2,7,10)] <- 'red'
plot(tree, label.offset=0.1, cex=1.2, tip.color=tip.col, x.lim=3.8, edge.col=cl)
text(0.2,8.5, "SBL", cex=1.2, adj=c(0,0))
# TIP
cl <- rep('black', length=length(tree$edge.length))
cl[c(4,6,8,9,13,15)] <- 'red'
plot(tree, label.offset=0.1, cex=1.2, tip.color=tip.col, x.lim=3.8, edge.col=cl)
text(0.2,8.5, "TIP", cex=1.2, adj=c(0,0))
# MST
tips <- c("A","C")
tip.col <- rep('grey', length=length(tree$tip.label))
tip.col[c(1,3)] <- 'black'
cl <- rep('black', length=length(tree$edge.length))
cl[c(3,4,6)] <- 'red'
plot(tree, label.offset=0.1, cex=1.2, tip.color=tip.col, x.lim=3.8, edge.col=cl)
text(0.2,8.5, "MST", cex=1.2, adj=c(0,0))
par(mar=c(3,3,1,1))
plot(density(rand), main='', xlab= 'TBL values for red listed British birds.')
abline(v=obs, col='red')
###################################################
### code chunk number 32: edExample
###################################################
data(IsaacEtAl)
primates.cm <- clade.matrix(primates.tree)
primateED <- ed.calc(primates.cm)
str(primateED)
plot(density(primateED$spp$ED))
with(primateED, spp[spp$ED == max(spp$ED),])
###################################################
### code chunk number 33: edExamplePlots
###################################################
par(mfrow=c(1,3), mar=c(0,0,0,0), mgp=c(2,0.7,0))
edDemo <- ed.calc(clmat)
edge.col <- rep('gray30', 16)
edge.col[c(1,2,6)] <- 'red'
edge.col[10:12] <- 'blue'
xx <- plot(tree, show.tip.label=FALSE, x.lim=c(0,4),y.lim=c(0.6,9.4), edge.col=edge.col, edge.width=2, no.margin=TRUE)
edgeLab <- with(edDemo$branch, paste(len, '/' , nSp)) [tree$edge[,2]]
edgelabels(edgeLab, 1:16, adj=c(0.5,-0.3), frame='none', col='gray30', cex=0.7)
edgeLab <- edDemo$branch$ED[tree$edge[,2]]
edgelabels(sprintf("%0.2f", edgeLab), 1:16, adj=c(0.5,1.3), frame='none', col=edge.col, cex=0.9)
tipLab <- with(edDemo$spp, sprintf("%0.2f", ED))
tipCol <- rep('gray30', 9)
tipCol[c(3,6)] <- c('red','blue')
tiplabels(text=tipLab, adj=c(-0.25,0.5), frame='none', col=tipCol)
par(usr=c(0,1,0,1))
text(0.1, 0.9, "a)", cex=1.2)
par(mar=c(3,3,1,1))
plot(density(primateED$spp$ED), main='', xlab='Species ED score')
edMax <- max(primateED$spp$ED)
arrows(edMax, 0.04, edMax, 0.01, col='red', len=0.1)
par(usr=c(0,1,0,1), mar=c(0,0,0,0))
text(0.1, 0.9, "b)", cex=1.2)
maxSpp <- which(primateED$spp$ED == edMax)
xx <- which(rowSums(primates.cm$clade.matrix[,maxSpp])> 0)
edgeCol <- rep('grey30', length(primates.tree$edge.length))
edgeCol[match(xx, primates.tree$edge[,2])] <- 'red'
plot(primates.tree, show.tip=FALSE, no.margin=TRUE, edge.col=edgeCol)
par(usr=c(0,1,0,1))
text(0.1, 0.9, "c)", cex=1.2)
###################################################
### code chunk number 34: setSeed
###################################################
# reasonable run time and reasonable results (on my Mac,
# no idea if this will carry on to R-Forge.)
set.seed(2345)
###################################################
### code chunk number 35: simpleGrowTree
###################################################
basicTree <- growTree(b=1, d=0, halt=20, grain=Inf)
extendTree <- growTree(b=1, d=0, halt=20, extend.proportion=1, grain=Inf)
timeLimit <- growTree(b=1, d=0, halt=expression(clade.age>=3), grain=0.01)
extinctTree <- growTree(b=1, d=0.1, halt=expression(nExtinctTip>=3), extend.proportion=1, grain=Inf)
densityDependence <- growTree(b=expression(2/nExtantTip), d=0, halt=50, grain=Inf)
increasingExtinction <- growTree(b=1, d=expression(0.2 * clade.age), halt=50)
###################################################
### code chunk number 36: simpleGrowTreePlots
###################################################
par(mfrow=c(2,3), mar=c(1.5,0.5,0,0.5), tcl=-0.2, mgp=c(1,0.5,0), cex.axis=0.8)
plot(basicTree$phy , root.edge=TRUE); axis(1); par(usr=c(0,1,0,1)); text(0.1,0.06,"a)")
plot(extendTree$phy , root.edge=TRUE); axis(1); par(usr=c(0,1,0,1)); text(0.1,0.06,"b)")
plot(timeLimit$phy , root.edge=TRUE); axis(1); par(usr=c(0,1,0,1)); text(0.1,0.06,"c)")
plot(extinctTree$phy, root.edge=TRUE); axis(1); par(usr=c(0,1,0,1)); text(0.1,0.06,"d)")
plot(densityDependence$phy, root.edge=TRUE); axis(1); par(usr=c(0,1,0,1)); text(0.1,0.06,"e)")
plot(increasingExtinction$phy, root.edge=TRUE); axis(1); par(usr=c(0,1,0,1)); text(0.1,0.06,"f)")
###################################################
### code chunk number 37: setSeed
###################################################
# reasonable run time and reasonable results (on my Mac,
# no idea if this will carry on to R-Forge.)
set.seed(421)
###################################################
### code chunk number 38: caper.rnw:1151-1168
###################################################
# > pantheria <- read.delim('PanTHERIA_1-0_WR05_Aug2008.txt', na.string='-999.00')
# > vars <- log(pantheria[, c(7,21)])
# > cov(vars, use='complete')
# X5.1_AdultBodyMass_g X15.1_LitterSize
# X5.1_AdultBodyMass_g 10.0038050 -0.6544125
# X15.1_LitterSize -0.6544125 0.4427426
# > sum(complete.cases(vars))
# [1] 2325
# > mean(vars,na.rm=TRUE)
# X5.1_AdultBodyMass_g X15.1_LitterSize
# 5.4749827 0.6905053
mammalMeans <- c(logBodyMass=5.48, logLitterSize=0.69)
simpleBrownian <- growTree(halt=100, ct.start=mammalMeans, extend.proportion=1, grain=Inf)
mammalVar <- c(10, 0.44)
varBrownian <- growTree(halt=100, ct.start=mammalMeans, ct.var=mammalVar, extend.proportion=1, grain=Inf)
mammalCovar <- matrix(c(10,-0.65, -0.65, 0.44), ncol=2)
covarBrownian <- growTree(halt=100, ct.start=mammalMeans, ct.var=mammalCovar, extend.proportion=1, grain=Inf)
###################################################
### code chunk number 39: contTraitPlots
###################################################
## par(mfrow=c(1,3), mar=c(0,0.5,0,4), tcl=-0.2, mgp=c(1,0.5,0), cex.axis=0.8)
##
## plot(simpleBrownian, show.tip=FALSE)
##
## rightEdge <- rep(par('usr')[2], 25)
## bm <- with(simpleBrownian, ct.data$logBodyMass[ match(tip.label, ct.data$node)])
## points(rightEdge, 1:25, cex=bm / 3, xpd=NA)
## ls <- with(simpleBrownian, ct.data$logLitterSize[ match(tip.label, ct.data$node)])
## points(rightEdge*1.1, 1:25, cex=ls * 2, xpd=NA)
##
## plot(varBrownian, show.tip=FALSE)
##
## rightEdge <- rep(par('usr')[2], 25)
## bm <- with(varBrownian, ct.data$logBodyMass[ match(tip.label, ct.data$node)])
## points(rightEdge, 1:25, cex=bm / 3, xpd=NA)
## ls <- with(varBrownian, ct.data$logLitterSize[ match(tip.label, ct.data$node)])
## points(rightEdge*1.1, 1:25, cex=ls * 2, xpd=NA)
##
##
##
## plot(covarBrownian, show.tip=FALSE)
##
## rightEdge <- rep(par('usr')[2], 25)
## bm <- with(covarBrownian, ct.data$logBodyMass[ match(tip.label, ct.data$node)])
## points(rightEdge, 1:25, cex=bm / 3, xpd=NA)
## ls <- with(covarBrownian, ct.data$logLitterSize[ match(tip.label, ct.data$node)])
## points(rightEdge*1.1, 1:25, cex=ls *2 , xpd=NA)
par(mfrow=c(1,3), mar=c(2.5,2.5,0.5,0.5), tcl=-0.2, mgp=c(1.5,0.5,0), cex.axis=0.8)
stips <- simpleBrownian$data
vtips <- varBrownian$data
cvtips <- covarBrownian$data
lims <- sapply( rbind(stips, vtips,cvtips)[, c('logBodyMass','logLitterSize')], range)
plot(logBodyMass ~ logLitterSize, data=stips, xlim=lims[,2], ylim=lims[,1])
plot(logBodyMass ~ logLitterSize, data=vtips, xlim=lims[,2], ylim=lims[,1])
plot(logBodyMass ~ logLitterSize, data=cvtips, xlim=lims[,2], ylim=lims[,1])
###################################################
### code chunk number 40: discreteTraitExamples
###################################################
flight <- matrix(c(0,0.1,0.001,0), ncol=2)
flightNames <- c('ter','fly')
dimnames(flight) <- list(flightNames, flightNames)
trophic <- matrix(c(0,0.2,0.01,0.2,0,0.1,0,0.05,0), ncol=3)
trophNames <- c('herb','omni','carn')
dimnames(trophic) <- list(trophNames, trophNames)
discTraits <- list(flight=flight, trophic=trophic)
discreteTree <- growTree(halt=60, dt=discTraits, extend.proportion=1, grain=Inf)
###################################################
### code chunk number 41: discreteTraitPlot
###################################################
par(mar=c(0,0,0,0), tcl=-0.2, mgp=c(1,0.5,0), cex.axis=0.8)
plot(discreteTree$phy, show.tip=FALSE)
lastPP <- get("last_plot.phylo", envir = .PlotPhyloEnv)
traitsByNode <- with(discreteTree, rbind( cbind(node=phy$tip.label, data[, c('flight','trophic')]), node.data[, c('node','flight','trophic')]))
traitsByNode <- traitsByNode[match(1:199, traitsByNode$node), ]
with(lastPP, points(xx + 0.06, yy, pch=21, col=unclass(traitsByNode$flight), xpd=NA, cex=0.6))
with(lastPP, points(xx + 0.12, yy, pch=22, col=unclass(traitsByNode$trophic), xpd=NA, cex=0.6))
###################################################
### code chunk number 42: setseed
###################################################
set.seed(95132)
###################################################
### code chunk number 43: patencyModel
###################################################
bLatency <- expression((0.2 *lin.age)/(0.1 + lin.age))
dSenesce <- expression(lin.age * 0.02)
halt <- expression(nExtantTip >= 60)
latencyTree <- growTree(b=bLatency, d=dSenesce, halt=halt, grain=0.01)
traitMean <- c(logBodyMass=5.48)
traitVar <- c(logBodyMass=10)
bLatTrait <- expression(((0.2 + ((5.48 - logBodyMass)/25))*lin.age)/(0.1 + lin.age))
latTraitTree <- growTree(b=bLatTrait, d=dSenesce, halt=halt, ct.start=traitMean, ct.var=traitVar, grain=0.01)
###################################################
### code chunk number 44: patencyPlot
###################################################
par(mfrow=c(2,2), mar=c(2.5,2.5,1,1), tcl=-0.2, mgp=c(1.5,0.5,0), cex.axis=0.8)
curve(0.02*x, xlim=c(0,20), ylab='Rate', xlab="Lineage age")
curve(((0.2 + ((5.48 - 5.48)/25))*x)/(0.1 + x), add=TRUE, col='red')
curve(((0.2 + ((5.48 - 3.48)/25))*x)/(0.1 + x), add=TRUE, col='red', lty=2)
curve(((0.2 + ((5.48 - 7.48)/25))*x)/(0.1 + x), add=TRUE, col='red', lty=2)
plot(latencyTree$phy, no.margin=TRUE, cex=0.8)
plot(latTraitTree$phy, no.margin=TRUE, cex=0.8, show.tip=FALSE)
# rightEdge <- par('usr')[2] - 0.75
# tips <- seq_along(latTraitTree$tip.label)
# bm <- with(latTraitTree, ct.data$logBodyMass[ match(tips, ct.data$node)])
#
# rect(rightEdge - 5.48/20, 0 , rightEdge + 5.48/20, max(tips)+1, col='grey80', border=NA)
#
# arrows(rightEdge-bm/20, tips, rightEdge+bm/20, tips, code=0, col='red', xpd=NA, lwd=2, lend=2)
###################################################
### code chunk number 45: inheritanceExample1
###################################################
traitMean <- c(logBodyMass=5.48)
traitVar <- c(logBodyMass=10)
inherit <- list(logBodyMass=expression(logBodyMass * c(0.8, 1.2)))
inheritTree <- growTree(b=1, halt=40, ct.start=traitMean, ct.var=traitVar, inheritance=inherit, grain=Inf, extend.proportion=1)
###################################################
### code chunk number 46: inheritanceExamples2
###################################################
rNames <- c("AB", "A", "B")
regions <- list(region = matrix(c(0, 0.05, 0.05, 0.1, 0,0,0.1,0,0), ncol=3,
dimnames=list(rNames,rNames)))
extinct <- expression(ifelse(region == "AB", 0.0001, 0.01))
spec <- list(regA_spec = expression(ifelse(region == "AB" | region == "A", 1, 0)),
regB_spec = expression(ifelse(region == "AB" | region == "B", 0.5, 0)))
inherit <- list(region = expression(if(winnerName=="regB_spec" && region[1] == "AB") c("B","A") else region),
region = expression(if(winnerName=="regA_spec" && region[1] == "AB") c("A","B") else region))
biogeogTree <- growTree(b=spec, d=extinct, halt=80, inherit=inherit, dt.rates=regions, inf.rates="quiet", grain=Inf)
###################################################
### code chunk number 47: epochExample
###################################################
epochTree <- growTree(halt=100, output.lineages=TRUE, grain=Inf)
epochTree2 <- growTree(d=5, halt=expression(nExtantTip==20), linObj=epochTree, output.lineages=TRUE, grain=Inf)
epochTree3 <- growTree(linObj=epochTree2, halt=100, grain=Inf)
###################################################
### code chunk number 48: inheritancePlots
###################################################
par(mfrow=c(1,3), mar=c(1,1,1,1))
depth <- VCV.array(inheritTree$phy)[1,1]
plot(inheritTree$phy, no.margin=TRUE, cex=0.8, show.tip=FALSE, root.edge=TRUE, x.lim=c(0,depth*1.1))
rightEdge <- depth*1.05
tips <- seq_along(inheritTree$phy$tip.label)
bm <- inheritTree$data$logBodyMass
sc <- max(bm) / (depth*0.04)
rect(rightEdge - 5.48/sc, 0 , rightEdge + 5.48/sc, max(tips)+1, col='grey80', border=NA)
arrows(rightEdge-bm/sc, tips, rightEdge+bm/sc, tips, code=0, col='red', xpd=NA, lwd=2, lend=2)
plot(biogeogTree$phy, edge.col= unclass(biogeogTree$data$region), show.tip.label=FALSE, root.edge=TRUE)
plot(epochTree3$phy, show.tip.label=FALSE)
###################################################
### code chunk number 49: cladeMatrixExample
###################################################
data(perissodactyla)
perisso <- comparative.data(perissodactyla.tree, perissodactyla.data, Binomial)
perissoCM <- clade.matrix(perisso$phy)
str(perissoCM)
perissoCM$clade.matrix
###################################################
### code chunk number 50: cladeMembersExample
###################################################
data(perissodactyla)
perisso <- comparative.data(perissodactyla.tree, perissodactyla.data, Binomial)
clade.members(15, perisso$phy)
clade.members(15, perisso$phy, tip.labels=TRUE)
clade.members(15, perisso$phy, tip.labels=TRUE, include.nodes=TRUE)
str(clade.members.list(perisso$phy))
str(clade.members.list(perisso$phy, tip.labels=TRUE))
###################################################
### code chunk number 51: vcvArrayExample
###################################################
data(perissodactyla)
perisso <- comparative.data(perissodactyla.tree, perissodactyla.data, Binomial)
str(VCV.array(perisso$phy))
str(VCV.array(perisso$phy, dim=3))
|
/inst/doc/caper.R
|
no_license
|
cran/caper
|
R
| false | false | 32,542 |
r
|
### R code from vignette source 'caper.rnw'
### Encoding: UTF-8
###################################################
### code chunk number 1: setup
###################################################
library(caper)
## whilst code is being tested, load most recent versions from the pkg repository
for(f in dir('../../R', full=TRUE)) (source(f))
###################################################
### code chunk number 2: whycaper
###################################################
par(mfrow=c(2,2), mar=c(3,3,1,1), mgp=c(2,0.7,0))
plot(c(0,13),c(0,10), typ="n", bty="n", xaxt="n",yaxt="n", xlab="", ylab="", xaxs="i",yaxs="i")
lines(c(0,7), c(5,8.5))
lines(c(0,7), c(5,1.5))
lines(c(3.5,7), c(3.25,5))
polygon(c(7,10,10), y=c(8.5,10,7))
polygon(c(7,10,10), y=c(5,6.5,3.5))
polygon(c(7,10,10), y=c(1.5,3,0))
points( c(0.5,1.5) +0.5, c(5,5), cex=1, col=1:2)
points(c(7.5,8.5)+0.5, c(8.5,8.5), cex=1, col=1:2)
points(c(4,5)+0.5, c(3.25,3.25), cex=1.5, col=1:2)
points(c(7.5,8.5)+0.5, c(5,5), cex=1.5, col=1:2)
points(c(7.5,8.5)+0.5, c(1.5,1.5), cex=2, col=1:2)
rect(11 - c(.3,.2,.1), c(0,3.5,7), 11 + c(.3,.2,.1) , c(3,6.5,10))
rect(12 - c(.3,.2,.1), c(0,3.5,7), 12 + c(.3,.2,.1) , c(3,6.5,10), border="red")
par(usr=c(0,1,0,1)); text(0.1,0.9, cex=2,"a")
dat <- data.frame(x = rnorm(120, mean= rep(2:4, each=40), sd=0.5),
y = rnorm(120, mean= rep(2:4, each=40), sd=0.5),
tx = gl(3,40))
plot(y~x, col=unclass(tx), data=dat, xaxt="n", xlab="", ylab="")
axis(1, col.axis="red")
abline(lm(y~x, data=dat))
for(sub in split(dat, dat$tx)) abline(lm(y~x, data=sub), col=unclass(sub$tx)[1], lty=2)
plot(c(0,13),c(0,10), typ="n", bty="n", xaxt="n",yaxt="n", xlab="", ylab="", xaxs="i",yaxs="i")
lines(c(0,7), c(5,8.5))
lines(c(0,7), c(5,1.5))
lines(c(3.5,7), c(3.25,5))
polygon(c(7,10,10), y=c(8.5,10,7))
polygon(c(7,10,10), y=c(5,6.5,3.5))
polygon(c(7,10,10), y=c(1.5,3,0))
points(c(0.5,1.5)+0.5, c(5,5), cex=1, col=1:2)
points(c(7.5,8.5)+0.5, c(8.5,8.5), cex=1, col=1:2)
points(c(4,5)+0.5, c(3.25,3.25), cex=c(1,1.5), col=1:2)
points(c(7.5,8.5)+0.5, c(5,5), cex=c(1,1.5), col=1:2)
points(c(7.5,8.5)+0.5, c(1.5,1.5), cex=c(1,2), col=1:2)
polygon(11 + c(-0,-0.1,0.1,0), c(3,0,0,3))
polygon(12 + c(-0.2,-0.3,0.3,0.2), c(3,0,0,3), border="red")
polygon(11 + c(-0,-0.1,0.1,0), c(6.5,3.5,3.5,6.5))
polygon(12 + c(-0.1,-0.2,0.2,0.1), c(6.5,3.5,3.5,6.5), border="red")
polygon(11 + c(-0,-0.1,0.1,0), c(10,7.5,7.5,10))
polygon(12 + c(-0.0,-0.1,0.1,0.), c(10,7.5,7.5,10), border="red")
par(usr=c(0,1,0,1)); text(0.1,0.9, cex=2, "b")
dat <- data.frame(x = rnorm(120, mean= rep(2:4, each=40), sd=0.5),
tx = gl(3,40))
dat$y <- dat$x - rnorm(120, mean= rep(0:2, each=40), sd=0.5)
plot(y~x, col=unclass(tx), data=dat, xaxt="n", xlab="", ylab="")
axis(1, col.axis="red")
abline(lm(y~x, data=dat))
for(sub in split(dat, dat$tx)) abline(lm(y~x, data=sub), col=unclass(sub$tx)[1], lty=2)
###################################################
### code chunk number 3: comparative.data
###################################################
phy <- read.tree(text='(((B:2,A:2):1,D:3):1,(C:1,E:1):3);')
dat <- data.frame(
taxa=c("A","B","C","D","E"),
n.species=c(5,9,12,1,13), mass=c(4.1,4.5,5.9,3.0,6.0)
)
cdat <- comparative.data(data=dat, phy=phy, names.col="taxa")
print(cdat)
###################################################
### code chunk number 4: na.omit
###################################################
data(perissodactyla)
(perisso <- comparative.data(perissodactyla.tree, perissodactyla.data, Binomial))
# but this can be turned off
(perissoFull <- comparative.data(perissodactyla.tree, perissodactyla.data, Binomial, na.omit=FALSE))
na.omit(perisso)
###################################################
### code chunk number 5: na.omit2
###################################################
comparative.data(perissodactyla.tree, perissodactyla.data, Binomial, scope= log.female.wt ~ log.gestation.length)
na.omit(perissoFull, scope=log.female.wt ~ log.gestation.length + Territoriality)
###################################################
### code chunk number 6: subset
###################################################
subset(perissoFull, subset=! is.na(Territoriality))
subset(perissoFull, subset=log.female.wt > 5.5, select=c(log.female.wt, log.gestation.length))
###################################################
### code chunk number 7: squarebracket
###################################################
horses <- grep('Equus', perissoFull$phy$tip.label)
perissoFull[horses,]
perissoFull[horses, 2:3]
###################################################
### code chunk number 8: pglsSetup
###################################################
## demo tree
z <- structure(list(edge = structure(c(11L, 15L, 18L, 18L, 15L, 16L,
16L, 11L, 12L, 13L, 13L, 19L, 19L, 12L, 14L, 14L, 17L, 17L, 15L,
18L, 1L, 2L, 16L, 3L, 4L, 12L, 13L, 5L, 19L, 6L, 7L, 14L, 8L,
17L, 9L, 10L), .Dim = c(18L, 2L)), edge.length = c(5.723, 2.186,
1.09, 1.09, 0.627, 2.649, 2.649, 1.049, 1.411, 6.54, 5.538, 1.001,
1.001, 1.863, 6.088, 4.777, 1.312, 1.312), tip.label = c("t8",
"t6", "t4", "t10", "t9", "t5", "t7", "t1", "t3", "t2"), Nnode = 9L), .Names = c("edge",
"edge.length", "tip.label", "Nnode"), class = "phylo", order = "cladewise")
V <- VCV.array(z)
###################################################
### code chunk number 9: vcvFig
###################################################
ec <- rep('grey50', 18)
ec[c(1,5,7)] <- 'red'
ec[c(8,14)] <- 'blue'
plot(z, no.margin=TRUE, cex=0.6, label.offset=0.3, edge.col=ec)
###################################################
### code chunk number 10: bltrans
###################################################
## internal branch lengths
internal <- z$edge[,2] > 10
vlines <- 9 * c(0, 0.5, 1, 1.5)
zz <- z
# layout
layout(matrix(c(1:9), ncol=3))
par(mar=c(0,0.5,2,0.5))
cx <- 0.8
ln <- 0.5
xl <- c(0,15)
# lambda
pvals <- c(1.4, 0.5)
ec <- ifelse(internal,'red', 'grey30')
## zz$edge.length <- ifelse(internal, z$edge.length*pvals[1], z$edge.length)
## plot(zz, edge.col=ec, x.lim=xl, label.offset=0.2)
## mtext(bquote(lambda == .(pvals[1])), side=3, cex=cx, line=ln)
## abline(v=vlines, lty=2, col='grey')
##
## plot(z, edge.col=ec, x.lim=xl, label.offset=0.2)
## abline(v=vlines, lty=2, col='grey')
## mtext(expression(lambda == 1), side=3, cex=cx, line=ln)
##
## zz$edge.length <- ifelse(internal, z$edge.length*pvals[2], z$edge.length)
## plot(zz, edge.col=ec, x.lim=xl, label.offset=0.2)
## mtext(bquote(lambda == .(pvals[2])), side=3, cex=cx, line=ln)
## abline(v=vlines, lty=2, col='grey')
# get the branching structure back from the matrix
dd <- ifelse(lower.tri(V) | upper.tri(V), V * pvals[1], V)
ddh <- as.phylo(hclust(dist(dd)))
plot(ddh, edge.col = 'red', x.lim=xl, label.offset=0.2)
mtext(bquote(lambda == .(pvals[1])), side=3, cex=cx, line=ln)
abline(v=vlines, lty=2, col='grey')
plot(z, edge.col=ec, x.lim=xl, label.offset=0.2)
abline(v=vlines, lty=2, col='grey')
mtext(expression(lambda == 1), side=3, cex=cx, line=ln)
dd <- ifelse(lower.tri(V) | upper.tri(V), V * pvals[2], V)
ddh <- as.phylo(hclust(dist(dd)))
plot(ddh, edge.col = 'red', x.lim=xl, label.offset=0.2)
mtext(bquote(lambda == .(pvals[2])), side=3, cex=cx, line=ln)
abline(v=vlines, lty=2, col='grey')
# delta:
pvals <- c(1.2, 0.5)
# get the branching structure back from the matrix
dd <- V ^ pvals[1]
ddh <- as.phylo(hclust(dist(dd)))
plot(ddh, edge.col = 'red', x.lim=xl, label.offset=0.2)
mtext(bquote(delta == .(pvals[1])), side=3, cex=cx, line=ln)
abline(v=vlines, lty=2, col='grey')
plot(z, edge.col='red', x.lim=xl, label.offset=0.2)
abline(v=vlines, lty=2, col='grey')
mtext(expression(delta == 1), side=3, cex=cx, line=ln)
dd <- V ^ pvals[2]
ddh <- as.phylo(hclust(dist(dd)))
plot(ddh, edge.col='red', x.lim=xl, label.offset=0.2)
mtext(bquote(delta == .(pvals[2])), cex=cx, line=ln)
abline(v=vlines, lty=2, col='grey')
# kappa
pvals <- c(1.2, 0.0)
ec <- ifelse(internal,'red', 'grey30')
zz$edge.length <- z$edge.length^pvals[1]
plot(zz, edge.col = 'red', x.lim=xl, label.offset=0.2)
mtext(bquote(kappa == .(pvals[1])), side=3, cex=cx, line=ln)
abline(v=vlines, lty=2, col='grey')
plot(z, edge.col='red', x.lim=xl, label.offset=0.2)
abline(v=vlines, lty=2, col='grey')
mtext(expression(kappa == 1), side=3, cex=cx, line=ln)
zz$edge.length <- z$edge.length^pvals[2]
plot(zz, edge.col='red', x.lim=xl, label.offset=0.2)
mtext(bquote(kappa == .(pvals[1])), cex=cx, line=ln)
abline(v=vlines, lty=2, col='grey')
###################################################
### code chunk number 11: basicPGLS
###################################################
data(shorebird)
shorebird <- comparative.data(shorebird.tree, shorebird.data, Species, vcv=TRUE)
mod <- pgls(log(Egg.Mass) ~ log(M.Mass), shorebird)
print(mod)
summary(mod)
###################################################
### code chunk number 12: lambdaOpt
###################################################
data(shorebird)
shorebird <- comparative.data(shorebird.tree, shorebird.data, Species, vcv=TRUE, vcv.dim=3)
mod <- pgls(log(Egg.Mass) ~ log(M.Mass), shorebird, lambda='ML')
summary(mod)
mod.l <- pgls.profile(mod, 'lambda')
mod.d <- pgls.profile(mod, 'delta')
mod.k <- pgls.profile(mod, 'kappa')
plot(mod.l); plot(mod.d); plot(mod.k)
###################################################
### code chunk number 13: lambdaOptPlot
###################################################
par(mar=c(4.5,3,1,1), mfrow=c(1,3), mgp=c(1.8,0.8,0), tcl=-0.2)
plot(mod.l); plot(mod.d); plot(mod.k)
###################################################
### code chunk number 14: pglsPlotCmd
###################################################
par(mfrow=c(2,2), mar=c(3,3,1,1), mgp=c(2,0.7,0), tcl=-0.2)
plot(mod)
###################################################
### code chunk number 15: pglsCrit
###################################################
mod1 <- pgls(log(Egg.Mass) ~ log(M.Mass) * log(F.Mass), shorebird)
anova(mod1)
mod2 <- pgls(log(Egg.Mass) ~ log(M.Mass) + log(F.Mass), shorebird)
mod3 <- pgls(log(Egg.Mass) ~ log(M.Mass) , shorebird)
mod4 <- pgls(log(Egg.Mass) ~ 1, shorebird)
anova(mod1, mod2, mod3, mod4)
AIC(mod1, mod2, mod3, mod4)
###################################################
### code chunk number 16: crunchExample
###################################################
data(shorebird)
shorebird.data$lgEgg.Mass <- log(shorebird.data$Egg.Mass)
shorebird.data$lgM.Mass <- log(shorebird.data$M.Mass)
shorebird.data$lgF.Mass <- log(shorebird.data$F.Mass)
shorebird <- comparative.data(shorebird.tree, shorebird.data, Species)
crunchMod <- crunch(lgEgg.Mass ~ lgF.Mass + lgM.Mass, data=shorebird)
summary(crunchMod)
###################################################
### code chunk number 17: brunchExample
###################################################
perisso <- comparative.data(perissodactyla.tree, perissodactyla.data, Binomial)
brunchMod <- brunch(log.female.wt ~ Territoriality, data=perisso)
caic.table(brunchMod)
###################################################
### code chunk number 18: brunchPlot
###################################################
bwd <- rep(1,15)
bwd[c(5,6,11,12,9,13,14,15)] <- 3
plot(perisso$phy, 'cladogram', use.edge.length=FALSE, label.offset=0.4, show.node=TRUE, cex=0.7, show.tip=FALSE, x.lim=c(0,12), no.margin=TRUE, edge.width=bwd)
points(rep(8.25,9), 1:9, pch=ifelse(perisso$data$Terr=='Yes', 1,19))
text(rep(8.5,9), 1:9, perisso$phy$tip.label, font=3, adj=0)
###################################################
### code chunk number 19: macrocaicExample
###################################################
data(IsaacEtAl)
primates <- comparative.data(primates.tree, primates.data, binomial, na.omit=FALSE)
primatesBodySize <- macrocaic(species.rich ~ body.mass, data=primates)
summary(primatesBodySize)
###################################################
### code chunk number 20: phylodScale
###################################################
data(BritishBirds)
BritishBirds <- comparative.data(BritishBirds.tree, BritishBirds.data, binomial)
redPD <- phylo.d(BritishBirds, binvar=Red_list)
par(mar=c(3,3,2,1), mgp=c(1.8,0.8,0), tcl=-0.3)
plot(density(redPD$Permutations$random, bw=0.5), main='', xlim=c(10,55), col='blue', xlab='Sum of character change')
lines(density(redPD$Permutations$brownian,bw=0.5), col='red')
abline(v=redPD$Parameters$Observed)
abline(v=redPD$Parameters$Observed, col='grey')
abline(v=redPD$Parameters$MeanRandom, col='blue')
abline(v=redPD$Parameters$MeanBrownian, col='red')
with(redPD$Parameters, axis(3, at=c(MeanBrownian, Observed, MeanRandom), labels=c(0, round(redPD$DEstimate,2),1), mgp=c(1.5,0.7,0.25)))
mtext(expression(italic(D)==phantom(x)), side=3, at=25, line=1.2)
###################################################
### code chunk number 21: phylodDemo
###################################################
data(BritishBirds)
BritishBirds <- comparative.data(BritishBirds.tree, BritishBirds.data, binomial)
redPhyloD <- phylo.d(BritishBirds, binvar=Red_list)
print(redPhyloD)
###################################################
### code chunk number 22: caicDiagExample
###################################################
par(mfrow=c(2,3))
shorebird <- comparative.data(shorebird.tree, shorebird.data, Species)
crunchMod <- crunch(Egg.Mass ~ M.Mass, data=shorebird)
caic.diagnostics(crunchMod)
shorebird.data$lgEgg.Mass <- log(shorebird.data$Egg.Mass)
shorebird.data$lgM.Mass <- log(shorebird.data$M.Mass)
shorebird <- comparative.data(shorebird.tree, shorebird.data, Species)
crunchMod2 <- crunch(lgEgg.Mass ~ lgM.Mass, data=shorebird)
caic.diagnostics(crunchMod2)
###################################################
### code chunk number 23: caicDiagExamplePlot
###################################################
par(mfrow=c(2,3), mar=c(3,3,1,1), mgp=c(2,0.7,0), tcl=-0.2)
shorebird <- comparative.data(shorebird.tree, shorebird.data, Species)
# need to store the output of caic diagnostics to stop it
# showing up in the float
crunchMod <- crunch(Egg.Mass ~ M.Mass, data=shorebird)
x <- caic.diagnostics(crunchMod)
crunchMod2 <- crunch(lgEgg.Mass ~ lgM.Mass, data=shorebird)
x <- caic.diagnostics(crunchMod2)
###################################################
### code chunk number 24: caicRobustExample
###################################################
data(shorebird)
shorebird <- comparative.data(shorebird.tree, shorebird.data, Species)
crunchMod <- crunch(Egg.Mass ~ M.Mass, data=shorebird)
caic.diagnostics(crunchMod)
crunchModRobust <- caic.robust(crunchMod)
caic.diagnostics(crunchModRobust, outlier=2)
###################################################
### code chunk number 25: caicRobustExamplePlot
###################################################
par(mfrow=c(2,3), mar=c(3,3,1,1), mgp=c(2,0.7,0), tcl=-0.2)
data(shorebird)
shorebird <- comparative.data(shorebird.tree, shorebird.data, Species)
# need to store the output of caic diagnostics to stop ip showing up in the float
crunchMod <- crunch(Egg.Mass ~ M.Mass, data=shorebird)
x <-caic.diagnostics(crunchMod)
crunchModRobust <- caic.robust(crunchMod)
x <-caic.diagnostics(crunchModRobust, outlier=2)
###################################################
### code chunk number 26: modelCrit
###################################################
data(shorebird)
shorebird.data$lgEgg.Mass <- log(shorebird.data$Egg.Mass)
shorebird.data$lgM.Mass <- log(shorebird.data$M.Mass)
shorebird.data$lgF.Mass <- log(shorebird.data$F.Mass)
shorebird <- comparative.data(shorebird.tree, shorebird.data, Species)
crunchMod <- crunch(lgEgg.Mass ~ lgF.Mass + lgM.Mass, data=shorebird)
par(mfrow=c(2,2))
plot(crunchMod)
###################################################
### code chunk number 27: modelCritPlot
###################################################
par(mfrow=c(2,2), mar=c(3,3,2,1), mgp=c(2,0.7,0), tcl=-0.2)
data(shorebird)
crunchMod <- crunch(lgEgg.Mass ~ lgF.Mass + lgM.Mass, data=shorebird)
plot(crunchMod)
###################################################
### code chunk number 28: modelComparison
###################################################
shorebird.data$lgEgg.Mass <- log(shorebird.data$Egg.Mass)
shorebird.data$lgM.Mass <- log(shorebird.data$M.Mass)
shorebird.data$lgF.Mass <- log(shorebird.data$F.Mass)
shorebird <- comparative.data(shorebird.tree, shorebird.data, Species)
cMod1 <- crunch(lgEgg.Mass ~ lgM.Mass * lgF.Mass, data=shorebird)
cMod2 <- crunch(lgEgg.Mass ~ lgM.Mass + lgF.Mass, data=shorebird)
cMod3 <- crunch(lgEgg.Mass ~ lgM.Mass , data=shorebird)
anova(cMod1, cMod2, cMod3)
AIC(cMod1, cMod2, cMod3)
###################################################
### code chunk number 29: fuscoDemo
###################################################
data(syrphidae)
syrphidae <- comparative.data(phy=syrphidaeTree, dat=syrphidaeRich, names.col=genus)
summary(fusco.test(syrphidae, rich=nSpp))
summary(fusco.test(syrphidae, tipsAsSpecies=TRUE))
###################################################
### code chunk number 30: pdExample
###################################################
data(BritishBirds)
BritishBirds.cm <- clade.matrix(BritishBirds.tree)
redListSpecies <- with(BritishBirds.data, binomial[Red_list==1])
obs <- pd.calc(BritishBirds.cm, redListSpecies, method="TBL")
rand <- pd.bootstrap(BritishBirds.cm, ntips=length(redListSpecies), rep=1000, method="TBL")
plot(density(rand), main='Total branch length for random sets of 32 species.')
abline(v=obs, col='red')
###################################################
### code chunk number 31: pdMeasurePlot
###################################################
tree <- read.tree(text="((((A:1,B:1):1.5,C:2.5):0.5,(D:0.6,E:0.6):2.4):0.5,((F:1.9,G:1.9):0.8,(H:1.6,I:1.6):1.1):0.8):0.2;")
clmat <- clade.matrix(tree)
tips <- c("A","C","D","E","G","H")
par(mfrow=c(2,3), mar=rep(1,4))
tip.col <- rep('grey', length=length(tree$tip.label))
tip.col[c(1,3,4,5,7,8)] <- 'black'
# TBL
cl <- rep('black', length=length(tree$edge.length))
cl[c(1,2,3,4,6,7,8,9,10,11,13,14,15)] <- 'red'
plot(tree, label.offset=0.1, cex=1.2, tip.color=tip.col, x.lim=3.8, edge.col=cl)
text(0.2,8.5, "TBL", cex=1.2, adj=c(0,0))
# UEH
cl <- rep('black', length=length(tree$edge.length))
cl[c(3,4,6,8,9,11,14,13,15)] <- 'red'
plot(tree, label.offset=0.1, cex=1.2, tip.color=tip.col, x.lim=3.8, edge.col=cl)
text(0.2,8.5, "UEH", cex=1.2, adj=c(0,0))
# SBL
cl <- rep('black', length=length(tree$edge.length))
cl[c(1,2,7,10)] <- 'red'
plot(tree, label.offset=0.1, cex=1.2, tip.color=tip.col, x.lim=3.8, edge.col=cl)
text(0.2,8.5, "SBL", cex=1.2, adj=c(0,0))
# TIP
cl <- rep('black', length=length(tree$edge.length))
cl[c(4,6,8,9,13,15)] <- 'red'
plot(tree, label.offset=0.1, cex=1.2, tip.color=tip.col, x.lim=3.8, edge.col=cl)
text(0.2,8.5, "TIP", cex=1.2, adj=c(0,0))
# MST
tips <- c("A","C")
tip.col <- rep('grey', length=length(tree$tip.label))
tip.col[c(1,3)] <- 'black'
cl <- rep('black', length=length(tree$edge.length))
cl[c(3,4,6)] <- 'red'
plot(tree, label.offset=0.1, cex=1.2, tip.color=tip.col, x.lim=3.8, edge.col=cl)
text(0.2,8.5, "MST", cex=1.2, adj=c(0,0))
par(mar=c(3,3,1,1))
plot(density(rand), main='', xlab= 'TBL values for red listed British birds.')
abline(v=obs, col='red')
###################################################
### code chunk number 32: edExample
###################################################
data(IsaacEtAl)
primates.cm <- clade.matrix(primates.tree)
primateED <- ed.calc(primates.cm)
str(primateED)
plot(density(primateED$spp$ED))
with(primateED, spp[spp$ED == max(spp$ED),])
###################################################
### code chunk number 33: edExamplePlots
###################################################
par(mfrow=c(1,3), mar=c(0,0,0,0), mgp=c(2,0.7,0))
edDemo <- ed.calc(clmat)
edge.col <- rep('gray30', 16)
edge.col[c(1,2,6)] <- 'red'
edge.col[10:12] <- 'blue'
xx <- plot(tree, show.tip.label=FALSE, x.lim=c(0,4),y.lim=c(0.6,9.4), edge.col=edge.col, edge.width=2, no.margin=TRUE)
edgeLab <- with(edDemo$branch, paste(len, '/' , nSp)) [tree$edge[,2]]
edgelabels(edgeLab, 1:16, adj=c(0.5,-0.3), frame='none', col='gray30', cex=0.7)
edgeLab <- edDemo$branch$ED[tree$edge[,2]]
edgelabels(sprintf("%0.2f", edgeLab), 1:16, adj=c(0.5,1.3), frame='none', col=edge.col, cex=0.9)
tipLab <- with(edDemo$spp, sprintf("%0.2f", ED))
tipCol <- rep('gray30', 9)
tipCol[c(3,6)] <- c('red','blue')
tiplabels(text=tipLab, adj=c(-0.25,0.5), frame='none', col=tipCol)
par(usr=c(0,1,0,1))
text(0.1, 0.9, "a)", cex=1.2)
par(mar=c(3,3,1,1))
plot(density(primateED$spp$ED), main='', xlab='Species ED score')
edMax <- max(primateED$spp$ED)
arrows(edMax, 0.04, edMax, 0.01, col='red', len=0.1)
par(usr=c(0,1,0,1), mar=c(0,0,0,0))
text(0.1, 0.9, "b)", cex=1.2)
maxSpp <- which(primateED$spp$ED == edMax)
xx <- which(rowSums(primates.cm$clade.matrix[,maxSpp])> 0)
edgeCol <- rep('grey30', length(primates.tree$edge.length))
edgeCol[match(xx, primates.tree$edge[,2])] <- 'red'
plot(primates.tree, show.tip=FALSE, no.margin=TRUE, edge.col=edgeCol)
par(usr=c(0,1,0,1))
text(0.1, 0.9, "c)", cex=1.2)
###################################################
### code chunk number 34: setSeed
###################################################
# reasonable run time and reasonable results (on my Mac,
# no idea if this will carry on to R-Forge.)
set.seed(2345)
###################################################
### code chunk number 35: simpleGrowTree
###################################################
basicTree <- growTree(b=1, d=0, halt=20, grain=Inf)
extendTree <- growTree(b=1, d=0, halt=20, extend.proportion=1, grain=Inf)
timeLimit <- growTree(b=1, d=0, halt=expression(clade.age>=3), grain=0.01)
extinctTree <- growTree(b=1, d=0.1, halt=expression(nExtinctTip>=3), extend.proportion=1, grain=Inf)
densityDependence <- growTree(b=expression(2/nExtantTip), d=0, halt=50, grain=Inf)
increasingExtinction <- growTree(b=1, d=expression(0.2 * clade.age), halt=50)
###################################################
### code chunk number 36: simpleGrowTreePlots
###################################################
par(mfrow=c(2,3), mar=c(1.5,0.5,0,0.5), tcl=-0.2, mgp=c(1,0.5,0), cex.axis=0.8)
plot(basicTree$phy , root.edge=TRUE); axis(1); par(usr=c(0,1,0,1)); text(0.1,0.06,"a)")
plot(extendTree$phy , root.edge=TRUE); axis(1); par(usr=c(0,1,0,1)); text(0.1,0.06,"b)")
plot(timeLimit$phy , root.edge=TRUE); axis(1); par(usr=c(0,1,0,1)); text(0.1,0.06,"c)")
plot(extinctTree$phy, root.edge=TRUE); axis(1); par(usr=c(0,1,0,1)); text(0.1,0.06,"d)")
plot(densityDependence$phy, root.edge=TRUE); axis(1); par(usr=c(0,1,0,1)); text(0.1,0.06,"e)")
plot(increasingExtinction$phy, root.edge=TRUE); axis(1); par(usr=c(0,1,0,1)); text(0.1,0.06,"f)")
###################################################
### code chunk number 37: setSeed
###################################################
# reasonable run time and reasonable results (on my Mac,
# no idea if this will carry on to R-Forge.)
set.seed(421)
###################################################
### code chunk number 38: caper.rnw:1151-1168
###################################################
# > pantheria <- read.delim('PanTHERIA_1-0_WR05_Aug2008.txt', na.string='-999.00')
# > vars <- log(pantheria[, c(7,21)])
# > cov(vars, use='complete')
# X5.1_AdultBodyMass_g X15.1_LitterSize
# X5.1_AdultBodyMass_g 10.0038050 -0.6544125
# X15.1_LitterSize -0.6544125 0.4427426
# > sum(complete.cases(vars))
# [1] 2325
# > mean(vars,na.rm=TRUE)
# X5.1_AdultBodyMass_g X15.1_LitterSize
# 5.4749827 0.6905053
mammalMeans <- c(logBodyMass=5.48, logLitterSize=0.69)
simpleBrownian <- growTree(halt=100, ct.start=mammalMeans, extend.proportion=1, grain=Inf)
mammalVar <- c(10, 0.44)
varBrownian <- growTree(halt=100, ct.start=mammalMeans, ct.var=mammalVar, extend.proportion=1, grain=Inf)
mammalCovar <- matrix(c(10,-0.65, -0.65, 0.44), ncol=2)
covarBrownian <- growTree(halt=100, ct.start=mammalMeans, ct.var=mammalCovar, extend.proportion=1, grain=Inf)
###################################################
### code chunk number 39: contTraitPlots
###################################################
## par(mfrow=c(1,3), mar=c(0,0.5,0,4), tcl=-0.2, mgp=c(1,0.5,0), cex.axis=0.8)
##
## plot(simpleBrownian, show.tip=FALSE)
##
## rightEdge <- rep(par('usr')[2], 25)
## bm <- with(simpleBrownian, ct.data$logBodyMass[ match(tip.label, ct.data$node)])
## points(rightEdge, 1:25, cex=bm / 3, xpd=NA)
## ls <- with(simpleBrownian, ct.data$logLitterSize[ match(tip.label, ct.data$node)])
## points(rightEdge*1.1, 1:25, cex=ls * 2, xpd=NA)
##
## plot(varBrownian, show.tip=FALSE)
##
## rightEdge <- rep(par('usr')[2], 25)
## bm <- with(varBrownian, ct.data$logBodyMass[ match(tip.label, ct.data$node)])
## points(rightEdge, 1:25, cex=bm / 3, xpd=NA)
## ls <- with(varBrownian, ct.data$logLitterSize[ match(tip.label, ct.data$node)])
## points(rightEdge*1.1, 1:25, cex=ls * 2, xpd=NA)
##
##
##
## plot(covarBrownian, show.tip=FALSE)
##
## rightEdge <- rep(par('usr')[2], 25)
## bm <- with(covarBrownian, ct.data$logBodyMass[ match(tip.label, ct.data$node)])
## points(rightEdge, 1:25, cex=bm / 3, xpd=NA)
## ls <- with(covarBrownian, ct.data$logLitterSize[ match(tip.label, ct.data$node)])
## points(rightEdge*1.1, 1:25, cex=ls *2 , xpd=NA)
par(mfrow=c(1,3), mar=c(2.5,2.5,0.5,0.5), tcl=-0.2, mgp=c(1.5,0.5,0), cex.axis=0.8)
stips <- simpleBrownian$data
vtips <- varBrownian$data
cvtips <- covarBrownian$data
lims <- sapply( rbind(stips, vtips,cvtips)[, c('logBodyMass','logLitterSize')], range)
plot(logBodyMass ~ logLitterSize, data=stips, xlim=lims[,2], ylim=lims[,1])
plot(logBodyMass ~ logLitterSize, data=vtips, xlim=lims[,2], ylim=lims[,1])
plot(logBodyMass ~ logLitterSize, data=cvtips, xlim=lims[,2], ylim=lims[,1])
###################################################
### code chunk number 40: discreteTraitExamples
###################################################
flight <- matrix(c(0,0.1,0.001,0), ncol=2)
flightNames <- c('ter','fly')
dimnames(flight) <- list(flightNames, flightNames)
trophic <- matrix(c(0,0.2,0.01,0.2,0,0.1,0,0.05,0), ncol=3)
trophNames <- c('herb','omni','carn')
dimnames(trophic) <- list(trophNames, trophNames)
discTraits <- list(flight=flight, trophic=trophic)
discreteTree <- growTree(halt=60, dt=discTraits, extend.proportion=1, grain=Inf)
###################################################
### code chunk number 41: discreteTraitPlot
###################################################
par(mar=c(0,0,0,0), tcl=-0.2, mgp=c(1,0.5,0), cex.axis=0.8)
plot(discreteTree$phy, show.tip=FALSE)
lastPP <- get("last_plot.phylo", envir = .PlotPhyloEnv)
traitsByNode <- with(discreteTree, rbind( cbind(node=phy$tip.label, data[, c('flight','trophic')]), node.data[, c('node','flight','trophic')]))
traitsByNode <- traitsByNode[match(1:199, traitsByNode$node), ]
with(lastPP, points(xx + 0.06, yy, pch=21, col=unclass(traitsByNode$flight), xpd=NA, cex=0.6))
with(lastPP, points(xx + 0.12, yy, pch=22, col=unclass(traitsByNode$trophic), xpd=NA, cex=0.6))
###################################################
### code chunk number 42: setseed
###################################################
set.seed(95132)
###################################################
### code chunk number 43: patencyModel
###################################################
bLatency <- expression((0.2 *lin.age)/(0.1 + lin.age))
dSenesce <- expression(lin.age * 0.02)
halt <- expression(nExtantTip >= 60)
latencyTree <- growTree(b=bLatency, d=dSenesce, halt=halt, grain=0.01)
traitMean <- c(logBodyMass=5.48)
traitVar <- c(logBodyMass=10)
bLatTrait <- expression(((0.2 + ((5.48 - logBodyMass)/25))*lin.age)/(0.1 + lin.age))
latTraitTree <- growTree(b=bLatTrait, d=dSenesce, halt=halt, ct.start=traitMean, ct.var=traitVar, grain=0.01)
###################################################
### code chunk number 44: patencyPlot
###################################################
par(mfrow=c(2,2), mar=c(2.5,2.5,1,1), tcl=-0.2, mgp=c(1.5,0.5,0), cex.axis=0.8)
curve(0.02*x, xlim=c(0,20), ylab='Rate', xlab="Lineage age")
curve(((0.2 + ((5.48 - 5.48)/25))*x)/(0.1 + x), add=TRUE, col='red')
curve(((0.2 + ((5.48 - 3.48)/25))*x)/(0.1 + x), add=TRUE, col='red', lty=2)
curve(((0.2 + ((5.48 - 7.48)/25))*x)/(0.1 + x), add=TRUE, col='red', lty=2)
plot(latencyTree$phy, no.margin=TRUE, cex=0.8)
plot(latTraitTree$phy, no.margin=TRUE, cex=0.8, show.tip=FALSE)
# rightEdge <- par('usr')[2] - 0.75
# tips <- seq_along(latTraitTree$tip.label)
# bm <- with(latTraitTree, ct.data$logBodyMass[ match(tips, ct.data$node)])
#
# rect(rightEdge - 5.48/20, 0 , rightEdge + 5.48/20, max(tips)+1, col='grey80', border=NA)
#
# arrows(rightEdge-bm/20, tips, rightEdge+bm/20, tips, code=0, col='red', xpd=NA, lwd=2, lend=2)
###################################################
### code chunk number 45: inheritanceExample1
###################################################
traitMean <- c(logBodyMass=5.48)
traitVar <- c(logBodyMass=10)
inherit <- list(logBodyMass=expression(logBodyMass * c(0.8, 1.2)))
inheritTree <- growTree(b=1, halt=40, ct.start=traitMean, ct.var=traitVar, inheritance=inherit, grain=Inf, extend.proportion=1)
###################################################
### code chunk number 46: inheritanceExamples2
###################################################
rNames <- c("AB", "A", "B")
regions <- list(region = matrix(c(0, 0.05, 0.05, 0.1, 0,0,0.1,0,0), ncol=3,
dimnames=list(rNames,rNames)))
extinct <- expression(ifelse(region == "AB", 0.0001, 0.01))
spec <- list(regA_spec = expression(ifelse(region == "AB" | region == "A", 1, 0)),
regB_spec = expression(ifelse(region == "AB" | region == "B", 0.5, 0)))
inherit <- list(region = expression(if(winnerName=="regB_spec" && region[1] == "AB") c("B","A") else region),
region = expression(if(winnerName=="regA_spec" && region[1] == "AB") c("A","B") else region))
biogeogTree <- growTree(b=spec, d=extinct, halt=80, inherit=inherit, dt.rates=regions, inf.rates="quiet", grain=Inf)
###################################################
### code chunk number 47: epochExample
###################################################
epochTree <- growTree(halt=100, output.lineages=TRUE, grain=Inf)
epochTree2 <- growTree(d=5, halt=expression(nExtantTip==20), linObj=epochTree, output.lineages=TRUE, grain=Inf)
epochTree3 <- growTree(linObj=epochTree2, halt=100, grain=Inf)
###################################################
### code chunk number 48: inheritancePlots
###################################################
par(mfrow=c(1,3), mar=c(1,1,1,1))
depth <- VCV.array(inheritTree$phy)[1,1]
plot(inheritTree$phy, no.margin=TRUE, cex=0.8, show.tip=FALSE, root.edge=TRUE, x.lim=c(0,depth*1.1))
rightEdge <- depth*1.05
tips <- seq_along(inheritTree$phy$tip.label)
bm <- inheritTree$data$logBodyMass
sc <- max(bm) / (depth*0.04)
rect(rightEdge - 5.48/sc, 0 , rightEdge + 5.48/sc, max(tips)+1, col='grey80', border=NA)
arrows(rightEdge-bm/sc, tips, rightEdge+bm/sc, tips, code=0, col='red', xpd=NA, lwd=2, lend=2)
plot(biogeogTree$phy, edge.col= unclass(biogeogTree$data$region), show.tip.label=FALSE, root.edge=TRUE)
plot(epochTree3$phy, show.tip.label=FALSE)
###################################################
### code chunk number 49: cladeMatrixExample
###################################################
data(perissodactyla)
perisso <- comparative.data(perissodactyla.tree, perissodactyla.data, Binomial)
perissoCM <- clade.matrix(perisso$phy)
str(perissoCM)
perissoCM$clade.matrix
###################################################
### code chunk number 50: cladeMembersExample
###################################################
data(perissodactyla)
perisso <- comparative.data(perissodactyla.tree, perissodactyla.data, Binomial)
clade.members(15, perisso$phy)
clade.members(15, perisso$phy, tip.labels=TRUE)
clade.members(15, perisso$phy, tip.labels=TRUE, include.nodes=TRUE)
str(clade.members.list(perisso$phy))
str(clade.members.list(perisso$phy, tip.labels=TRUE))
###################################################
### code chunk number 51: vcvArrayExample
###################################################
data(perissodactyla)
perisso <- comparative.data(perissodactyla.tree, perissodactyla.data, Binomial)
str(VCV.array(perisso$phy))
str(VCV.array(perisso$phy, dim=3))
|
# Find all wards within Zambia --------------------------------------------
# Shape files of wards in Zambia are a bit messy, so constructing a lookup table of province, district,
# constituencies, wards, and polling places
# Laura Hughes, lhughes@usaid.gov, USAID | GeoCenter
# 7 July 2017
# procedure ---------------------------------------------------------------
# 1. Previously: in ZMB_assembly2016_clean.R, scraped all the constituencies to back out their distr/prov
# 2. Using these constituency names, pull up the constituency-level data
# 3. Within this website, the "Polling Stations in <Constituency>" drop-down menu contains all the ward names. Scrape it!
# 4. Clean and pull out just the pertinent data
# setup -------------------------------------------------------------------
library(tidyverse)
library(stringr)
library(rvest)
base_dir = '~/Documents/GitHub/Zambia/'
# previous lookup table: prov, dist, constit ------------------------------
# constit = read_csv( paste0(base_dir, 'processeddata/ZMB_2016_adminnames.csv')) %>% select(-X1)
crswlk = read_excel('ZMB_admin_crosswalk.xlsx', sheet = 2)
constit = crswlk %>%
filter(website2015 != 'NA') %>%
select(-constituency) %>% rename(constituency = website2015)
# Polling-level website ---------------------------------------------------
# URL for getting the polling station level data:
# example: https://www.elections.org.zm/results/2016_presidential_election/poll/ambidzi,chadiza
# end is /poll/ward,district
# base_poll_url = "https://www.elections.org.zm/results/2016_presidential_election/poll/"
base_poll_url = "/results/2015_presidential_election/poll/"
# Pull tables of wards per constituency -----------------------------------
base_url = 'https://www.elections.org.zm/results/2015_presidential_election/constituency/'
constit = constit %>%
mutate(url = paste0(base_url, str_to_lower(constituency)),
url = str_replace_all(url, ' ', '_'),
url = str_replace_all(url,"'", '%2527'))
wards = NULL
# Note: would be faster to create function and lapply it across the list.
for (i in 1:nrow(constit)) {
print(paste0(i, ': ', round(i/nrow(constit), 2) * 100, '%'))
url = constit$url[i]
cons = constit$constituency[i]
dist = constit$district[i]
prov = constit$province[i]
html = read_html(url)
# HTML text from the form i
# Use html_form to pull out the form data, which will get both the
# 1) URL like "/results/2016_presidential_election/poll/lukundushi,mansa"
# 2) ward name / polling place like "MANO/Mano Primary School"
messy_wards = html %>%
html_node('#districts-select')
if(!is.na(messy_wards)){
warning(paste0(cons, ' has no wards'))
messy_wards = messy_wards %>%
html_form()
# pull out just the options from the form
messy_wards = data.frame(messy_wards$fields$`NULL`$options)
# clean up the wards
ward = messy_wards %>%
rename(ward_url = messy_wards.fields..NULL..options) %>%
mutate(ward_polling = row.names(messy_wards),
constituency = cons,
province = prov,
district = dist,
dist_fromurl = str_replace_all(ward_url, base_poll_url, '')) %>%
# split ward / polling location into two columns
separate(ward_polling, sep = "\\/", into = c('ward', 'polling_station'), remove = FALSE) %>%
# split URL into ward and district
separate(dist_fromurl, sep = '\\,', into = c('ward_fromurl', 'dist_fromurl')) %>%
mutate(ward = str_to_title(ward),
ward_fromurl = str_to_title(ward_fromurl),
dist_fromurl = str_to_title(dist_fromurl))
wards = bind_rows(wards, ward)
}
}
wards = wards %>% filter(ward != "")
# Merge with previous crosswalk -------------------------------------------
# crswlk = read_excel('ZMB_admin_crosswalk.xlsx', sheet = 2)
unique_wards = wards %>% select(province, district, dist_fromurl, constituency, ward) %>% distinct()
crswlk = full_join(unique_wards, crswlk, by = c("constituency", "province", "district"))
write_csv(crswlk, 'ZMB_admin_wards_crosswalk.csv')
|
/ZMB_find_wards.R
|
permissive
|
tessam30/Zambia
|
R
| false | false | 4,144 |
r
|
# Find all wards within Zambia --------------------------------------------
# Shape files of wards in Zambia are a bit messy, so constructing a lookup table of province, district,
# constituencies, wards, and polling places
# Laura Hughes, lhughes@usaid.gov, USAID | GeoCenter
# 7 July 2017
# procedure ---------------------------------------------------------------
# 1. Previously: in ZMB_assembly2016_clean.R, scraped all the constituencies to back out their distr/prov
# 2. Using these constituency names, pull up the constituency-level data
# 3. Within this website, the "Polling Stations in <Constituency>" drop-down menu contains all the ward names. Scrape it!
# 4. Clean and pull out just the pertinent data
# setup -------------------------------------------------------------------
library(tidyverse)
library(stringr)
library(rvest)
base_dir = '~/Documents/GitHub/Zambia/'
# previous lookup table: prov, dist, constit ------------------------------
# constit = read_csv( paste0(base_dir, 'processeddata/ZMB_2016_adminnames.csv')) %>% select(-X1)
crswlk = read_excel('ZMB_admin_crosswalk.xlsx', sheet = 2)
constit = crswlk %>%
filter(website2015 != 'NA') %>%
select(-constituency) %>% rename(constituency = website2015)
# Polling-level website ---------------------------------------------------
# URL for getting the polling station level data:
# example: https://www.elections.org.zm/results/2016_presidential_election/poll/ambidzi,chadiza
# end is /poll/ward,district
# base_poll_url = "https://www.elections.org.zm/results/2016_presidential_election/poll/"
base_poll_url = "/results/2015_presidential_election/poll/"
# Pull tables of wards per constituency -----------------------------------
base_url = 'https://www.elections.org.zm/results/2015_presidential_election/constituency/'
constit = constit %>%
mutate(url = paste0(base_url, str_to_lower(constituency)),
url = str_replace_all(url, ' ', '_'),
url = str_replace_all(url,"'", '%2527'))
wards = NULL
# Note: would be faster to create function and lapply it across the list.
for (i in 1:nrow(constit)) {
print(paste0(i, ': ', round(i/nrow(constit), 2) * 100, '%'))
url = constit$url[i]
cons = constit$constituency[i]
dist = constit$district[i]
prov = constit$province[i]
html = read_html(url)
# HTML text from the form i
# Use html_form to pull out the form data, which will get both the
# 1) URL like "/results/2016_presidential_election/poll/lukundushi,mansa"
# 2) ward name / polling place like "MANO/Mano Primary School"
messy_wards = html %>%
html_node('#districts-select')
if(!is.na(messy_wards)){
warning(paste0(cons, ' has no wards'))
messy_wards = messy_wards %>%
html_form()
# pull out just the options from the form
messy_wards = data.frame(messy_wards$fields$`NULL`$options)
# clean up the wards
ward = messy_wards %>%
rename(ward_url = messy_wards.fields..NULL..options) %>%
mutate(ward_polling = row.names(messy_wards),
constituency = cons,
province = prov,
district = dist,
dist_fromurl = str_replace_all(ward_url, base_poll_url, '')) %>%
# split ward / polling location into two columns
separate(ward_polling, sep = "\\/", into = c('ward', 'polling_station'), remove = FALSE) %>%
# split URL into ward and district
separate(dist_fromurl, sep = '\\,', into = c('ward_fromurl', 'dist_fromurl')) %>%
mutate(ward = str_to_title(ward),
ward_fromurl = str_to_title(ward_fromurl),
dist_fromurl = str_to_title(dist_fromurl))
wards = bind_rows(wards, ward)
}
}
wards = wards %>% filter(ward != "")
# Merge with previous crosswalk -------------------------------------------
# crswlk = read_excel('ZMB_admin_crosswalk.xlsx', sheet = 2)
unique_wards = wards %>% select(province, district, dist_fromurl, constituency, ward) %>% distinct()
crswlk = full_join(unique_wards, crswlk, by = c("constituency", "province", "district"))
write_csv(crswlk, 'ZMB_admin_wards_crosswalk.csv')
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/getPost.R
\name{getPost}
\alias{getPost}
\title{Extract information about a public Facebook post}
\usage{
getPost(post, token, n = 500, comments = TRUE, likes = TRUE,
n.likes = n, n.comments = n)
}
\arguments{
\item{post}{A post ID}
\item{token}{Either a temporary access token created at
\url{https://developers.facebook.com/tools/explorer} or the OAuth token
created with \code{fbOAuth}.}
\item{n}{numeric, maximum number of comments and likes to return.}
\item{comments}{logical, default is \code{TRUE}, which will return data frame
with comments to the post.}
\item{likes}{logical, default is \code{TRUE}, which will return data frame
with likes for the post.}
\item{n.likes}{numeric, maximum number of likes to return. Default is \code{n}.}
\item{n.comments}{numeric, maximum number of likes to return. Default is
\code{n}.}
}
\description{
\code{getPost} retrieves information about a public Facebook post, including
list of comments and likes.
}
\details{
\code{getPost} returns a list with three components: \code{post},
\code{likes}, and \code{comments}. First, \code{post} contains information
about the post: author, creation date, id, counts of likes, comments, and
shares, etc. Second, \code{likes} is a data frame that contains names and
Facebook IDs of all the users that liked the post. Finally, \code{comments}
is a data frame with information about the comments to the post (author,
message, creation time, id).
}
\examples{
\dontrun{
## See examples for fbOAuth to know how token was created.
## Getting information about Facebook's Facebook Page
load("fb_oauth")
fb_page <- getPage(page="facebook", token=fb_oauth)
## Getting information and likes/comments about most recent post
post <- getPost(post=fb_page$id[1], n=2000, token=fb_oauth)
}
}
\author{
Pablo Barbera \email{pablo.barbera@nyu.edu}
}
\seealso{
\code{\link{getUsers}}, \code{\link{getPage}}, \code{\link{fbOAuth}}
}
|
/Rfacebook/man/getPost.Rd
|
no_license
|
ashgreat/Rfacebook
|
R
| false | true | 1,993 |
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/getPost.R
\name{getPost}
\alias{getPost}
\title{Extract information about a public Facebook post}
\usage{
getPost(post, token, n = 500, comments = TRUE, likes = TRUE,
n.likes = n, n.comments = n)
}
\arguments{
\item{post}{A post ID}
\item{token}{Either a temporary access token created at
\url{https://developers.facebook.com/tools/explorer} or the OAuth token
created with \code{fbOAuth}.}
\item{n}{numeric, maximum number of comments and likes to return.}
\item{comments}{logical, default is \code{TRUE}, which will return data frame
with comments to the post.}
\item{likes}{logical, default is \code{TRUE}, which will return data frame
with likes for the post.}
\item{n.likes}{numeric, maximum number of likes to return. Default is \code{n}.}
\item{n.comments}{numeric, maximum number of likes to return. Default is
\code{n}.}
}
\description{
\code{getPost} retrieves information about a public Facebook post, including
list of comments and likes.
}
\details{
\code{getPost} returns a list with three components: \code{post},
\code{likes}, and \code{comments}. First, \code{post} contains information
about the post: author, creation date, id, counts of likes, comments, and
shares, etc. Second, \code{likes} is a data frame that contains names and
Facebook IDs of all the users that liked the post. Finally, \code{comments}
is a data frame with information about the comments to the post (author,
message, creation time, id).
}
\examples{
\dontrun{
## See examples for fbOAuth to know how token was created.
## Getting information about Facebook's Facebook Page
load("fb_oauth")
fb_page <- getPage(page="facebook", token=fb_oauth)
## Getting information and likes/comments about most recent post
post <- getPost(post=fb_page$id[1], n=2000, token=fb_oauth)
}
}
\author{
Pablo Barbera \email{pablo.barbera@nyu.edu}
}
\seealso{
\code{\link{getUsers}}, \code{\link{getPage}}, \code{\link{fbOAuth}}
}
|
### rna_seq_featureCounter.R
### Laura M. Carroll
### April 20, 2019
### input: bam files of mapped reads, saf file output by gff2saf.py script
# uncomment to install Rsubread if necessary
if (!requireNamespace("BiocManager", quietly = TRUE))
install.packages("BiocManager")
BiocManager::install("Rsubread", version = "3.8")
# read.saf function to read saf file from gff2saf.py
read.saf <- function(saf){
saf.og <- read.delim(file = saf, header = T, sep = "\t")
saf <- saf.og[,1:5]
# returns saf file for featureCounts, as well as the original saf file (saf_full) from gff2saf.py
# see featureCounts for description of saf file
# featureCounts: https://www.rdocumentation.org/packages/Rsubread/versions/1.22.2/topics/featureCounts
return(list(saf = saf, saf_full = saf.og))
}
# load Rsubread
library(Rsubread)
# read Cerro saf file
saf.cerro <- read.saf(saf = "~/Documents/RNA_seq_Salmonella/cerro/FSL-R8-2349_S17_L001_contigs_long.saf")
# run featureCounts for Cerro, supplying sorted bam files and Cerro saf file
# keep strandSpecific to 2 (reverse-stranded RNA-Seq)
# keep isPairedEnd to F (this is single-end data)
# change other options if desired; see featureCounts for details
fc.cerro <- featureCounts(files = c("~/Documents/RNA_seq_Salmonella/cerro/cerro_AC4.sorted.bam",
"~/Documents/RNA_seq_Salmonella/cerro/cerro_AC5.sorted.bam",
"~/Documents/RNA_seq_Salmonella/cerro/cerro_AC6.sorted.bam"),
annot.ext = saf.cerro$saf, strandSpecific = 2, isPairedEnd = F)
# stats to see how many reads mapped to features, didn't map, etc.
fc.cerro$stat
# see the top part of the annotation file just because
head(fc.cerro$annotation)
write.table(x = data.frame(fc.cerro$annotation[,c("GeneID", "Length")], fc.cerro$counts, stringsAsFactors = FALSE), file = "cerro_featurecounts.txt", append = F, quote = F, sep = "\t", row.names = F)
# read Javiana saf file
saf.javiana <- read.saf(saf = "~/Documents/RNA_seq_Salmonella/javiana/S5_0395_long.saf")
# run featureCounts for Javiana, supplying sorted bam files and Javiana saf file
# keep strandSpecific to 2 (reverse-stranded RNA-Seq)
# keep isPairedEnd to F (this is single-end data)
# change other options if desired; see featureCounts for details
fc.javiana <- featureCounts(files = c("~/Documents/RNA_seq_Salmonella/javiana/javiana_AC1.sorted.bam",
"~/Documents/RNA_seq_Salmonella/javiana/javiana_AC2.sorted.bam",
"~/Documents/RNA_seq_Salmonella/javiana/javiana_AC3.sorted.bam"),
annot.ext = saf.javiana$saf, strandSpecific = 2, isPairedEnd = F)
# stats to see how many reads mapped to features, didn't map, etc.
fc.javiana$stat
# see the top part of the annotation file just because
head(fc.javiana$annotation)
write.table(x = data.frame(fc.javiana$annotation[,c("GeneID", "Length")], fc.javiana$counts, stringsAsFactors = FALSE), file = "javiana_featurecounts.txt", append = F, quote = F, sep = "\t", row.names = F)
# read Typhimurium saf file
saf.typhimurium <- read.saf(saf = "~/Documents/RNA_seq_Salmonella/typhimurium/14028s_NCBI.saf")
# run featureCounts for Typhimurium, supplying sorted bam files and Typhimurium saf file
# keep strandSpecific to 2 (reverse-stranded RNA-Seq)
# keep isPairedEnd to F (this is single-end data)
# change other options if desired; see featureCounts for details
fc.typhimurium <- featureCounts(files = c("~/Documents/RNA_seq_Salmonella/typhimurium/typhimurium_AC7.sorted.bam",
"~/Documents/RNA_seq_Salmonella/typhimurium/typhimurium_AC8.sorted.bam",
"~/Documents/RNA_seq_Salmonella/typhimurium/typhimurium_AC9.sorted.bam"),
annot.ext = saf.typhimurium$saf, strandSpecific = 2, isPairedEnd = F)
# stats to see how many reads mapped to features, didn't map, etc.
fc.typhimurium$stat
# see the top part of the annotation file just because
head(fc.typhimurium$annotation)
write.table(x = data.frame(fc.typhimurium$annotation[,c("GeneID", "Length")], fc.typhimurium$counts, stringsAsFactors = FALSE), file = "typhimurium_featurecounts.txt", append = F, quote = F, sep = "\t", row.names = F)
# merge Cerro and Javiana counts, including pan genome
# genes present in one reference strain but not the other will be denoted by NA
cj <- merge(fc.cerro$counts, fc.javiana$counts, by="row.names", all.x=T, all.y=T)
rownames(cj) <- cj$Row.names
cj <- cj[,2:ncol(cj)]
cj[is.na(cj)] <- 0
table(is.na(as.vector(cj)))
#merge Cerro and Typhimurium counts, including pan genome
ct <- merge(fc.cerro$counts, fc.typhimurium$counts, by="row.names", all.x=T, all.y=T)
rownames(ct) <- cj$Row.names
ct <- ct[,2:ncol(ct)]
ct[is.na(ct)] <- 0
table(is.na(as.vector(ct)))
# merge Cerro and Javiana annotation, including pan genome
# genes present in one reference strain but not the other will be denoted by NA
cj <- merge(fc.cerro$annotation, fc.javiana$annotation, by="row.names", all.x=T, all.y=T)
rownames(cj) <- cj$Row.names
cj <- cj[,2:ncol(cj)]
cj[is.na(cj)] <- 0
table(is.na(as.vector(cj)))
#merge Cerro and Typhimurium annotation, including pan genome
ct <- merge(fc.cerro$annotation, fc.typhimurium$annotation, by="row.names", all.x=T, all.y=T)
rownames(ct) <- cj$Row.names
ct <- ct[,2:ncol(ct)]
ct[is.na(ct)] <- 0
table(is.na(as.vector(ct)))
# merge CerroJaviana and Typhimurium counts, including pan genome
# genes absent from a reference strain will be denoted by NA
cjt <- merge(cj, fc.typhimurium$counts, by="row.names", all.x=T, all.y=T)
# sanity check; how many NAs do we have?
table(is.na(as.vector(cjt)))
# replace NA with 0 counts
cjt[is.na(cjt)] <- 0
# sanity check; are our NAs gone?
table(is.na(as.vector(cjt)))
# change the column names of the count matrix to make it more readable
colnames(cjt) <- c("Feature", "Cerro-rep1", "Cerro-rep2", "Cerro-rep3",
"Javiana-rep1", "Javiana-rep2", "Javiana-rep3",
"Typhimurium-rep1", "Typhimurium-rep2", "Typhimurium-rep3")
# write this zero-inflated pan-genome count matrix to a tab-delimited file
# file is named CerroJavianaTyphimurium_featureCounts_panGenome_as_zeros.txt
write.table(x = cjt, file = "CerroJavianaTyphimurium_featureCounts_panGenome_as_zeros.txt",
append = F, quote = F, sep = "\t", row.names = F, col.names = T)
# merge CerroJaviana and Typhimurium annotations, including pan genome
# genes absent from a reference strain will be denoted by NA
cjt <- merge(cj, fc.typhimurium$annotation, by="row.names", all.x=T, all.y=T)
# sanity check; how many NAs do we have?
table(is.na(as.vector(cjt)))
# replace NA with 0 counts
cjt[is.na(cjt)] <- 0
# sanity check; are our NAs gone?
table(is.na(as.vector(cjt)))
# change the column names of the count matrix to make it more readable
colnames(cjt) <- c("Feature", "Cerro-rep1", "Cerro-rep2", "Cerro-rep3",
"Javiana-rep1", "Javiana-rep2", "Javiana-rep3",
"Typhimurium-rep1", "Typhimurium-rep2", "Typhimurium-rep3")
# write this zero-inflated pan-genome count matrix to a tab-delimited file
# file is named CerroJavianaTyphimurium_featureCounts_panGenome_as_zeros.txt
write.table(x = cjt, file = "CerroJavianaTyphimurium_featureCounts_panGenome_as_zeros.txt",
append = F, quote = F, sep = "\t", row.names = F, col.names = T)
# merge Cerro and Javiana counts, excluding pan genome
# only genes present in both reference strains will be maintained
cj.core <- merge(fc.cerro$counts, fc.javiana$counts, by="row.names", all.x=F, all.y=F)
rownames(cj.core) <- cj.core$Row.names
table(is.na(as.vector(cj.core)))
colnames(cj.core) <- c("Feature", "Cerro-rep1", "Cerro-rep2", "Cerro-rep3", "Javiana-rep1", "Javiana-rep2", "Javiana-rep3")
write.table(x = cj.core, file="cerrojaviana_featurecounts_core.txt", append = F, quote = F, sep = "\t", row.names = F, col.names = T)
# merge Cerro and Javiana annotation, excluding pan genome
# only genes present in both reference strains will be maintained
cj.core <- merge(fc.cerro$annotation, fc.javiana$annotation, by="row.names", all.x=F, all.y=F)
rownames(cj.core) <- cj.core$Row.names
table(is.na(as.vector(cj.core)))
colnames(cj.core) <- c("Feature", "Cerro-rep1", "Cerro-rep2", "Cerro-rep3", "Javiana-rep1", "Javiana-rep2", "Javiana-rep3")
write.table(x = cj.core, file="cerrojaviana_annotation_core.txt", append = F, quote = F, sep = "\t", row.names = F, col.names = T)
# merge Cerro and Typhimurium counts, excluding pan genome
# only genes present in both reference strains will be maintained
ct.core <- merge(fc.cerro$counts, fc.typhimurium$counts, by="row.names", all.x=F, all.y=F)
rownames(ct.core) <- ct.core$Row.names
table(is.na(as.vector(ct.core)))
colnames(ct.core) <- c("Feature", "Cerro-rep1", "Cerro-rep2", "Cerro-rep3", "Typhimurium-rep1", "Typhimurium-rep2", "Typhimurium-rep3")
write.table(x = ct.core, file="cerrotyphimurium_featurecounts_core.txt", append = F, quote = F, sep = "\t", row.names = F, col.names = T)
# merge Javiana and Typhimurium counts, excluding pan genome
# only genes present in both reference strains will be maintained
jt.core <- merge(fc.javiana$counts, fc.typhimurium$counts, by="row.names", all.x=F, all.y=F)
rownames(jt.core) <- jt.core$Row.names
table(is.na(as.vector(jt.core)))
colnames(jt.core) <- c("Feature", "Javiana-rep1", "Javiana-rep2", "Javiana-rep3", "Typhimurium-rep1", "Typhimurium-rep2", "Typhimurium-rep3")
write.table(x = jt.core, file="javianatyphimurium_featurecounts_core.txt", append = F, quote = F, sep = "\t", row.names = F, col.names = T)
# merge CerroJaviana and Typhimurium counts, excluding pan genome
# only genes present in all three reference strains will be maintained
cjt.core <- merge(cj.core, fc.typhimurium$counts, by="row.names", all.x=F, all.y=F)
# sanity check; there should be no NAs (this is just the core genome of the 3 strains)
table(is.na(as.vector(cjt.core)))
# change the column names of the count matrix to make it more readable
colnames(cjt.core) <- c("Feature", "Cerro-rep1", "Cerro-rep2", "Cerro-rep3",
"Javiana-rep1", "Javiana-rep2", "Javiana-rep3",
"Typhimurium-rep1", "Typhimurium-rep2", "Typhimurium-rep3")
# write this core-genome count matrix to a tab-delimited file
# file is named CerroJavianaTyphimurium_featureCounts_drop_panGenome.txt
write.table(x = cjt.core, file = "CerroJavianaTyphimurium_featureCounts_drop_panGenome.txt",
append = F, quote = F, sep = "\t", row.names = F, col.names = T)
# merge CerroJaviana and Typhimurium annotation, excluding pan genome
# only genes present in all three reference strains will be maintained
cjt.core <- merge(cj.core, fc.typhimurium$annotation, by="row.names", all.x=F, all.y=F)
# sanity check; there should be no NAs (this is just the core genome of the 3 strains)
table(is.na(as.vector(cjt.core)))
# change the column names of the count matrix to make it more readable
colnames(cjt.core) <- c("Feature", "Cerro-rep1", "Cerro-rep2", "Cerro-rep3",
"Javiana-rep1", "Javiana-rep2", "Javiana-rep3",
"Typhimurium-rep1", "Typhimurium-rep2", "Typhimurium-rep3")
# write this core-genome count matrix to a tab-delimited file
# file is named CerroJavianaTyphimurium_featureCounts_drop_panGenome.txt
write.table(x = cjt.core, file = "cjt_annotation.txt",
append = F, quote = F, sep = "\t", row.names = F, col.names = T)
|
/rna_seq_featureCounter.R
|
no_license
|
alexarcohn/salmonella_rnaseq
|
R
| false | false | 11,521 |
r
|
### rna_seq_featureCounter.R
### Laura M. Carroll
### April 20, 2019
### input: bam files of mapped reads, saf file output by gff2saf.py script
# uncomment to install Rsubread if necessary
if (!requireNamespace("BiocManager", quietly = TRUE))
install.packages("BiocManager")
BiocManager::install("Rsubread", version = "3.8")
# read.saf function to read saf file from gff2saf.py
read.saf <- function(saf){
saf.og <- read.delim(file = saf, header = T, sep = "\t")
saf <- saf.og[,1:5]
# returns saf file for featureCounts, as well as the original saf file (saf_full) from gff2saf.py
# see featureCounts for description of saf file
# featureCounts: https://www.rdocumentation.org/packages/Rsubread/versions/1.22.2/topics/featureCounts
return(list(saf = saf, saf_full = saf.og))
}
# load Rsubread
library(Rsubread)
# read Cerro saf file
saf.cerro <- read.saf(saf = "~/Documents/RNA_seq_Salmonella/cerro/FSL-R8-2349_S17_L001_contigs_long.saf")
# run featureCounts for Cerro, supplying sorted bam files and Cerro saf file
# keep strandSpecific to 2 (reverse-stranded RNA-Seq)
# keep isPairedEnd to F (this is single-end data)
# change other options if desired; see featureCounts for details
fc.cerro <- featureCounts(files = c("~/Documents/RNA_seq_Salmonella/cerro/cerro_AC4.sorted.bam",
"~/Documents/RNA_seq_Salmonella/cerro/cerro_AC5.sorted.bam",
"~/Documents/RNA_seq_Salmonella/cerro/cerro_AC6.sorted.bam"),
annot.ext = saf.cerro$saf, strandSpecific = 2, isPairedEnd = F)
# stats to see how many reads mapped to features, didn't map, etc.
fc.cerro$stat
# see the top part of the annotation file just because
head(fc.cerro$annotation)
write.table(x = data.frame(fc.cerro$annotation[,c("GeneID", "Length")], fc.cerro$counts, stringsAsFactors = FALSE), file = "cerro_featurecounts.txt", append = F, quote = F, sep = "\t", row.names = F)
# read Javiana saf file
saf.javiana <- read.saf(saf = "~/Documents/RNA_seq_Salmonella/javiana/S5_0395_long.saf")
# run featureCounts for Javiana, supplying sorted bam files and Javiana saf file
# keep strandSpecific to 2 (reverse-stranded RNA-Seq)
# keep isPairedEnd to F (this is single-end data)
# change other options if desired; see featureCounts for details
fc.javiana <- featureCounts(files = c("~/Documents/RNA_seq_Salmonella/javiana/javiana_AC1.sorted.bam",
"~/Documents/RNA_seq_Salmonella/javiana/javiana_AC2.sorted.bam",
"~/Documents/RNA_seq_Salmonella/javiana/javiana_AC3.sorted.bam"),
annot.ext = saf.javiana$saf, strandSpecific = 2, isPairedEnd = F)
# stats to see how many reads mapped to features, didn't map, etc.
fc.javiana$stat
# see the top part of the annotation file just because
head(fc.javiana$annotation)
write.table(x = data.frame(fc.javiana$annotation[,c("GeneID", "Length")], fc.javiana$counts, stringsAsFactors = FALSE), file = "javiana_featurecounts.txt", append = F, quote = F, sep = "\t", row.names = F)
# read Typhimurium saf file
saf.typhimurium <- read.saf(saf = "~/Documents/RNA_seq_Salmonella/typhimurium/14028s_NCBI.saf")
# run featureCounts for Typhimurium, supplying sorted bam files and Typhimurium saf file
# keep strandSpecific to 2 (reverse-stranded RNA-Seq)
# keep isPairedEnd to F (this is single-end data)
# change other options if desired; see featureCounts for details
fc.typhimurium <- featureCounts(files = c("~/Documents/RNA_seq_Salmonella/typhimurium/typhimurium_AC7.sorted.bam",
"~/Documents/RNA_seq_Salmonella/typhimurium/typhimurium_AC8.sorted.bam",
"~/Documents/RNA_seq_Salmonella/typhimurium/typhimurium_AC9.sorted.bam"),
annot.ext = saf.typhimurium$saf, strandSpecific = 2, isPairedEnd = F)
# stats to see how many reads mapped to features, didn't map, etc.
fc.typhimurium$stat
# see the top part of the annotation file just because
head(fc.typhimurium$annotation)
write.table(x = data.frame(fc.typhimurium$annotation[,c("GeneID", "Length")], fc.typhimurium$counts, stringsAsFactors = FALSE), file = "typhimurium_featurecounts.txt", append = F, quote = F, sep = "\t", row.names = F)
# merge Cerro and Javiana counts, including pan genome
# genes present in one reference strain but not the other will be denoted by NA
cj <- merge(fc.cerro$counts, fc.javiana$counts, by="row.names", all.x=T, all.y=T)
rownames(cj) <- cj$Row.names
cj <- cj[,2:ncol(cj)]
cj[is.na(cj)] <- 0
table(is.na(as.vector(cj)))
#merge Cerro and Typhimurium counts, including pan genome
ct <- merge(fc.cerro$counts, fc.typhimurium$counts, by="row.names", all.x=T, all.y=T)
rownames(ct) <- cj$Row.names
ct <- ct[,2:ncol(ct)]
ct[is.na(ct)] <- 0
table(is.na(as.vector(ct)))
# merge Cerro and Javiana annotation, including pan genome
# genes present in one reference strain but not the other will be denoted by NA
cj <- merge(fc.cerro$annotation, fc.javiana$annotation, by="row.names", all.x=T, all.y=T)
rownames(cj) <- cj$Row.names
cj <- cj[,2:ncol(cj)]
cj[is.na(cj)] <- 0
table(is.na(as.vector(cj)))
#merge Cerro and Typhimurium annotation, including pan genome
ct <- merge(fc.cerro$annotation, fc.typhimurium$annotation, by="row.names", all.x=T, all.y=T)
rownames(ct) <- cj$Row.names
ct <- ct[,2:ncol(ct)]
ct[is.na(ct)] <- 0
table(is.na(as.vector(ct)))
# merge CerroJaviana and Typhimurium counts, including pan genome
# genes absent from a reference strain will be denoted by NA
cjt <- merge(cj, fc.typhimurium$counts, by="row.names", all.x=T, all.y=T)
# sanity check; how many NAs do we have?
table(is.na(as.vector(cjt)))
# replace NA with 0 counts
cjt[is.na(cjt)] <- 0
# sanity check; are our NAs gone?
table(is.na(as.vector(cjt)))
# change the column names of the count matrix to make it more readable
colnames(cjt) <- c("Feature", "Cerro-rep1", "Cerro-rep2", "Cerro-rep3",
"Javiana-rep1", "Javiana-rep2", "Javiana-rep3",
"Typhimurium-rep1", "Typhimurium-rep2", "Typhimurium-rep3")
# write this zero-inflated pan-genome count matrix to a tab-delimited file
# file is named CerroJavianaTyphimurium_featureCounts_panGenome_as_zeros.txt
write.table(x = cjt, file = "CerroJavianaTyphimurium_featureCounts_panGenome_as_zeros.txt",
append = F, quote = F, sep = "\t", row.names = F, col.names = T)
# merge CerroJaviana and Typhimurium annotations, including pan genome
# genes absent from a reference strain will be denoted by NA
cjt <- merge(cj, fc.typhimurium$annotation, by="row.names", all.x=T, all.y=T)
# sanity check; how many NAs do we have?
table(is.na(as.vector(cjt)))
# replace NA with 0 counts
cjt[is.na(cjt)] <- 0
# sanity check; are our NAs gone?
table(is.na(as.vector(cjt)))
# change the column names of the count matrix to make it more readable
colnames(cjt) <- c("Feature", "Cerro-rep1", "Cerro-rep2", "Cerro-rep3",
"Javiana-rep1", "Javiana-rep2", "Javiana-rep3",
"Typhimurium-rep1", "Typhimurium-rep2", "Typhimurium-rep3")
# write this zero-inflated pan-genome count matrix to a tab-delimited file
# file is named CerroJavianaTyphimurium_featureCounts_panGenome_as_zeros.txt
write.table(x = cjt, file = "CerroJavianaTyphimurium_featureCounts_panGenome_as_zeros.txt",
append = F, quote = F, sep = "\t", row.names = F, col.names = T)
# merge Cerro and Javiana counts, excluding pan genome
# only genes present in both reference strains will be maintained
cj.core <- merge(fc.cerro$counts, fc.javiana$counts, by="row.names", all.x=F, all.y=F)
rownames(cj.core) <- cj.core$Row.names
table(is.na(as.vector(cj.core)))
colnames(cj.core) <- c("Feature", "Cerro-rep1", "Cerro-rep2", "Cerro-rep3", "Javiana-rep1", "Javiana-rep2", "Javiana-rep3")
write.table(x = cj.core, file="cerrojaviana_featurecounts_core.txt", append = F, quote = F, sep = "\t", row.names = F, col.names = T)
# merge Cerro and Javiana annotation, excluding pan genome
# only genes present in both reference strains will be maintained
cj.core <- merge(fc.cerro$annotation, fc.javiana$annotation, by="row.names", all.x=F, all.y=F)
rownames(cj.core) <- cj.core$Row.names
table(is.na(as.vector(cj.core)))
colnames(cj.core) <- c("Feature", "Cerro-rep1", "Cerro-rep2", "Cerro-rep3", "Javiana-rep1", "Javiana-rep2", "Javiana-rep3")
write.table(x = cj.core, file="cerrojaviana_annotation_core.txt", append = F, quote = F, sep = "\t", row.names = F, col.names = T)
# merge Cerro and Typhimurium counts, excluding pan genome
# only genes present in both reference strains will be maintained
ct.core <- merge(fc.cerro$counts, fc.typhimurium$counts, by="row.names", all.x=F, all.y=F)
rownames(ct.core) <- ct.core$Row.names
table(is.na(as.vector(ct.core)))
colnames(ct.core) <- c("Feature", "Cerro-rep1", "Cerro-rep2", "Cerro-rep3", "Typhimurium-rep1", "Typhimurium-rep2", "Typhimurium-rep3")
write.table(x = ct.core, file="cerrotyphimurium_featurecounts_core.txt", append = F, quote = F, sep = "\t", row.names = F, col.names = T)
# merge Javiana and Typhimurium counts, excluding pan genome
# only genes present in both reference strains will be maintained
jt.core <- merge(fc.javiana$counts, fc.typhimurium$counts, by="row.names", all.x=F, all.y=F)
rownames(jt.core) <- jt.core$Row.names
table(is.na(as.vector(jt.core)))
colnames(jt.core) <- c("Feature", "Javiana-rep1", "Javiana-rep2", "Javiana-rep3", "Typhimurium-rep1", "Typhimurium-rep2", "Typhimurium-rep3")
write.table(x = jt.core, file="javianatyphimurium_featurecounts_core.txt", append = F, quote = F, sep = "\t", row.names = F, col.names = T)
# merge CerroJaviana and Typhimurium counts, excluding pan genome
# only genes present in all three reference strains will be maintained
cjt.core <- merge(cj.core, fc.typhimurium$counts, by="row.names", all.x=F, all.y=F)
# sanity check; there should be no NAs (this is just the core genome of the 3 strains)
table(is.na(as.vector(cjt.core)))
# change the column names of the count matrix to make it more readable
colnames(cjt.core) <- c("Feature", "Cerro-rep1", "Cerro-rep2", "Cerro-rep3",
"Javiana-rep1", "Javiana-rep2", "Javiana-rep3",
"Typhimurium-rep1", "Typhimurium-rep2", "Typhimurium-rep3")
# write this core-genome count matrix to a tab-delimited file
# file is named CerroJavianaTyphimurium_featureCounts_drop_panGenome.txt
write.table(x = cjt.core, file = "CerroJavianaTyphimurium_featureCounts_drop_panGenome.txt",
append = F, quote = F, sep = "\t", row.names = F, col.names = T)
# merge CerroJaviana and Typhimurium annotation, excluding pan genome
# only genes present in all three reference strains will be maintained
cjt.core <- merge(cj.core, fc.typhimurium$annotation, by="row.names", all.x=F, all.y=F)
# sanity check; there should be no NAs (this is just the core genome of the 3 strains)
table(is.na(as.vector(cjt.core)))
# change the column names of the count matrix to make it more readable
colnames(cjt.core) <- c("Feature", "Cerro-rep1", "Cerro-rep2", "Cerro-rep3",
"Javiana-rep1", "Javiana-rep2", "Javiana-rep3",
"Typhimurium-rep1", "Typhimurium-rep2", "Typhimurium-rep3")
# write this core-genome count matrix to a tab-delimited file
# file is named CerroJavianaTyphimurium_featureCounts_drop_panGenome.txt
write.table(x = cjt.core, file = "cjt_annotation.txt",
append = F, quote = F, sep = "\t", row.names = F, col.names = T)
|
# Copyright 2019 Observational Health Data Sciences and Informatics
#
# This file is part of aspirin365
#
# 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.
#' Run CohortMethod package
#'
#' @details
#' Run the CohortMethod package, which implements the comparative cohort design.
#'
#' @param connectionDetails An object of type \code{connectionDetails} as created using the
#' \code{\link[DatabaseConnector]{createConnectionDetails}} function in the
#' DatabaseConnector package.
#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides.
#' Note that for SQL Server, this should include both the database and
#' schema name, for example 'cdm_data.dbo'.
#' @param cohortDatabaseSchema Schema name where intermediate data can be stored. You will need to have
#' write priviliges in this schema. Note that for SQL Server, this should
#' include both the database and schema name, for example 'cdm_data.dbo'.
#' @param cohortTable The name of the table that will be created in the work database schema.
#' This table will hold the exposure and outcome cohorts used in this
#' study.
#' @param oracleTempSchema Should be used in Oracle to specify a schema where the user has write
#' priviliges for storing temporary tables.
#' @param outputFolder Name of local folder where the results were generated; make sure to use forward slashes
#' (/). Do not use a folder on a network drive since this greatly impacts
#' performance.
#' @param maxCores How many parallel cores should be used? If more cores are made available
#' this can speed up the analyses.
#'
#' @export
runCohortMethod <- function(connectionDetails,
cdmDatabaseSchema,
cohortDatabaseSchema,
cohortTable,
oracleTempSchema,
outputFolder,
maxCores) {
cmOutputFolder <- file.path(outputFolder, "cmOutput")
if (!file.exists(cmOutputFolder)) {
dir.create(cmOutputFolder)
}
cmAnalysisListFile <- system.file("settings",
"cmAnalysisList.json",
package = "aspirin365")
cmAnalysisList <- CohortMethod::loadCmAnalysisList(cmAnalysisListFile)
SubgroupCovSet <- createSubgroupCovariateSettings(windowStart = -99999, windowEnd = -1, analysisId = 998)
for (i in seq_along(cmAnalysisList)){
cmAnalysisList[[i]]$getDbCohortMethodDataArgs$covariateSettings <- list(cmAnalysisList[[i]]$getDbCohortMethodDataArgs$covariateSettings, SubgroupCovSet)
}
tcosList <- createTcos(outputFolder = outputFolder)
outcomesOfInterest <- getOutcomesOfInterest()
results <- CohortMethod::runCmAnalyses(connectionDetails = connectionDetails,
cdmDatabaseSchema = cdmDatabaseSchema,
exposureDatabaseSchema = cohortDatabaseSchema,
exposureTable = cohortTable,
outcomeDatabaseSchema = cohortDatabaseSchema,
outcomeTable = cohortTable,
outputFolder = cmOutputFolder,
oracleTempSchema = oracleTempSchema,
cmAnalysisList = cmAnalysisList,
targetComparatorOutcomesList = tcosList,
getDbCohortMethodDataThreads = min(3, maxCores),
createStudyPopThreads = min(3, maxCores),
createPsThreads = max(1, round(maxCores/10)),
psCvThreads = min(10, maxCores),
trimMatchStratifyThreads = min(10, maxCores),
fitOutcomeModelThreads = max(1, round(maxCores/4)),
outcomeCvThreads = min(4, maxCores),
refitPsForEveryOutcome = FALSE,
outcomeIdsOfInterest = outcomesOfInterest)
ParallelLogger::logInfo("Summarizing results")
analysisSummary <- CohortMethod::summarizeAnalyses(referenceTable = results,
outputFolder = cmOutputFolder)
analysisSummary <- addCohortNames(analysisSummary, "targetId", "targetName")
analysisSummary <- addCohortNames(analysisSummary, "comparatorId", "comparatorName")
analysisSummary <- addCohortNames(analysisSummary, "outcomeId", "outcomeName")
analysisSummary <- addAnalysisDescription(analysisSummary, "analysisId", "analysisDescription")
write.csv(analysisSummary, file.path(outputFolder, "analysisSummary.csv"), row.names = FALSE)
ParallelLogger::logInfo("Computing covariate balance")
balanceFolder <- file.path(outputFolder, "balance")
if (!file.exists(balanceFolder)) {
dir.create(balanceFolder)
}
subset <- results[results$outcomeId %in% outcomesOfInterest,]
subset <- subset[subset$strataFile != "", ]
if (nrow(subset) > 0) {
subset <- split(subset, seq(nrow(subset)))
cluster <- ParallelLogger::makeCluster(min(3, maxCores))
ParallelLogger::clusterApply(cluster, subset, computeCovariateBalance, cmOutputFolder = cmOutputFolder, balanceFolder = balanceFolder)
ParallelLogger::stopCluster(cluster)
}
}
computeCovariateBalance <- function(row, cmOutputFolder, balanceFolder) {
outputFileName <- file.path(balanceFolder,
sprintf("bal_t%s_c%s_o%s_a%s.rds", row$targetId, row$comparatorId, row$outcomeId, row$analysisId))
if (!file.exists(outputFileName)) {
ParallelLogger::logTrace("Creating covariate balance file ", outputFileName)
cohortMethodDataFolder <- file.path(cmOutputFolder, row$cohortMethodDataFolder)
cohortMethodData <- CohortMethod::loadCohortMethodData(cohortMethodDataFolder)
strataFile <- file.path(cmOutputFolder, row$strataFile)
strata <- readRDS(strataFile)
balance <- CohortMethod::computeCovariateBalance(population = strata, cohortMethodData = cohortMethodData)
saveRDS(balance, outputFileName)
}
}
addAnalysisDescription <- function(data, IdColumnName = "analysisId", nameColumnName = "analysisDescription") {
cmAnalysisListFile <- system.file("settings",
"cmAnalysisList.json",
package = "aspirin365")
cmAnalysisList <- CohortMethod::loadCmAnalysisList(cmAnalysisListFile)
SubgroupCovSet <- createSubgroupCovariateSettings(windowStart = -99999, windowEnd = -1, analysisId = 998)
for (i in seq_along(cmAnalysisList)){
cmAnalysisList[[i]]$getDbCohortMethodDataArgs$covariateSettings <- list(cmAnalysisList[[i]]$getDbCohortMethodDataArgs$covariateSettings, SubgroupCovSet)
}
idToName <- lapply(cmAnalysisList, function(x) data.frame(analysisId = x$analysisId, description = as.character(x$description)))
idToName <- do.call("rbind", idToName)
names(idToName)[1] <- IdColumnName
names(idToName)[2] <- nameColumnName
data <- merge(data, idToName, all.x = TRUE)
# Change order of columns:
idCol <- which(colnames(data) == IdColumnName)
if (idCol < ncol(data) - 1) {
data <- data[, c(1:idCol, ncol(data) , (idCol+1):(ncol(data)-1))]
}
return(data)
}
createTcos <- function(outputFolder) {
pathToCsv <- system.file("settings", "TcosOfInterest.csv", package = "aspirin365")
tcosOfInterest <- read.csv(pathToCsv, stringsAsFactors = FALSE)
allControls <- getAllControls(outputFolder)
tcs <- unique(rbind(tcosOfInterest[, c("targetId", "comparatorId")],
allControls[, c("targetId", "comparatorId")]))
createTco <- function(i) {
targetId <- tcs$targetId[i]
comparatorId <- tcs$comparatorId[i]
outcomeIds <- as.character(tcosOfInterest$outcomeIds[tcosOfInterest$targetId == targetId & tcosOfInterest$comparatorId == comparatorId])
outcomeIds <- as.numeric(strsplit(outcomeIds, split = ";")[[1]])
outcomeIds <- c(outcomeIds, allControls$outcomeId[allControls$targetId == targetId & allControls$comparatorId == comparatorId])
excludeConceptIds <- as.character(tcosOfInterest$excludedCovariateConceptIds[tcosOfInterest$targetId == targetId & tcosOfInterest$comparatorId == comparatorId])
if (length(excludeConceptIds) == 1 && is.na(excludeConceptIds)) {
excludeConceptIds <- c()
} else if (length(excludeConceptIds) > 0) {
excludeConceptIds <- as.numeric(strsplit(excludeConceptIds, split = ";")[[1]])
}
includeConceptIds <- as.character(tcosOfInterest$includedCovariateConceptIds[tcosOfInterest$targetId == targetId & tcosOfInterest$comparatorId == comparatorId])
if (length(includeConceptIds) == 1 && is.na(includeConceptIds)) {
includeConceptIds <- c()
} else if (length(includeConceptIds) > 0) {
includeConceptIds <- as.numeric(strsplit(excludeConceptIds, split = ";")[[1]])
}
tco <- CohortMethod::createTargetComparatorOutcomes(targetId = targetId,
comparatorId = comparatorId,
outcomeIds = outcomeIds,
excludedCovariateConceptIds = excludeConceptIds,
includedCovariateConceptIds = includeConceptIds)
return(tco)
}
tcosList <- lapply(1:nrow(tcs), createTco)
return(tcosList)
}
getOutcomesOfInterest <- function() {
pathToCsv <- system.file("settings", "TcosOfInterest.csv", package = "aspirin365")
tcosOfInterest <- read.csv(pathToCsv, stringsAsFactors = FALSE)
outcomeIds <- as.character(tcosOfInterest$outcomeIds)
outcomeIds <- do.call("c", (strsplit(outcomeIds, split = ";")))
outcomeIds <- unique(as.numeric(outcomeIds))
return(outcomeIds)
}
getAllControls <- function(outputFolder) {
allControlsFile <- file.path(outputFolder, "AllControls.csv")
if (file.exists(allControlsFile)) {
# Positive controls must have been synthesized. Include both positive and negative controls.
allControls <- read.csv(allControlsFile)
} else {
# Include only negative controls
pathToCsv <- system.file("settings", "NegativeControls.csv", package = "aspirin365")
allControls <- read.csv(pathToCsv)
allControls$oldOutcomeId <- allControls$outcomeId
allControls$targetEffectSize <- rep(1, nrow(allControls))
}
return(allControls)
}
|
/aspirin365/R/CohortMethod.R
|
permissive
|
rlawodud3920/CDM-Rpackage-2020
|
R
| false | false | 11,679 |
r
|
# Copyright 2019 Observational Health Data Sciences and Informatics
#
# This file is part of aspirin365
#
# 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.
#' Run CohortMethod package
#'
#' @details
#' Run the CohortMethod package, which implements the comparative cohort design.
#'
#' @param connectionDetails An object of type \code{connectionDetails} as created using the
#' \code{\link[DatabaseConnector]{createConnectionDetails}} function in the
#' DatabaseConnector package.
#' @param cdmDatabaseSchema Schema name where your patient-level data in OMOP CDM format resides.
#' Note that for SQL Server, this should include both the database and
#' schema name, for example 'cdm_data.dbo'.
#' @param cohortDatabaseSchema Schema name where intermediate data can be stored. You will need to have
#' write priviliges in this schema. Note that for SQL Server, this should
#' include both the database and schema name, for example 'cdm_data.dbo'.
#' @param cohortTable The name of the table that will be created in the work database schema.
#' This table will hold the exposure and outcome cohorts used in this
#' study.
#' @param oracleTempSchema Should be used in Oracle to specify a schema where the user has write
#' priviliges for storing temporary tables.
#' @param outputFolder Name of local folder where the results were generated; make sure to use forward slashes
#' (/). Do not use a folder on a network drive since this greatly impacts
#' performance.
#' @param maxCores How many parallel cores should be used? If more cores are made available
#' this can speed up the analyses.
#'
#' @export
runCohortMethod <- function(connectionDetails,
cdmDatabaseSchema,
cohortDatabaseSchema,
cohortTable,
oracleTempSchema,
outputFolder,
maxCores) {
cmOutputFolder <- file.path(outputFolder, "cmOutput")
if (!file.exists(cmOutputFolder)) {
dir.create(cmOutputFolder)
}
cmAnalysisListFile <- system.file("settings",
"cmAnalysisList.json",
package = "aspirin365")
cmAnalysisList <- CohortMethod::loadCmAnalysisList(cmAnalysisListFile)
SubgroupCovSet <- createSubgroupCovariateSettings(windowStart = -99999, windowEnd = -1, analysisId = 998)
for (i in seq_along(cmAnalysisList)){
cmAnalysisList[[i]]$getDbCohortMethodDataArgs$covariateSettings <- list(cmAnalysisList[[i]]$getDbCohortMethodDataArgs$covariateSettings, SubgroupCovSet)
}
tcosList <- createTcos(outputFolder = outputFolder)
outcomesOfInterest <- getOutcomesOfInterest()
results <- CohortMethod::runCmAnalyses(connectionDetails = connectionDetails,
cdmDatabaseSchema = cdmDatabaseSchema,
exposureDatabaseSchema = cohortDatabaseSchema,
exposureTable = cohortTable,
outcomeDatabaseSchema = cohortDatabaseSchema,
outcomeTable = cohortTable,
outputFolder = cmOutputFolder,
oracleTempSchema = oracleTempSchema,
cmAnalysisList = cmAnalysisList,
targetComparatorOutcomesList = tcosList,
getDbCohortMethodDataThreads = min(3, maxCores),
createStudyPopThreads = min(3, maxCores),
createPsThreads = max(1, round(maxCores/10)),
psCvThreads = min(10, maxCores),
trimMatchStratifyThreads = min(10, maxCores),
fitOutcomeModelThreads = max(1, round(maxCores/4)),
outcomeCvThreads = min(4, maxCores),
refitPsForEveryOutcome = FALSE,
outcomeIdsOfInterest = outcomesOfInterest)
ParallelLogger::logInfo("Summarizing results")
analysisSummary <- CohortMethod::summarizeAnalyses(referenceTable = results,
outputFolder = cmOutputFolder)
analysisSummary <- addCohortNames(analysisSummary, "targetId", "targetName")
analysisSummary <- addCohortNames(analysisSummary, "comparatorId", "comparatorName")
analysisSummary <- addCohortNames(analysisSummary, "outcomeId", "outcomeName")
analysisSummary <- addAnalysisDescription(analysisSummary, "analysisId", "analysisDescription")
write.csv(analysisSummary, file.path(outputFolder, "analysisSummary.csv"), row.names = FALSE)
ParallelLogger::logInfo("Computing covariate balance")
balanceFolder <- file.path(outputFolder, "balance")
if (!file.exists(balanceFolder)) {
dir.create(balanceFolder)
}
subset <- results[results$outcomeId %in% outcomesOfInterest,]
subset <- subset[subset$strataFile != "", ]
if (nrow(subset) > 0) {
subset <- split(subset, seq(nrow(subset)))
cluster <- ParallelLogger::makeCluster(min(3, maxCores))
ParallelLogger::clusterApply(cluster, subset, computeCovariateBalance, cmOutputFolder = cmOutputFolder, balanceFolder = balanceFolder)
ParallelLogger::stopCluster(cluster)
}
}
computeCovariateBalance <- function(row, cmOutputFolder, balanceFolder) {
outputFileName <- file.path(balanceFolder,
sprintf("bal_t%s_c%s_o%s_a%s.rds", row$targetId, row$comparatorId, row$outcomeId, row$analysisId))
if (!file.exists(outputFileName)) {
ParallelLogger::logTrace("Creating covariate balance file ", outputFileName)
cohortMethodDataFolder <- file.path(cmOutputFolder, row$cohortMethodDataFolder)
cohortMethodData <- CohortMethod::loadCohortMethodData(cohortMethodDataFolder)
strataFile <- file.path(cmOutputFolder, row$strataFile)
strata <- readRDS(strataFile)
balance <- CohortMethod::computeCovariateBalance(population = strata, cohortMethodData = cohortMethodData)
saveRDS(balance, outputFileName)
}
}
addAnalysisDescription <- function(data, IdColumnName = "analysisId", nameColumnName = "analysisDescription") {
cmAnalysisListFile <- system.file("settings",
"cmAnalysisList.json",
package = "aspirin365")
cmAnalysisList <- CohortMethod::loadCmAnalysisList(cmAnalysisListFile)
SubgroupCovSet <- createSubgroupCovariateSettings(windowStart = -99999, windowEnd = -1, analysisId = 998)
for (i in seq_along(cmAnalysisList)){
cmAnalysisList[[i]]$getDbCohortMethodDataArgs$covariateSettings <- list(cmAnalysisList[[i]]$getDbCohortMethodDataArgs$covariateSettings, SubgroupCovSet)
}
idToName <- lapply(cmAnalysisList, function(x) data.frame(analysisId = x$analysisId, description = as.character(x$description)))
idToName <- do.call("rbind", idToName)
names(idToName)[1] <- IdColumnName
names(idToName)[2] <- nameColumnName
data <- merge(data, idToName, all.x = TRUE)
# Change order of columns:
idCol <- which(colnames(data) == IdColumnName)
if (idCol < ncol(data) - 1) {
data <- data[, c(1:idCol, ncol(data) , (idCol+1):(ncol(data)-1))]
}
return(data)
}
createTcos <- function(outputFolder) {
pathToCsv <- system.file("settings", "TcosOfInterest.csv", package = "aspirin365")
tcosOfInterest <- read.csv(pathToCsv, stringsAsFactors = FALSE)
allControls <- getAllControls(outputFolder)
tcs <- unique(rbind(tcosOfInterest[, c("targetId", "comparatorId")],
allControls[, c("targetId", "comparatorId")]))
createTco <- function(i) {
targetId <- tcs$targetId[i]
comparatorId <- tcs$comparatorId[i]
outcomeIds <- as.character(tcosOfInterest$outcomeIds[tcosOfInterest$targetId == targetId & tcosOfInterest$comparatorId == comparatorId])
outcomeIds <- as.numeric(strsplit(outcomeIds, split = ";")[[1]])
outcomeIds <- c(outcomeIds, allControls$outcomeId[allControls$targetId == targetId & allControls$comparatorId == comparatorId])
excludeConceptIds <- as.character(tcosOfInterest$excludedCovariateConceptIds[tcosOfInterest$targetId == targetId & tcosOfInterest$comparatorId == comparatorId])
if (length(excludeConceptIds) == 1 && is.na(excludeConceptIds)) {
excludeConceptIds <- c()
} else if (length(excludeConceptIds) > 0) {
excludeConceptIds <- as.numeric(strsplit(excludeConceptIds, split = ";")[[1]])
}
includeConceptIds <- as.character(tcosOfInterest$includedCovariateConceptIds[tcosOfInterest$targetId == targetId & tcosOfInterest$comparatorId == comparatorId])
if (length(includeConceptIds) == 1 && is.na(includeConceptIds)) {
includeConceptIds <- c()
} else if (length(includeConceptIds) > 0) {
includeConceptIds <- as.numeric(strsplit(excludeConceptIds, split = ";")[[1]])
}
tco <- CohortMethod::createTargetComparatorOutcomes(targetId = targetId,
comparatorId = comparatorId,
outcomeIds = outcomeIds,
excludedCovariateConceptIds = excludeConceptIds,
includedCovariateConceptIds = includeConceptIds)
return(tco)
}
tcosList <- lapply(1:nrow(tcs), createTco)
return(tcosList)
}
getOutcomesOfInterest <- function() {
pathToCsv <- system.file("settings", "TcosOfInterest.csv", package = "aspirin365")
tcosOfInterest <- read.csv(pathToCsv, stringsAsFactors = FALSE)
outcomeIds <- as.character(tcosOfInterest$outcomeIds)
outcomeIds <- do.call("c", (strsplit(outcomeIds, split = ";")))
outcomeIds <- unique(as.numeric(outcomeIds))
return(outcomeIds)
}
getAllControls <- function(outputFolder) {
allControlsFile <- file.path(outputFolder, "AllControls.csv")
if (file.exists(allControlsFile)) {
# Positive controls must have been synthesized. Include both positive and negative controls.
allControls <- read.csv(allControlsFile)
} else {
# Include only negative controls
pathToCsv <- system.file("settings", "NegativeControls.csv", package = "aspirin365")
allControls <- read.csv(pathToCsv)
allControls$oldOutcomeId <- allControls$outcomeId
allControls$targetEffectSize <- rep(1, nrow(allControls))
}
return(allControls)
}
|
data = read.csv("all.csv")
attach(data)
gap = dem_pct-gop_pct
fit = glm(gap ~ gdp_pct * incumbent * relec)
fit
newdata = data.frame(gdp_pct=c(2.43), incumbent=c(0), relec=c(FALSE))
predict(fit, newdata)
pcts = seq(-5,5,by=0.1)
hypdata = data.frame(gdp_pct=pcts, incumbent=rep(0,101), relec=rep(FALSE,101))
predicted = predict(fit, hypdata)
plot(predicted)
|
/bayesian-president/data/elections/elec.R
|
no_license
|
CoryMcCartan/election-2016
|
R
| false | false | 356 |
r
|
data = read.csv("all.csv")
attach(data)
gap = dem_pct-gop_pct
fit = glm(gap ~ gdp_pct * incumbent * relec)
fit
newdata = data.frame(gdp_pct=c(2.43), incumbent=c(0), relec=c(FALSE))
predict(fit, newdata)
pcts = seq(-5,5,by=0.1)
hypdata = data.frame(gdp_pct=pcts, incumbent=rep(0,101), relec=rep(FALSE,101))
predicted = predict(fit, hypdata)
plot(predicted)
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/RcppExports.R
\name{optim_Ridge}
\alias{optim_Ridge}
\title{find optimized solution for ObjectRidge function}
\usage{
optim_Ridge(theta, X, y, family, r)
}
\arguments{
\item{theta}{vector store our optimized result}
\item{X}{high dimensional matrix}
\item{y}{where y = Xβ + ε}
\item{family}{three family cases: gaussian, poisson and binomial}
\item{r}{tuning.parameter}
}
\description{
find optimized solution for ObjectRidge function
}
|
/man/optim_Ridge.Rd
|
permissive
|
aahilgert/myTridge
|
R
| false | true | 521 |
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/RcppExports.R
\name{optim_Ridge}
\alias{optim_Ridge}
\title{find optimized solution for ObjectRidge function}
\usage{
optim_Ridge(theta, X, y, family, r)
}
\arguments{
\item{theta}{vector store our optimized result}
\item{X}{high dimensional matrix}
\item{y}{where y = Xβ + ε}
\item{family}{three family cases: gaussian, poisson and binomial}
\item{r}{tuning.parameter}
}
\description{
find optimized solution for ObjectRidge function
}
|
## Date: 4 October, 2022
## Author: Drew Neavin
## Reason: RNA velocity on iPSC village samples for pseudotime following the Allevin tutorial https://combine-lab.github.io/alevin-tutorial/2020/alevin-velocity/
library(Biostrings)
library(BSgenome)
library(eisaR)
library(GenomicFeatures)
library(SummarizedExperiment)
library(tximeta)
library(rjson)
library(reticulate)
library(SingleCellExperiment)
library(scater)
outdir <- "/path/to/output/RNA_Velocity_Pseudotime/preprocess"
dir.create(outdir, recursive = TRUE)
gtf <- "/path/to/gencode.v38.annotation.gtf.gz" # available from https://www.gencodegenes.org/human/release_38.html
fasta <- "/path/to/GRCh38.primary_assembly.genome.fa" # available from https://www.gencodegenes.org/human/release_38.html
pool_dir_10x <- "/path/to/cellranger/gene_expression/" ### Available by processing fastq data through cellranger or on request from d.neavin @ garvan.org.au
##################################################
##### Step 1. Generate reference fasta files #####
##################################################
##### Read in gtf file as GRanges Object #####
grl <- eisaR::getFeatureRanges(
gtf = gtf,
featureType = c("spliced", "intron"),
intronType = "separate",
flankLength = 90L,
joinOverlappingIntrons = FALSE,
verbose = TRUE
)
##### Make fasta file overlapping gtf #####
genome <- Biostrings::readDNAStringSet(
fasta
)
names(genome) <- sapply(strsplit(names(genome), " "), .subset, 1)
seqs <- GenomicFeatures::extractTranscriptSeqs(
x = genome,
transcripts = grl
)
Biostrings::writeXStringSet(
seqs, filepath = paste0(outdir, "gencode.v38.annotation.expanded.fa")
)
##### Write Explanded annotation file #####
eisaR::exportToGtf(
grl,
filepath = "gencode.v38.annotation.expanded.gtf"
)
##### Write spliced and unspliced seqwuences #####
head(metadata(grl)$corrgene)
write.table(
metadata(grl)$corrgene,
file = paste0(outdir,"gencode.v38.annotation.expanded.features.tsv"),
row.names = FALSE, col.names = TRUE, quote = FALSE, sep = "\t"
)
##### Write file for mapping transcripts to genes #####
df <- eisaR::getTx2Gene(
grl, filepath = paste0(outdir,"gencode.v38.annotation.expanded.tx2gene.tsv")
)
################################################
##### Step 2. Index the reference features #####
################################################
system(paste0('grep ">" ',fasta,' | cut -d ">" -f 2 | cut -d " " -f 1 > ', outdir, 'GRCh38.primary_assembly.genome.chrnames.txt'))
system(paste0('cat ',outdir, 'gencode.v38.annotation.expanded.fa ', fasta, '> ', outdir, 'combined_fasta.fa'))
### Run salmon index using submission system (qsub): salmon_index.qsub
##### Make tximeta linked transcriptome #####
tximeta::makeLinkedTxome(
indexDir = paste0(outdir,"gencode.v38.annotation.expanded.sidx"),
source = "GENCODE", genome = "GRCh38",
organism = "Homo sapiens", release = "38",
fasta = paste0(outdir,"gencode.v38.annotation.expanded.fa"),
gtf = paste0(outdir,"gencode.v38.annotation.expanded.gtf"),
write = TRUE, jsonFile = "gencode.v38.annotation.expanded.json")
rjson::fromJSON(file = "gencode.v38.annotation.expanded.json")
|
/scripts/hiPSC_village_3_lines/RNA_Velocity_Pseudotime/scVelo_preprocess.R
|
no_license
|
powellgenomicslab/iPSC_Village_Publication
|
R
| false | false | 3,182 |
r
|
## Date: 4 October, 2022
## Author: Drew Neavin
## Reason: RNA velocity on iPSC village samples for pseudotime following the Allevin tutorial https://combine-lab.github.io/alevin-tutorial/2020/alevin-velocity/
library(Biostrings)
library(BSgenome)
library(eisaR)
library(GenomicFeatures)
library(SummarizedExperiment)
library(tximeta)
library(rjson)
library(reticulate)
library(SingleCellExperiment)
library(scater)
outdir <- "/path/to/output/RNA_Velocity_Pseudotime/preprocess"
dir.create(outdir, recursive = TRUE)
gtf <- "/path/to/gencode.v38.annotation.gtf.gz" # available from https://www.gencodegenes.org/human/release_38.html
fasta <- "/path/to/GRCh38.primary_assembly.genome.fa" # available from https://www.gencodegenes.org/human/release_38.html
pool_dir_10x <- "/path/to/cellranger/gene_expression/" ### Available by processing fastq data through cellranger or on request from d.neavin @ garvan.org.au
##################################################
##### Step 1. Generate reference fasta files #####
##################################################
##### Read in gtf file as GRanges Object #####
grl <- eisaR::getFeatureRanges(
gtf = gtf,
featureType = c("spliced", "intron"),
intronType = "separate",
flankLength = 90L,
joinOverlappingIntrons = FALSE,
verbose = TRUE
)
##### Make fasta file overlapping gtf #####
genome <- Biostrings::readDNAStringSet(
fasta
)
names(genome) <- sapply(strsplit(names(genome), " "), .subset, 1)
seqs <- GenomicFeatures::extractTranscriptSeqs(
x = genome,
transcripts = grl
)
Biostrings::writeXStringSet(
seqs, filepath = paste0(outdir, "gencode.v38.annotation.expanded.fa")
)
##### Write Explanded annotation file #####
eisaR::exportToGtf(
grl,
filepath = "gencode.v38.annotation.expanded.gtf"
)
##### Write spliced and unspliced seqwuences #####
head(metadata(grl)$corrgene)
write.table(
metadata(grl)$corrgene,
file = paste0(outdir,"gencode.v38.annotation.expanded.features.tsv"),
row.names = FALSE, col.names = TRUE, quote = FALSE, sep = "\t"
)
##### Write file for mapping transcripts to genes #####
df <- eisaR::getTx2Gene(
grl, filepath = paste0(outdir,"gencode.v38.annotation.expanded.tx2gene.tsv")
)
################################################
##### Step 2. Index the reference features #####
################################################
system(paste0('grep ">" ',fasta,' | cut -d ">" -f 2 | cut -d " " -f 1 > ', outdir, 'GRCh38.primary_assembly.genome.chrnames.txt'))
system(paste0('cat ',outdir, 'gencode.v38.annotation.expanded.fa ', fasta, '> ', outdir, 'combined_fasta.fa'))
### Run salmon index using submission system (qsub): salmon_index.qsub
##### Make tximeta linked transcriptome #####
tximeta::makeLinkedTxome(
indexDir = paste0(outdir,"gencode.v38.annotation.expanded.sidx"),
source = "GENCODE", genome = "GRCh38",
organism = "Homo sapiens", release = "38",
fasta = paste0(outdir,"gencode.v38.annotation.expanded.fa"),
gtf = paste0(outdir,"gencode.v38.annotation.expanded.gtf"),
write = TRUE, jsonFile = "gencode.v38.annotation.expanded.json")
rjson::fromJSON(file = "gencode.v38.annotation.expanded.json")
|
library(testthat)
library(RsNlme)
test_package("RsNlme")
|
/RsNlme/tests/run_test.r
|
no_license
|
phxnlmedev/rpackages
|
R
| false | false | 58 |
r
|
library(testthat)
library(RsNlme)
test_package("RsNlme")
|
library(data.table)
library(prophet)
library(dplyr)
library(ggpubr)
library(Metrics)
dt=data.table(read.csv('sample_fb.csv'))
offers=data.table(read.csv('offers.csv'))
dt$Day=as.Date(as.character(dt$Day))
offers$Date=as.Date(as.character(offers$Date))
names(dt)=c('ds','y')
dt= dt[order(ds),]
############# Daily Forecasting #####
dt_train = dt[ds< '2019-05-01',]
##### Adding NZ holidays and promos as extra events #######
#holidays=data.table(prophet::generated_holidays)
#holidays= holidays[year %in% c('2018','2019','2020') & country=='NZ',]
#xmass_eve=data.table(holiday='xmass_Eve',ds=as.Date(c('2018-12-24','2019-12-24','2020-12-24')))
easter_break_19=data.table(holiday='easter_break_19',ds=as.Date('2019-04-19'),lower_window = 0,
upper_window = 10,prior_scale=40)
newyear_break=data.table(holiday='newyear_break',ds=as.Date('2017-12-22','2018-12-22','2019-12-22','2020-12-22'),lower_window = 0,
upper_window = 16,prior_scale=40
)
school_hols <- data.table(
holiday = 'School_holiday',ds = as.Date(c('2017-04-13', '2017-06-08', '2017-10-01',
'2018-04-13', '2018-06-08', '2018-10-01',
'2019-04-13', '2019-06-08', '2019-10-01',
'2020-04-13', '2020-06-08', '2020-10-01',
'2021-04-13', '2021-06-08', '2021-10-01',
'2022-04-13', '2022-06-08', '2022-10-01',
'2023-04-13', '2023-06-08', '2023-10-01',
'2024-04-13', '2024-06-08', '2024-10-01',
'2025-04-13', '2025-06-08', '2025-10-01'
,'2026-04-13', '2026-06-08', '2026-10-01')),
lower_window = -2,
upper_window = 14,
prior_scale=15
)
offer= data.table(holiday='offer',ds=as.Date(as.character(offers$Date)),lower_window = 0,
upper_window = 0,prior_scale=100)
holidays=rbind(easter_break_19,newyear_break,school_hols)
holidays_offers=rbind(easter_break_19,newyear_break,school_hols,offer)
m = prophet(holidays = holidays_offers,changepoint.prior.scale = 5,daily.seasonality=FALSE)
#holidays.prior.scale = 15
m <- add_country_holidays(m, country_name = 'NZ')
#m <- add_seasonality(m, name='weekly', period=7, fourier.order=3, prior.scale=0.1)
m <- fit.prophet(m, dt_train)
future <- make_future_dataframe(m, periods =91 )
forecast <- predict(m, future)
prophet_plot_components(m, forecast)
plot(m, forecast)
##### Preparing dataframe for plotting ######
forecast_plot = forecast %>% select('ds','yhat')
#,'yhat_upper','yhat_lower')
forecast_plot$Type="Forecast"
forecast_plot$ds = as.Date(forecast_plot$ds)
names(forecast_plot)[2]="y"
dt$Type="Actuals"
df_plot= rbind(dt, forecast_plot)
df_plot= as.data.table(df_plot)
df_plot=df_plot[ds > '2019-01-01',]
ggline(df_plot, x = 'ds', y = 'y',color = 'Type',palette = c("#00AFBB", "#E7B800"))
### The accuracy of the model using RMSE and MAPE
|
/Forecast_GAM_v1.r
|
no_license
|
saracmbr/Code_Demo
|
R
| false | false | 2,669 |
r
|
library(data.table)
library(prophet)
library(dplyr)
library(ggpubr)
library(Metrics)
dt=data.table(read.csv('sample_fb.csv'))
offers=data.table(read.csv('offers.csv'))
dt$Day=as.Date(as.character(dt$Day))
offers$Date=as.Date(as.character(offers$Date))
names(dt)=c('ds','y')
dt= dt[order(ds),]
############# Daily Forecasting #####
dt_train = dt[ds< '2019-05-01',]
##### Adding NZ holidays and promos as extra events #######
#holidays=data.table(prophet::generated_holidays)
#holidays= holidays[year %in% c('2018','2019','2020') & country=='NZ',]
#xmass_eve=data.table(holiday='xmass_Eve',ds=as.Date(c('2018-12-24','2019-12-24','2020-12-24')))
easter_break_19=data.table(holiday='easter_break_19',ds=as.Date('2019-04-19'),lower_window = 0,
upper_window = 10,prior_scale=40)
newyear_break=data.table(holiday='newyear_break',ds=as.Date('2017-12-22','2018-12-22','2019-12-22','2020-12-22'),lower_window = 0,
upper_window = 16,prior_scale=40
)
school_hols <- data.table(
holiday = 'School_holiday',ds = as.Date(c('2017-04-13', '2017-06-08', '2017-10-01',
'2018-04-13', '2018-06-08', '2018-10-01',
'2019-04-13', '2019-06-08', '2019-10-01',
'2020-04-13', '2020-06-08', '2020-10-01',
'2021-04-13', '2021-06-08', '2021-10-01',
'2022-04-13', '2022-06-08', '2022-10-01',
'2023-04-13', '2023-06-08', '2023-10-01',
'2024-04-13', '2024-06-08', '2024-10-01',
'2025-04-13', '2025-06-08', '2025-10-01'
,'2026-04-13', '2026-06-08', '2026-10-01')),
lower_window = -2,
upper_window = 14,
prior_scale=15
)
offer= data.table(holiday='offer',ds=as.Date(as.character(offers$Date)),lower_window = 0,
upper_window = 0,prior_scale=100)
holidays=rbind(easter_break_19,newyear_break,school_hols)
holidays_offers=rbind(easter_break_19,newyear_break,school_hols,offer)
m = prophet(holidays = holidays_offers,changepoint.prior.scale = 5,daily.seasonality=FALSE)
#holidays.prior.scale = 15
m <- add_country_holidays(m, country_name = 'NZ')
#m <- add_seasonality(m, name='weekly', period=7, fourier.order=3, prior.scale=0.1)
m <- fit.prophet(m, dt_train)
future <- make_future_dataframe(m, periods =91 )
forecast <- predict(m, future)
prophet_plot_components(m, forecast)
plot(m, forecast)
##### Preparing dataframe for plotting ######
forecast_plot = forecast %>% select('ds','yhat')
#,'yhat_upper','yhat_lower')
forecast_plot$Type="Forecast"
forecast_plot$ds = as.Date(forecast_plot$ds)
names(forecast_plot)[2]="y"
dt$Type="Actuals"
df_plot= rbind(dt, forecast_plot)
df_plot= as.data.table(df_plot)
df_plot=df_plot[ds > '2019-01-01',]
ggline(df_plot, x = 'ds', y = 'y',color = 'Type',palette = c("#00AFBB", "#E7B800"))
### The accuracy of the model using RMSE and MAPE
|
## ----setup, include = FALSE----------------------------------------------
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
## ----ttest_ex1, eval=FALSE-----------------------------------------------
# # load the bain package which includes the simulated sesamesim data set
# library(bain)
# # collect the data for the boys in the vector x and for the girls in the
# # vector y
# x<-sesamesim$postnumb[which(sesamesim$sex==1)]
# y<-sesamesim$postnumb[which(sesamesim$sex==2)]
# # execute student's t-test
# ttest <- t_test(x,y,paired = FALSE, var.equal = TRUE)
# # Check the names of the estimates
# coef(ttest)
# # set a seed value
# set.seed(100)
# # test hypotheses with bain
# results <- bain(ttest, "x = y; x > y; x < y")
# # display the results
# results
# # obtain the descriptives table
# summary(results, ci = 0.95)
## ----ttest_ex2, eval=FALSE-----------------------------------------------
# # load the bain package which includes the simulated sesamesim data set
# library(bain)
# # collect the data for the boys in the vector x and for the girs in the
# # vector y
# x<-sesamesim$postnumb[which(sesamesim$sex==1)]
# y<-sesamesim$postnumb[which(sesamesim$sex==2)]
# # execute student's t-test
# ttest <- t_test(x,y,paired = FALSE, var.equal = FALSE)
# # Check the names of the coefficients
# coef(ttest)
# # set a seed value
# set.seed(100)
# # test hypotheses with bain
# results <- bain(ttest, "x = y; x > y; x < y")
# # display the results
# print(results)
# # obtain the descriptives table
# summary(results, ci = 0.95)
## ----ttest_ex3, eval=FALSE-----------------------------------------------
# # load the bain package which includes the simulated sesamesim data set
# library(bain)
# # compare the pre with the post measurements
# ttest <- t_test(sesamesim$prenumb,sesamesim$postnumb,paired = TRUE)
# # Check name of the coefficient
# coef(ttest)
# # set a seed value
# set.seed(100)
# # test hypotheses with bain
# results <- bain(ttest, "difference=0; difference>0; difference<0")
# # display the results
# print(results)
# # obtain the descriptives table
# summary(results, ci = 0.95)
## ----ttest_ex4, eval=FALSE-----------------------------------------------
# # load the bain package which includes the simulated sesamesim data se
# library(bain)
# # compare post measurements with the reference value 30
# ttest <- t_test(sesamesim$postnumb)
# # Check name of estimate
# coef(ttest)
# # set a seed value
# set.seed(100)
# # test hypotheses with bain versus the reference value 30
# results <- bain(ttest, "x=30; x>30; x<30")
# # display the results
# print(results)
# # obtain the descriptives table
# summary(results, ci = 0.95)
## ----ttest_ex5, eval=FALSE-----------------------------------------------
# # load the bain package which includes the simulated sesamesim data set
# library(bain)
# # collect the data for the boys in the vector x and for the girs in the
# # vector y
# x<-sesamesim$postnumb[which(sesamesim$sex==1)]
# y<-sesamesim$postnumb[which(sesamesim$sex==2)]
# # execute student's t-test
# ttest <- t_test(x,y,paired = FALSE, var.equal = TRUE)
# # Check the names of the estimates
# coef(ttest)
# # compute the pooled within standard deviation using the variance of x
# # (ttest$v[1]) and y (ttest$v[2])
# pwsd <- sqrt(((length(x) -1) * ttest$v[1] + (length(y)-1) * ttest$v[2])/
# ((length(x) -1) + (length(y) -1)))
# # print pwsd in order to be able to include it in the hypothesis. Its value
# # is 12.60
# print(pwsd)
# # set a seed value
# set.seed(100)
# # test hypotheses (the means of boy and girl differ less than .2 * pwsd =
# # 2.52 VERSUS the means differ more than .2 * pwsd = 2.52) with bain
# # note that, .2 is a value for Cohen's d reflecting a "small" effect, that
# # is, the means differ less or more than .2 pwsd.
# results <- bain(ttest, "x - y > -2.52 & x - y < 2.52")
# # display the results
# print(results)
# # obtain the descriptives table
# summary(results, ci = 0.95)
## ----ttest_ex6, eval=FALSE-----------------------------------------------
# # load the bain package which includes the simulated sesamesim data set
# library(bain)
# # make a factor of variable site
# sesamesim$site <- as.factor(sesamesim$site)
# # execute an analysis of variance using lm() which, due to the -1, returns
# # estimates of the means per group
# anov <- lm(postnumb~site-1,sesamesim)
# # take a look at the estimated means and their names
# coef(anov)
# # set a seed value
# set.seed(100)
# # test hypotheses with bain
# results <- bain(anov, "site1=site2=site3=site4=site5; site2>site5>site1>
# site3>site4")
# # display the results
# print(results)
# # obtain the descriptives table
# summary(results, ci = 0.95)
## ----ttest_ex7, eval=FALSE-----------------------------------------------
# # load the bain package which includes the simulated sesamesim data se
# library(bain)
# # make a factor of variable site
# sesamesim$site <- as.factor(sesamesim$site)
# # Center the covariate. If centered the coef() command below displays the
# # adjusted means. If not centered the intercepts are displayed.
# sesamesim$prenumb <- sesamesim$prenumb - mean(sesamesim$prenumb)
# # execute an analysis of covariance using lm() which, due to the -1, returns
# # estimates of the adjusted means per group
# ancov <- lm(postnumb~site+prenumb-1,sesamesim)
# # take a look at the estimated adjusted means, the regression coefficient
# # of the covariate and their names
# coef(ancov)
# # set a seed value
# set.seed(100)
# # test hypotheses with bain
# results <- bain(ancov, "site1=site2=site3=site4=site5;
# site2>site5>site1>site3>site4")
# # display the results
# print(results)
# # obtain the descriptives table
# summary(results, ci = 0.95)
## ----ttest_ex8, eval=FALSE-----------------------------------------------
# # load the bain package which includes the simulated sesamesim data set
# library(bain)
# # execute a multiple regression using lm()
# regr <- lm(postnumb ~ age + peabody + prenumb,sesamesim)
# # take a look at the estimated regression coefficients and their names
# coef(regr)
# # set a seed value
# set.seed(100)
# # test hypotheses with bain. Note that standardized = FALSE denotes that the
# # hypotheses are in terms of unstandardized regression coefficients
# results<-bain(regr, "age = 0 & peab=0 & pre=0 ; age > 0 & peab > 0 & pre > 0"
# , standardize = FALSE)
# # display the results
# print(results)
# # obtain the descriptives table
# summary(results, ci = 0.95)
# # Since it is only meaningful to compare regression coefficients if they are
# # measured on the same scale, bain can also evaluate standardized regression
# # coefficients (based on the seBeta function by Jeff Jones and Niels Waller):
# # set a seed value
# set.seed(100)
# # test hypotheses with bain. Note that standardized = TRUE denotes that the
# # hypotheses are in terms of standardized regression coefficients
# results<-bain(regr, "age = peab = pre ; pre > age > peab",standardize = TRUE)
# # display the results
# print(results)
# # obtain the descriptives table
# summary(results, ci = 0.95)
## ----ttest_ex9, eval=FALSE-----------------------------------------------
# # load the bain package which includes the simulated sesamesim data se
# library(bain)
# # make a factor of variable site
# sesamesim$site <- as.factor(sesamesim$site)
# # execute an analysis of variance using lm() which, due to the -1, returns
# # estimates of the means per group
# anov <- lm(postnumb~site-1,sesamesim)
# # take a look at the estimated means and their names
# coef(anov)
# # collect the estimates means in a vector
# estimate <- coef(anov)
# # give names to the estimates in anov
# names(estimate) <- c("site1", "site2", "site3","site4","site5")
# # create a vector containing the sample sizes of each group
# ngroup <- table(sesamesim$site)
# # compute for each group the covariance matrix of the parameters
# # of that group and collect these in a list
# # for the ANOVA this is simply a list containing for each group the variance
# # of the mean note that, the within group variance as estimated using lm is
# # used to compute the variance of each of the means! See, Hoijtink, Gu, and
# # Mulder (2018) for further elaborations.
# var <- summary(anov)$sigma**2
# cov1 <- matrix(var/ngroup[1], nrow=1, ncol=1)
# cov2 <- matrix(var/ngroup[2], nrow=1, ncol=1)
# cov3 <- matrix(var/ngroup[3], nrow=1, ncol=1)
# cov4 <- matrix(var/ngroup[4], nrow=1, ncol=1)
# cov5 <- matrix(var/ngroup[5], nrow=1, ncol=1)
# covlist <- list(cov1, cov2, cov3, cov4,cov5)
# # set a seed value
# set.seed(100)
# # test hypotheses with bain. Note that there are multiple groups
# # characterized by one mean, therefore group_parameters=0. Note that are no
# # joint parameters, therefore, joint_parameters=0.
# results <- bain(estimate,
# "site1=site2=site3=site4=site5; site2>site5>site1>site3>site4",
# n=ngroup,Sigma=covlist,group_parameters=1,joint_parameters = 0)
# # display the results
# print(results)
# # obtain the descriptives table
# summary(results, ci = 0.95)
## ----ttest_ex10, eval=FALSE----------------------------------------------
# # load the bain package which includes the simulated sesamesim data se
# library(bain)
# # make a factor of variable site
# sesamesim$site <- as.factor(sesamesim$site)
# # center the covariate. If centered the coef() command below displays the
# # adjusted means. If not centered the intercepts are displayed.
# sesamesim$prenumb <- sesamesim$prenumb - mean(sesamesim$prenumb)
# # execute an analysis of covariance using lm() which, due to the -1, returns
# # estimates of the adjusted means per group
# ancov2 <- lm(postnumb~site+prenumb-1,sesamesim)
# # take a look at the estimated adjusted means and their names
# coef(ancov2)
# # collect the estimates of the adjusted means and regression coefficient of
# # the covariate in a vector (the vector has to contain first the
# # adjusted means and next the regression coefficients of the covariates)
# estimates <- coef(ancov2)
# # assign names to the estimates
# names(estimates)<- c("v.1", "v.2", "v.3", "v.4","v.5", "pre")
# # compute the sample size per group
# ngroup <- table(sesamesim$site)
# # compute for each group the covariance matrix of the parameters of that
# # group and collect these in a list note that, the residual variance as
# # estimated using lm is used to compute these covariance matrices
# var <- (summary(ancov2)$sigma)**2
# # below, for each group, the covariance matrix of the adjusted mean and
# # covariate is computed
# # see Hoijtink, Gu, and Mulder (2018) for further explanation and elaboration
# cat1 <- subset(cbind(sesamesim$site,sesamesim$prenumb), sesamesim$site == 1)
# cat1[,1] <- 1
# cat1 <- as.matrix(cat1)
# cov1 <- var * solve(t(cat1) %*% cat1)
# #
# cat2 <- subset(cbind(sesamesim$site,sesamesim$prenumb), sesamesim$site == 2)
# cat2[,1] <- 1
# cat2 <- as.matrix(cat2)
# cov2 <- var * solve(t(cat2) %*% cat2)
# #
# cat3 <- subset(cbind(sesamesim$site,sesamesim$prenumb), sesamesim$site == 3)
# cat3[,1] <- 1
# cat3 <- as.matrix(cat3)
# cov3 <- var * solve(t(cat3) %*% cat3)
# #
# cat4 <- subset(cbind(sesamesim$site,sesamesim$prenumb), sesamesim$site == 4)
# cat4[,1] <- 1
# cat4 <- as.matrix(cat4)
# cov4 <- var * solve(t(cat4) %*% cat4)
# #
# cat5 <- subset(cbind(sesamesim$site,sesamesim$prenumb), sesamesim$site == 5)
# cat5[,1] <- 1
# cat5 <- as.matrix(cat5)
# cov5 <- var * solve(t(cat5) %*% cat5)
# #
# covariances <- list(cov1, cov2, cov3, cov4,cov5)
# # set a seed value
# set.seed(100)
# # test hypotheses with bain. Note that there are multiple groups
# # characterized by one adjusted mean, therefore group_parameters=1 Note that
# # there is one covariate, therefore, joint_parameters=1.
# results2<-bain(estimates,"v.1=v.2=v.3=v.4=v.5;v.2 > v.5 > v.1 > v.3 >v.4;",
# n=ngroup,Sigma=covariances,group_parameters=1,joint_parameters = 1)
# # display the results
# print(results2)
# # obtain the descriptives table
# summary(results2, ci = 0.95)
## ----ttest_ex11, eval=FALSE----------------------------------------------
# # load the bain package which includes the simulated sesamesim data set
# library(bain)
# # estimate the means of three repeated measures of number knowledge
# # the 1 denotes that these means have to be estimated
# within <- lm(cbind(prenumb,postnumb,funumb)~1, data=sesamesim)
# # take a look at the estimated means and their names
# coef(within)
# # note that the model specified in lm has three dependent variables.
# # Consequently, the estimates rendered by lm are collected in a "matrix".
# # Since bain needs a named vector containing the estimated means, the [1:3]
# # code is used to select the three means from a matrix and store them in a
# # vector.
# estimate <- coef(within)[1:3]
# # give names to the estimates in anov
# names(estimate) <- c("pre", "post", "fu")
# # compute the sample size
# ngroup <- nrow(sesamesim)
# # compute the covariance matrix of the three means
# covmatr <- list(vcov(within))
# # set a seed value
# set.seed(100)
# # test hypotheses with bain. Note that there is one group, with three
# # means therefore group_parameters=3.
# results <- bain(estimate,"pre = post = fu; pre < post < fu", n=ngroup,
# Sigma=covmatr, group_parameters=3, joint_parameters = 0)
# # display the results
# print(results)
# # obtain the descriptives table
# summary(results, ci = 0.95)
## ----ttest_ex12, eval=FALSE----------------------------------------------
# # load the bain package which includes the simulated sesamesim data set
# library(bain)
# # make a factor of the variable sex
# sesamesim$sex <- factor(sesamesim$sex)
# # estimate the means of prenumb, postnumb, and funumb for boys and girls
# # the -1 denotes that the means have to estimated
# bw <- lm(cbind(prenumb, postnumb, funumb)~sex-1, data=sesamesim)
# # take a look at the estimated means and their names
# coef(bw)
# # collect the estimated means in a vector
# est1 <-coef(bw)[1,1:3] # the three means for sex = 1
# est2 <-coef(bw)[2,1:3] # the three means for sex = 2
# estimate <- c(est1,est2)
# # give names to the estimates in anov
# names(estimate) <- c("pre1", "post1", "fu1","pre2", "post2", "fu2")
# # determine the sample size per group
# ngroup<-table(sesamesim$sex)
# # cov1 has to contain the covariance matrix of the three means in group 1.
# # cov2 has to contain the covariance matrix in group 2
# # typing vcov(bw) in the console pane highlights the structure of
# # the covariance matrix of all 3+3=6 means
# # it has to be dissected in to cov1 and cov2
# cov1 <- c(vcov(bw)[1,1],vcov(bw)[1,3],vcov(bw)[1,5],vcov(bw)[3,1],
# vcov(bw)[3,3],vcov(bw)[3,5],vcov(bw)[5,1],vcov(bw)[5,3],vcov(bw)[5,5])
# cov1 <- matrix(cov1,3,3)
# cov2 <- c(vcov(bw)[2,2],vcov(bw)[2,4],vcov(bw)[2,6],vcov(bw)[4,2],
# vcov(bw)[4,4],vcov(bw)[4,6],vcov(bw)[6,2],vcov(bw)[6,4],vcov(bw)[6,6])
# cov2 <- matrix(cov2,3,3)
# covariance<-list(cov1,cov2)
# # set a seed value
# set.seed(100)
# # test hypotheses with bain. Note that there are multiple groups
# # characterized by three means, therefore group_parameters=3. Note that there
# # are no additional parameters, therefore, joint_parameters=0.
# results <-bain(estimate, "pre1 - pre2 = post1 - post2 = fu1 -fu2;
# pre1 - pre2 > post1 - post2 > fu1 -fu2" , n=ngroup, Sigma=covariance,
# group_parameters=3, joint_parameters = 0)
# # display the results
# print(results)
# # obtain the descriptives table
# summary(results, ci = 0.95)
## ----ttest_ex13, eval=FALSE----------------------------------------------
# # load the bain package which includes the simulated sesamesim data set
# library(bain)
# # regression coefficients can only be mutually compared if the
# # corresponding predictors are measured on the same scale, therefore the
# # predictors are standardized
# sesamesim$age <- (sesamesim$age - mean(sesamesim$age))/sd(sesamesim$age)
# sesamesim$peabody <- (sesamesim$peabody - mean(sesamesim$peabody))/
# sd(sesamesim$peabody)
# sesamesim$prenumb <- (sesamesim$prenumb - mean(sesamesim$prenumb))/
# sd(sesamesim$prenumb)
# # estimate the logistic regression coefficients
# logreg <- glm(viewenc ~ age + peabody + prenumb, family=binomial,
# data=sesamesim)
# # take a look at the estimates and their names
# coef(logreg)
# # collect the estimated intercept and regression coefficients in a vector
# estimate <- coef(logreg)
# # give names to the estimates
# names(estimate) <- c("int", "age", "peab" ,"pre" )
# # compute the sample size. Note that, this is an analysis with ONE group
# ngroup <- nrow(sesamesim)
# # compute the covariance matrix of the intercept and regression coefficients
# covmatr <- list(vcov(logreg))
# # set a seed value
# set.seed(100)
# # test hypotheses with bain. Note that there is one group, with four
# # parameters (intercept plus three regression coefficients) therefore
# # group_parameters=4.
# results <- bain(estimate, "age = peab = pre; age > pre > peab", n=ngroup,
# Sigma=covmatr, group_parameters=4, joint_parameters = 0)
# # display the results
# print(results)
# # obtain the descriptives table
# summary(results, ci = 0.95)
## ----ttest_ex14, eval=FALSE----------------------------------------------
# # load the bain package which includes the simulated sesamesim data set
# library(bain)
# # load the numDeriv package which will be used to compute the covariance
# # matrix of the adjusted group coefficients and regression coefficient of age
# # for the boys and the girls # using the estimates obtained using the data for
# # the boys AND the girls.
# library(numDeriv)
# # make a factor of the variable sex
# sesamesim$sex <- factor(sesamesim$sex)
# # center the covariate age
# sesamesim$age <- sesamesim$age - mean(sesamesim$age)
# # determine sample size per sex group
# ngroup <- table(sesamesim$sex)
# # execute the logistic regression, -1 ensures that the coefficients
# # for boys and girl are estimated adjusted for the covariate age
# anal <- glm(viewenc ~ sex + age - 1, family=binomial, data=sesamesim)
# # take a look at the estimates and their names
# coef(anal)
# # collect the estimates obtained using the data of the boys AND the
# # girls in a vector. This vector contains first the group specific
# # parameters followed by the regression coefficient of the covariate.
# estimates <-coef(anal)
# # give names to the estimates
# names(estimates) <- c("boys", "girls", "age")
# # use numDeriv to compute the Hessian matrix and subsequently the
# # covariance matrix for each of the two (boys and girls) groups.
# # The vector f should contain the regression coefficient of the group
# # at hand and the regression coefficient of the covariate.
# #
# # the first group
# data <- subset(cbind(sesamesim$sex,sesamesim$age,sesamesim$viewenc),
# sesamesim$sex==1)
# f <- 1
# f[1] <- estimates[1] # the regression coefficient of boys
# f[2] <- estimates[3] # the regression coefficient of age
# #
# # within the for loop below the log likelihood of the logistic
# # regression model is computed using the data for the boys
# logist1 <- function(x){
# out <- 0
# for (i in 1:ngroup[1]){
# out <- out + data[i,3]*(x[1] + x[2]*data[i,2]) - log (1 +
# exp(x[1] + x[2]*data[i,2]))
# }
# return(out)
# }
# hes1 <- hessian(func=logist1, x=f)
# # multiply with -1 and invert to obtain the covariance matrix for the
# # first group
# cov1 <- -1 * solve(hes1)
# #
# # the second group
# data <- subset(cbind(sesamesim$sex,sesamesim$age,sesamesim$viewenc),
# sesamesim$sex==2)
# f[1] <- estimates[2] # the regression coefficient of girls
# f[2] <- estimates[3] # the regression coefficient of age
#
# # within the for loop below the log likelihood of the logistic
# # regression model is computed using the data for the girls
# logist2 <- function(x){
# out <- 0
# for (i in 1:ngroup[2]){
# out <- out + data[i,3]*(x[1] + x[2]*data[i,2]) - log (1 +
# exp(x[1] + x[2]*data[i,2]))
# }
# return(out)
# }
# hes2 <- hessian(func=logist2, x=f)
# # multiply with -1 and invert to obtain the covariance matrix
# cov2 <- -1 * solve(hes2)
# #
# #make a list of covariance matrices
# covariance<-list(cov1,cov2)
# #
# # set a seed value
# set.seed(100)
# # test hypotheses with bain. Note that there are multiple groups
# # characterized by one adjusted group coefficient,
# # therefore group_parameters=1. Note that there is one covariate,
# # therefore, joint_parameters=1.
# results <- bain(estimates, "boys < girls & age > 0", n=ngroup,
# Sigma=covariance, group_parameters=1, joint_parameters = 1)
# # display the results
# print(results)
# # obtain the descriptives table
# summary(results, ci = 0.95)
## ----ttest_ex15, eval=FALSE----------------------------------------------
# # load the bain package which includes the simulated sesamesim data set
# library(bain)
# # load the WRS2 package which renders the trimmed sample mean and
# # corresponding standard error
# library(WRS2)
# # make a factor of variable site
# sesamesim$site <- as.factor(sesamesim$site)
# # create a vector containing the sample sizes of each group
# ngroup <- table(sesamesim$site)
# # Compute the 20\% sample trimmed mean for each site
# estimates <- c(mean(sesamesim$postnumb[sesamesim$site == 1], tr = 0.2),
# mean(sesamesim$postnumb[sesamesim$site == 2], tr = 0.2),
# mean(sesamesim$postnumb[sesamesim$site == 3], tr = 0.2),
# mean(sesamesim$postnumb[sesamesim$site == 4], tr = 0.2),
# mean(sesamesim$postnumb[sesamesim$site == 5], tr = 0.2))
# # give names to the estimates
# names(estimates) <- c("s1", "s2", "s3","s4","s5")
# # display the estimates and their names
# print(estimates)
# # Compute the sample trimmed mean standard error for each site
# se <- c(trimse(sesamesim$postnumb[sesamesim$site == 1]),
# trimse(sesamesim$postnumb[sesamesim$site == 2]),
# trimse(sesamesim$postnumb[sesamesim$site == 3]),
# trimse(sesamesim$postnumb[sesamesim$site == 4]),
# trimse(sesamesim$postnumb[sesamesim$site == 5]))
# # Square the standard errors to obtain the variances of the sample
# # trimmed means
# var <- se^2
# # Store the variances in a list of matrices
# covlist <- list(matrix(var[1]),matrix(var[2]),
# matrix(var[3]),matrix(var[4]), matrix(var[5]))
# # set a seed value
# set.seed(100)
# # test hypotheses with bain
# results <- bain(estimates,"s1=s2=s3=s4=s5;s2>s5>s1>s3>s4",
# n=ngroup,Sigma=covlist,group_parameters=1,joint_parameters= 0)
# # display the results
# print(results)
# # obtain the descriptives table
# summary(results, ci = 0.95)
## ----ttest_ex16, eval=FALSE----------------------------------------------
# # load the bain package which includes the simulated sesamesim data set
# library(bain)
# # load the mice (multiple imputation of missing data), psych
# # (provides access to the describe function), and MASS libraries -
# # inspect the mice help file to obtain further information
# # - also surf to http://www.stefvanbuuren.nl/mi/MICE.html to obtain
# # further information and references for mice.
# library(mice)
# library(psych)
# library(MASS)
# sesamesim <- cbind(sesamesim$prenumb,sesamesim$postnumb,sesamesim$funumb,sesamesim$peabody)
# colnames(sesamesim) <- c("prenumb","postnumb","funumb","peabody")
# sesamesim <- as.data.frame(sesamesim)
# # this examples is based on the prenumb, postnumb, funumb and peabody
# # variables in the sesamesim data set. First of all, missing data are
# # created in these four variables.
# #
# set.seed(1)
# pmis1<-1
# pmis2<-1
# pmis3<-1
# #
# for (i in 1:240){
# pmis1[i] <- .80
# pmis2[i]<- .80
# pmis3[i]<- .80
# #
# uni<-runif(1)
# if (pmis1[i] < uni) {
# sesamesim$funumb[i]<-NaN
# }
# uni<-runif(1)
# if (pmis2[i] < uni) {
# sesamesim$prenumb[i]<-NaN
# sesamesim$postnumb[i]<-NaN
# }
# uni<-runif(1)
# if (pmis3[i] < uni) {
# sesamesim$peabody[i]<-NaN
# }
# }
# # print data summaries - note that due to missing valus the n per variable is smaller than 240
# print(describe(sesamesim))
# # use mice to create 1000 imputed data matrices. Note that, the approach used below
# # is only one manner in which mice can be instructed. Many other options are available.
# M <- 1000
# out <- mice(data = sesamesim, m = M, seed=999, meth=c("norm","norm","norm","norm"), diagnostics = FALSE, printFlag = FALSE)
# # create matrices in which 1000 vectors with estimates can be stored and in which a covariance matrix can be stored
# mulest <- matrix(0,nrow=1000,ncol=2)
# covwithin <- matrix(0,nrow=2,ncol=2)
# # execute 1000 multiple regressions using the imputed data matrices and store the estimates
# # of only the regression coefficients of funumb on prenumb and postnumband and the average
# # of the 1000 covariance matrices.
# # See Hoijtink, Gu, Mulder, and Rosseel (2018) for an explanation of the latter.
# for(i in 1:M) {
# mulres <- lm(funumb~prenumb+postnumb,complete(out,i))
# mulest[i,]<-coef(mulres)[2:3]
# covwithin<-covwithin + 1/M * vcov(mulres)[2:3,2:3]
# }
# # Compute the average of the estimates and assign names, the between and total covariance matrix.
# # See Hoijtink, Gu, Mulder, and Rosseel (2018) for an explanation.
# estimates <- colMeans(mulest)
# names(estimates) <- c("prenumb", "postnumb")
# covbetween <- cov(mulest)
# covariance <- covwithin + (1+1/M)*covbetween
# # determine the sample size
# samp <- nrow(sesamesim)
# # compute the effective sample size
# # See Hoijtink, Gu, Mulder, and Rosseel (2018) for an explanation.
# nucom<-samp-length(estimates)
# lam <- (1+1/M)*(1/length(estimates))* tr(covbetween %*% ginv(covariance))
# nuold<-(M-1)/(lam^2)
# nuobs<-(nucom+1)/(nucom+3)*nucom*(1-lam)
# nu<- nuold*nuobs/(nuold+nuobs)
# fracmis <- (nu+1)/(nu+3)*lam + 2/(nu+3)
# neff<-samp-samp*fracmis
# covariance<-list(covariance)
# # set the seed
# set.seed(100)
# # test hypotheses with bain
# results <- bain(estimates,"prenumb=postnumb=0",n=neff,Sigma=covariance,group_parameters=2,joint_parameters = 0)
# # display the results
# print(results)
# # obtain the descriptives table
# summary(results, ci = 0.95)
## ----ttest_ex17, eval=FALSE----------------------------------------------
# # load the bain package
# library(bain)
# # load the lavaan package - look at the lavaan help file to obtain
# # further information - also surf to # lavaan.ugent.be to obtain
# # further information and references for lavaan - this example uses the
# # HolzingerSwineford1939 data set which is included with lavaan.
# library(lavaan)
# # Specify a latent regression model
# model <- 'visual =~ x1 + x2 + x3
# textual =~ x4 + x5 + x6
# speed =~ x7 + x8 + x9
# speed ~ textual + visual'
# # Estimate the parameters of the latent regression model with lavaan
# fit<-sem(model,data=HolzingerSwineford1939,std.lv = TRUE)
# # determine the sample size
# ngroup<-nobs(fit)
# # collect the "standardized" estimates of the latent regression
# # coefficients in a vector, typing standardizedSolution(fit)
# # in the console pane shows that the estimates can be
# # found in the fourth column of rows 10 and 11.
# estimate<-standardizedSolution(fit)[10:11,4]
# # assign names to the estimates
# names(estimate) <- c("textual","visual")
# # determine the covariance matrix of the estimates typing
# # lavInspect(fit, "vcov.std.all") in the console pane shows that the
# # estimates can be found in the rows 10 and 11 crossed with
# # columns 10 and 11
# covariance<-list(lavInspect(fit, "vcov.std.all")[10:11,10:11])
# # set a seed value
# set.seed(100)
# # test hypotheses with bain
# results <- bain(estimate,"visual=textual=0; visual > textual >
# 0",n=ngroup,Sigma=covariance,group_parameters=2,joint_parameters = 0)
# # display the results
# print(results)
# # obtain the descriptives table
# summary(results, ci = 0.95)
|
/data/genthat_extracted_code/bain/vignettes/Introduction_to_bain.R
|
no_license
|
surayaaramli/typeRrh
|
R
| false | false | 29,011 |
r
|
## ----setup, include = FALSE----------------------------------------------
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
## ----ttest_ex1, eval=FALSE-----------------------------------------------
# # load the bain package which includes the simulated sesamesim data set
# library(bain)
# # collect the data for the boys in the vector x and for the girls in the
# # vector y
# x<-sesamesim$postnumb[which(sesamesim$sex==1)]
# y<-sesamesim$postnumb[which(sesamesim$sex==2)]
# # execute student's t-test
# ttest <- t_test(x,y,paired = FALSE, var.equal = TRUE)
# # Check the names of the estimates
# coef(ttest)
# # set a seed value
# set.seed(100)
# # test hypotheses with bain
# results <- bain(ttest, "x = y; x > y; x < y")
# # display the results
# results
# # obtain the descriptives table
# summary(results, ci = 0.95)
## ----ttest_ex2, eval=FALSE-----------------------------------------------
# # load the bain package which includes the simulated sesamesim data set
# library(bain)
# # collect the data for the boys in the vector x and for the girs in the
# # vector y
# x<-sesamesim$postnumb[which(sesamesim$sex==1)]
# y<-sesamesim$postnumb[which(sesamesim$sex==2)]
# # execute student's t-test
# ttest <- t_test(x,y,paired = FALSE, var.equal = FALSE)
# # Check the names of the coefficients
# coef(ttest)
# # set a seed value
# set.seed(100)
# # test hypotheses with bain
# results <- bain(ttest, "x = y; x > y; x < y")
# # display the results
# print(results)
# # obtain the descriptives table
# summary(results, ci = 0.95)
## ----ttest_ex3, eval=FALSE-----------------------------------------------
# # load the bain package which includes the simulated sesamesim data set
# library(bain)
# # compare the pre with the post measurements
# ttest <- t_test(sesamesim$prenumb,sesamesim$postnumb,paired = TRUE)
# # Check name of the coefficient
# coef(ttest)
# # set a seed value
# set.seed(100)
# # test hypotheses with bain
# results <- bain(ttest, "difference=0; difference>0; difference<0")
# # display the results
# print(results)
# # obtain the descriptives table
# summary(results, ci = 0.95)
## ----ttest_ex4, eval=FALSE-----------------------------------------------
# # load the bain package which includes the simulated sesamesim data se
# library(bain)
# # compare post measurements with the reference value 30
# ttest <- t_test(sesamesim$postnumb)
# # Check name of estimate
# coef(ttest)
# # set a seed value
# set.seed(100)
# # test hypotheses with bain versus the reference value 30
# results <- bain(ttest, "x=30; x>30; x<30")
# # display the results
# print(results)
# # obtain the descriptives table
# summary(results, ci = 0.95)
## ----ttest_ex5, eval=FALSE-----------------------------------------------
# # load the bain package which includes the simulated sesamesim data set
# library(bain)
# # collect the data for the boys in the vector x and for the girs in the
# # vector y
# x<-sesamesim$postnumb[which(sesamesim$sex==1)]
# y<-sesamesim$postnumb[which(sesamesim$sex==2)]
# # execute student's t-test
# ttest <- t_test(x,y,paired = FALSE, var.equal = TRUE)
# # Check the names of the estimates
# coef(ttest)
# # compute the pooled within standard deviation using the variance of x
# # (ttest$v[1]) and y (ttest$v[2])
# pwsd <- sqrt(((length(x) -1) * ttest$v[1] + (length(y)-1) * ttest$v[2])/
# ((length(x) -1) + (length(y) -1)))
# # print pwsd in order to be able to include it in the hypothesis. Its value
# # is 12.60
# print(pwsd)
# # set a seed value
# set.seed(100)
# # test hypotheses (the means of boy and girl differ less than .2 * pwsd =
# # 2.52 VERSUS the means differ more than .2 * pwsd = 2.52) with bain
# # note that, .2 is a value for Cohen's d reflecting a "small" effect, that
# # is, the means differ less or more than .2 pwsd.
# results <- bain(ttest, "x - y > -2.52 & x - y < 2.52")
# # display the results
# print(results)
# # obtain the descriptives table
# summary(results, ci = 0.95)
## ----ttest_ex6, eval=FALSE-----------------------------------------------
# # load the bain package which includes the simulated sesamesim data set
# library(bain)
# # make a factor of variable site
# sesamesim$site <- as.factor(sesamesim$site)
# # execute an analysis of variance using lm() which, due to the -1, returns
# # estimates of the means per group
# anov <- lm(postnumb~site-1,sesamesim)
# # take a look at the estimated means and their names
# coef(anov)
# # set a seed value
# set.seed(100)
# # test hypotheses with bain
# results <- bain(anov, "site1=site2=site3=site4=site5; site2>site5>site1>
# site3>site4")
# # display the results
# print(results)
# # obtain the descriptives table
# summary(results, ci = 0.95)
## ----ttest_ex7, eval=FALSE-----------------------------------------------
# # load the bain package which includes the simulated sesamesim data se
# library(bain)
# # make a factor of variable site
# sesamesim$site <- as.factor(sesamesim$site)
# # Center the covariate. If centered the coef() command below displays the
# # adjusted means. If not centered the intercepts are displayed.
# sesamesim$prenumb <- sesamesim$prenumb - mean(sesamesim$prenumb)
# # execute an analysis of covariance using lm() which, due to the -1, returns
# # estimates of the adjusted means per group
# ancov <- lm(postnumb~site+prenumb-1,sesamesim)
# # take a look at the estimated adjusted means, the regression coefficient
# # of the covariate and their names
# coef(ancov)
# # set a seed value
# set.seed(100)
# # test hypotheses with bain
# results <- bain(ancov, "site1=site2=site3=site4=site5;
# site2>site5>site1>site3>site4")
# # display the results
# print(results)
# # obtain the descriptives table
# summary(results, ci = 0.95)
## ----ttest_ex8, eval=FALSE-----------------------------------------------
# # load the bain package which includes the simulated sesamesim data set
# library(bain)
# # execute a multiple regression using lm()
# regr <- lm(postnumb ~ age + peabody + prenumb,sesamesim)
# # take a look at the estimated regression coefficients and their names
# coef(regr)
# # set a seed value
# set.seed(100)
# # test hypotheses with bain. Note that standardized = FALSE denotes that the
# # hypotheses are in terms of unstandardized regression coefficients
# results<-bain(regr, "age = 0 & peab=0 & pre=0 ; age > 0 & peab > 0 & pre > 0"
# , standardize = FALSE)
# # display the results
# print(results)
# # obtain the descriptives table
# summary(results, ci = 0.95)
# # Since it is only meaningful to compare regression coefficients if they are
# # measured on the same scale, bain can also evaluate standardized regression
# # coefficients (based on the seBeta function by Jeff Jones and Niels Waller):
# # set a seed value
# set.seed(100)
# # test hypotheses with bain. Note that standardized = TRUE denotes that the
# # hypotheses are in terms of standardized regression coefficients
# results<-bain(regr, "age = peab = pre ; pre > age > peab",standardize = TRUE)
# # display the results
# print(results)
# # obtain the descriptives table
# summary(results, ci = 0.95)
## ----ttest_ex9, eval=FALSE-----------------------------------------------
# # load the bain package which includes the simulated sesamesim data se
# library(bain)
# # make a factor of variable site
# sesamesim$site <- as.factor(sesamesim$site)
# # execute an analysis of variance using lm() which, due to the -1, returns
# # estimates of the means per group
# anov <- lm(postnumb~site-1,sesamesim)
# # take a look at the estimated means and their names
# coef(anov)
# # collect the estimates means in a vector
# estimate <- coef(anov)
# # give names to the estimates in anov
# names(estimate) <- c("site1", "site2", "site3","site4","site5")
# # create a vector containing the sample sizes of each group
# ngroup <- table(sesamesim$site)
# # compute for each group the covariance matrix of the parameters
# # of that group and collect these in a list
# # for the ANOVA this is simply a list containing for each group the variance
# # of the mean note that, the within group variance as estimated using lm is
# # used to compute the variance of each of the means! See, Hoijtink, Gu, and
# # Mulder (2018) for further elaborations.
# var <- summary(anov)$sigma**2
# cov1 <- matrix(var/ngroup[1], nrow=1, ncol=1)
# cov2 <- matrix(var/ngroup[2], nrow=1, ncol=1)
# cov3 <- matrix(var/ngroup[3], nrow=1, ncol=1)
# cov4 <- matrix(var/ngroup[4], nrow=1, ncol=1)
# cov5 <- matrix(var/ngroup[5], nrow=1, ncol=1)
# covlist <- list(cov1, cov2, cov3, cov4,cov5)
# # set a seed value
# set.seed(100)
# # test hypotheses with bain. Note that there are multiple groups
# # characterized by one mean, therefore group_parameters=0. Note that are no
# # joint parameters, therefore, joint_parameters=0.
# results <- bain(estimate,
# "site1=site2=site3=site4=site5; site2>site5>site1>site3>site4",
# n=ngroup,Sigma=covlist,group_parameters=1,joint_parameters = 0)
# # display the results
# print(results)
# # obtain the descriptives table
# summary(results, ci = 0.95)
## ----ttest_ex10, eval=FALSE----------------------------------------------
# # load the bain package which includes the simulated sesamesim data se
# library(bain)
# # make a factor of variable site
# sesamesim$site <- as.factor(sesamesim$site)
# # center the covariate. If centered the coef() command below displays the
# # adjusted means. If not centered the intercepts are displayed.
# sesamesim$prenumb <- sesamesim$prenumb - mean(sesamesim$prenumb)
# # execute an analysis of covariance using lm() which, due to the -1, returns
# # estimates of the adjusted means per group
# ancov2 <- lm(postnumb~site+prenumb-1,sesamesim)
# # take a look at the estimated adjusted means and their names
# coef(ancov2)
# # collect the estimates of the adjusted means and regression coefficient of
# # the covariate in a vector (the vector has to contain first the
# # adjusted means and next the regression coefficients of the covariates)
# estimates <- coef(ancov2)
# # assign names to the estimates
# names(estimates)<- c("v.1", "v.2", "v.3", "v.4","v.5", "pre")
# # compute the sample size per group
# ngroup <- table(sesamesim$site)
# # compute for each group the covariance matrix of the parameters of that
# # group and collect these in a list note that, the residual variance as
# # estimated using lm is used to compute these covariance matrices
# var <- (summary(ancov2)$sigma)**2
# # below, for each group, the covariance matrix of the adjusted mean and
# # covariate is computed
# # see Hoijtink, Gu, and Mulder (2018) for further explanation and elaboration
# cat1 <- subset(cbind(sesamesim$site,sesamesim$prenumb), sesamesim$site == 1)
# cat1[,1] <- 1
# cat1 <- as.matrix(cat1)
# cov1 <- var * solve(t(cat1) %*% cat1)
# #
# cat2 <- subset(cbind(sesamesim$site,sesamesim$prenumb), sesamesim$site == 2)
# cat2[,1] <- 1
# cat2 <- as.matrix(cat2)
# cov2 <- var * solve(t(cat2) %*% cat2)
# #
# cat3 <- subset(cbind(sesamesim$site,sesamesim$prenumb), sesamesim$site == 3)
# cat3[,1] <- 1
# cat3 <- as.matrix(cat3)
# cov3 <- var * solve(t(cat3) %*% cat3)
# #
# cat4 <- subset(cbind(sesamesim$site,sesamesim$prenumb), sesamesim$site == 4)
# cat4[,1] <- 1
# cat4 <- as.matrix(cat4)
# cov4 <- var * solve(t(cat4) %*% cat4)
# #
# cat5 <- subset(cbind(sesamesim$site,sesamesim$prenumb), sesamesim$site == 5)
# cat5[,1] <- 1
# cat5 <- as.matrix(cat5)
# cov5 <- var * solve(t(cat5) %*% cat5)
# #
# covariances <- list(cov1, cov2, cov3, cov4,cov5)
# # set a seed value
# set.seed(100)
# # test hypotheses with bain. Note that there are multiple groups
# # characterized by one adjusted mean, therefore group_parameters=1 Note that
# # there is one covariate, therefore, joint_parameters=1.
# results2<-bain(estimates,"v.1=v.2=v.3=v.4=v.5;v.2 > v.5 > v.1 > v.3 >v.4;",
# n=ngroup,Sigma=covariances,group_parameters=1,joint_parameters = 1)
# # display the results
# print(results2)
# # obtain the descriptives table
# summary(results2, ci = 0.95)
## ----ttest_ex11, eval=FALSE----------------------------------------------
# # load the bain package which includes the simulated sesamesim data set
# library(bain)
# # estimate the means of three repeated measures of number knowledge
# # the 1 denotes that these means have to be estimated
# within <- lm(cbind(prenumb,postnumb,funumb)~1, data=sesamesim)
# # take a look at the estimated means and their names
# coef(within)
# # note that the model specified in lm has three dependent variables.
# # Consequently, the estimates rendered by lm are collected in a "matrix".
# # Since bain needs a named vector containing the estimated means, the [1:3]
# # code is used to select the three means from a matrix and store them in a
# # vector.
# estimate <- coef(within)[1:3]
# # give names to the estimates in anov
# names(estimate) <- c("pre", "post", "fu")
# # compute the sample size
# ngroup <- nrow(sesamesim)
# # compute the covariance matrix of the three means
# covmatr <- list(vcov(within))
# # set a seed value
# set.seed(100)
# # test hypotheses with bain. Note that there is one group, with three
# # means therefore group_parameters=3.
# results <- bain(estimate,"pre = post = fu; pre < post < fu", n=ngroup,
# Sigma=covmatr, group_parameters=3, joint_parameters = 0)
# # display the results
# print(results)
# # obtain the descriptives table
# summary(results, ci = 0.95)
## ----ttest_ex12, eval=FALSE----------------------------------------------
# # load the bain package which includes the simulated sesamesim data set
# library(bain)
# # make a factor of the variable sex
# sesamesim$sex <- factor(sesamesim$sex)
# # estimate the means of prenumb, postnumb, and funumb for boys and girls
# # the -1 denotes that the means have to estimated
# bw <- lm(cbind(prenumb, postnumb, funumb)~sex-1, data=sesamesim)
# # take a look at the estimated means and their names
# coef(bw)
# # collect the estimated means in a vector
# est1 <-coef(bw)[1,1:3] # the three means for sex = 1
# est2 <-coef(bw)[2,1:3] # the three means for sex = 2
# estimate <- c(est1,est2)
# # give names to the estimates in anov
# names(estimate) <- c("pre1", "post1", "fu1","pre2", "post2", "fu2")
# # determine the sample size per group
# ngroup<-table(sesamesim$sex)
# # cov1 has to contain the covariance matrix of the three means in group 1.
# # cov2 has to contain the covariance matrix in group 2
# # typing vcov(bw) in the console pane highlights the structure of
# # the covariance matrix of all 3+3=6 means
# # it has to be dissected in to cov1 and cov2
# cov1 <- c(vcov(bw)[1,1],vcov(bw)[1,3],vcov(bw)[1,5],vcov(bw)[3,1],
# vcov(bw)[3,3],vcov(bw)[3,5],vcov(bw)[5,1],vcov(bw)[5,3],vcov(bw)[5,5])
# cov1 <- matrix(cov1,3,3)
# cov2 <- c(vcov(bw)[2,2],vcov(bw)[2,4],vcov(bw)[2,6],vcov(bw)[4,2],
# vcov(bw)[4,4],vcov(bw)[4,6],vcov(bw)[6,2],vcov(bw)[6,4],vcov(bw)[6,6])
# cov2 <- matrix(cov2,3,3)
# covariance<-list(cov1,cov2)
# # set a seed value
# set.seed(100)
# # test hypotheses with bain. Note that there are multiple groups
# # characterized by three means, therefore group_parameters=3. Note that there
# # are no additional parameters, therefore, joint_parameters=0.
# results <-bain(estimate, "pre1 - pre2 = post1 - post2 = fu1 -fu2;
# pre1 - pre2 > post1 - post2 > fu1 -fu2" , n=ngroup, Sigma=covariance,
# group_parameters=3, joint_parameters = 0)
# # display the results
# print(results)
# # obtain the descriptives table
# summary(results, ci = 0.95)
## ----ttest_ex13, eval=FALSE----------------------------------------------
# # load the bain package which includes the simulated sesamesim data set
# library(bain)
# # regression coefficients can only be mutually compared if the
# # corresponding predictors are measured on the same scale, therefore the
# # predictors are standardized
# sesamesim$age <- (sesamesim$age - mean(sesamesim$age))/sd(sesamesim$age)
# sesamesim$peabody <- (sesamesim$peabody - mean(sesamesim$peabody))/
# sd(sesamesim$peabody)
# sesamesim$prenumb <- (sesamesim$prenumb - mean(sesamesim$prenumb))/
# sd(sesamesim$prenumb)
# # estimate the logistic regression coefficients
# logreg <- glm(viewenc ~ age + peabody + prenumb, family=binomial,
# data=sesamesim)
# # take a look at the estimates and their names
# coef(logreg)
# # collect the estimated intercept and regression coefficients in a vector
# estimate <- coef(logreg)
# # give names to the estimates
# names(estimate) <- c("int", "age", "peab" ,"pre" )
# # compute the sample size. Note that, this is an analysis with ONE group
# ngroup <- nrow(sesamesim)
# # compute the covariance matrix of the intercept and regression coefficients
# covmatr <- list(vcov(logreg))
# # set a seed value
# set.seed(100)
# # test hypotheses with bain. Note that there is one group, with four
# # parameters (intercept plus three regression coefficients) therefore
# # group_parameters=4.
# results <- bain(estimate, "age = peab = pre; age > pre > peab", n=ngroup,
# Sigma=covmatr, group_parameters=4, joint_parameters = 0)
# # display the results
# print(results)
# # obtain the descriptives table
# summary(results, ci = 0.95)
## ----ttest_ex14, eval=FALSE----------------------------------------------
# # load the bain package which includes the simulated sesamesim data set
# library(bain)
# # load the numDeriv package which will be used to compute the covariance
# # matrix of the adjusted group coefficients and regression coefficient of age
# # for the boys and the girls # using the estimates obtained using the data for
# # the boys AND the girls.
# library(numDeriv)
# # make a factor of the variable sex
# sesamesim$sex <- factor(sesamesim$sex)
# # center the covariate age
# sesamesim$age <- sesamesim$age - mean(sesamesim$age)
# # determine sample size per sex group
# ngroup <- table(sesamesim$sex)
# # execute the logistic regression, -1 ensures that the coefficients
# # for boys and girl are estimated adjusted for the covariate age
# anal <- glm(viewenc ~ sex + age - 1, family=binomial, data=sesamesim)
# # take a look at the estimates and their names
# coef(anal)
# # collect the estimates obtained using the data of the boys AND the
# # girls in a vector. This vector contains first the group specific
# # parameters followed by the regression coefficient of the covariate.
# estimates <-coef(anal)
# # give names to the estimates
# names(estimates) <- c("boys", "girls", "age")
# # use numDeriv to compute the Hessian matrix and subsequently the
# # covariance matrix for each of the two (boys and girls) groups.
# # The vector f should contain the regression coefficient of the group
# # at hand and the regression coefficient of the covariate.
# #
# # the first group
# data <- subset(cbind(sesamesim$sex,sesamesim$age,sesamesim$viewenc),
# sesamesim$sex==1)
# f <- 1
# f[1] <- estimates[1] # the regression coefficient of boys
# f[2] <- estimates[3] # the regression coefficient of age
# #
# # within the for loop below the log likelihood of the logistic
# # regression model is computed using the data for the boys
# logist1 <- function(x){
# out <- 0
# for (i in 1:ngroup[1]){
# out <- out + data[i,3]*(x[1] + x[2]*data[i,2]) - log (1 +
# exp(x[1] + x[2]*data[i,2]))
# }
# return(out)
# }
# hes1 <- hessian(func=logist1, x=f)
# # multiply with -1 and invert to obtain the covariance matrix for the
# # first group
# cov1 <- -1 * solve(hes1)
# #
# # the second group
# data <- subset(cbind(sesamesim$sex,sesamesim$age,sesamesim$viewenc),
# sesamesim$sex==2)
# f[1] <- estimates[2] # the regression coefficient of girls
# f[2] <- estimates[3] # the regression coefficient of age
#
# # within the for loop below the log likelihood of the logistic
# # regression model is computed using the data for the girls
# logist2 <- function(x){
# out <- 0
# for (i in 1:ngroup[2]){
# out <- out + data[i,3]*(x[1] + x[2]*data[i,2]) - log (1 +
# exp(x[1] + x[2]*data[i,2]))
# }
# return(out)
# }
# hes2 <- hessian(func=logist2, x=f)
# # multiply with -1 and invert to obtain the covariance matrix
# cov2 <- -1 * solve(hes2)
# #
# #make a list of covariance matrices
# covariance<-list(cov1,cov2)
# #
# # set a seed value
# set.seed(100)
# # test hypotheses with bain. Note that there are multiple groups
# # characterized by one adjusted group coefficient,
# # therefore group_parameters=1. Note that there is one covariate,
# # therefore, joint_parameters=1.
# results <- bain(estimates, "boys < girls & age > 0", n=ngroup,
# Sigma=covariance, group_parameters=1, joint_parameters = 1)
# # display the results
# print(results)
# # obtain the descriptives table
# summary(results, ci = 0.95)
## ----ttest_ex15, eval=FALSE----------------------------------------------
# # load the bain package which includes the simulated sesamesim data set
# library(bain)
# # load the WRS2 package which renders the trimmed sample mean and
# # corresponding standard error
# library(WRS2)
# # make a factor of variable site
# sesamesim$site <- as.factor(sesamesim$site)
# # create a vector containing the sample sizes of each group
# ngroup <- table(sesamesim$site)
# # Compute the 20\% sample trimmed mean for each site
# estimates <- c(mean(sesamesim$postnumb[sesamesim$site == 1], tr = 0.2),
# mean(sesamesim$postnumb[sesamesim$site == 2], tr = 0.2),
# mean(sesamesim$postnumb[sesamesim$site == 3], tr = 0.2),
# mean(sesamesim$postnumb[sesamesim$site == 4], tr = 0.2),
# mean(sesamesim$postnumb[sesamesim$site == 5], tr = 0.2))
# # give names to the estimates
# names(estimates) <- c("s1", "s2", "s3","s4","s5")
# # display the estimates and their names
# print(estimates)
# # Compute the sample trimmed mean standard error for each site
# se <- c(trimse(sesamesim$postnumb[sesamesim$site == 1]),
# trimse(sesamesim$postnumb[sesamesim$site == 2]),
# trimse(sesamesim$postnumb[sesamesim$site == 3]),
# trimse(sesamesim$postnumb[sesamesim$site == 4]),
# trimse(sesamesim$postnumb[sesamesim$site == 5]))
# # Square the standard errors to obtain the variances of the sample
# # trimmed means
# var <- se^2
# # Store the variances in a list of matrices
# covlist <- list(matrix(var[1]),matrix(var[2]),
# matrix(var[3]),matrix(var[4]), matrix(var[5]))
# # set a seed value
# set.seed(100)
# # test hypotheses with bain
# results <- bain(estimates,"s1=s2=s3=s4=s5;s2>s5>s1>s3>s4",
# n=ngroup,Sigma=covlist,group_parameters=1,joint_parameters= 0)
# # display the results
# print(results)
# # obtain the descriptives table
# summary(results, ci = 0.95)
## ----ttest_ex16, eval=FALSE----------------------------------------------
# # load the bain package which includes the simulated sesamesim data set
# library(bain)
# # load the mice (multiple imputation of missing data), psych
# # (provides access to the describe function), and MASS libraries -
# # inspect the mice help file to obtain further information
# # - also surf to http://www.stefvanbuuren.nl/mi/MICE.html to obtain
# # further information and references for mice.
# library(mice)
# library(psych)
# library(MASS)
# sesamesim <- cbind(sesamesim$prenumb,sesamesim$postnumb,sesamesim$funumb,sesamesim$peabody)
# colnames(sesamesim) <- c("prenumb","postnumb","funumb","peabody")
# sesamesim <- as.data.frame(sesamesim)
# # this examples is based on the prenumb, postnumb, funumb and peabody
# # variables in the sesamesim data set. First of all, missing data are
# # created in these four variables.
# #
# set.seed(1)
# pmis1<-1
# pmis2<-1
# pmis3<-1
# #
# for (i in 1:240){
# pmis1[i] <- .80
# pmis2[i]<- .80
# pmis3[i]<- .80
# #
# uni<-runif(1)
# if (pmis1[i] < uni) {
# sesamesim$funumb[i]<-NaN
# }
# uni<-runif(1)
# if (pmis2[i] < uni) {
# sesamesim$prenumb[i]<-NaN
# sesamesim$postnumb[i]<-NaN
# }
# uni<-runif(1)
# if (pmis3[i] < uni) {
# sesamesim$peabody[i]<-NaN
# }
# }
# # print data summaries - note that due to missing valus the n per variable is smaller than 240
# print(describe(sesamesim))
# # use mice to create 1000 imputed data matrices. Note that, the approach used below
# # is only one manner in which mice can be instructed. Many other options are available.
# M <- 1000
# out <- mice(data = sesamesim, m = M, seed=999, meth=c("norm","norm","norm","norm"), diagnostics = FALSE, printFlag = FALSE)
# # create matrices in which 1000 vectors with estimates can be stored and in which a covariance matrix can be stored
# mulest <- matrix(0,nrow=1000,ncol=2)
# covwithin <- matrix(0,nrow=2,ncol=2)
# # execute 1000 multiple regressions using the imputed data matrices and store the estimates
# # of only the regression coefficients of funumb on prenumb and postnumband and the average
# # of the 1000 covariance matrices.
# # See Hoijtink, Gu, Mulder, and Rosseel (2018) for an explanation of the latter.
# for(i in 1:M) {
# mulres <- lm(funumb~prenumb+postnumb,complete(out,i))
# mulest[i,]<-coef(mulres)[2:3]
# covwithin<-covwithin + 1/M * vcov(mulres)[2:3,2:3]
# }
# # Compute the average of the estimates and assign names, the between and total covariance matrix.
# # See Hoijtink, Gu, Mulder, and Rosseel (2018) for an explanation.
# estimates <- colMeans(mulest)
# names(estimates) <- c("prenumb", "postnumb")
# covbetween <- cov(mulest)
# covariance <- covwithin + (1+1/M)*covbetween
# # determine the sample size
# samp <- nrow(sesamesim)
# # compute the effective sample size
# # See Hoijtink, Gu, Mulder, and Rosseel (2018) for an explanation.
# nucom<-samp-length(estimates)
# lam <- (1+1/M)*(1/length(estimates))* tr(covbetween %*% ginv(covariance))
# nuold<-(M-1)/(lam^2)
# nuobs<-(nucom+1)/(nucom+3)*nucom*(1-lam)
# nu<- nuold*nuobs/(nuold+nuobs)
# fracmis <- (nu+1)/(nu+3)*lam + 2/(nu+3)
# neff<-samp-samp*fracmis
# covariance<-list(covariance)
# # set the seed
# set.seed(100)
# # test hypotheses with bain
# results <- bain(estimates,"prenumb=postnumb=0",n=neff,Sigma=covariance,group_parameters=2,joint_parameters = 0)
# # display the results
# print(results)
# # obtain the descriptives table
# summary(results, ci = 0.95)
## ----ttest_ex17, eval=FALSE----------------------------------------------
# # load the bain package
# library(bain)
# # load the lavaan package - look at the lavaan help file to obtain
# # further information - also surf to # lavaan.ugent.be to obtain
# # further information and references for lavaan - this example uses the
# # HolzingerSwineford1939 data set which is included with lavaan.
# library(lavaan)
# # Specify a latent regression model
# model <- 'visual =~ x1 + x2 + x3
# textual =~ x4 + x5 + x6
# speed =~ x7 + x8 + x9
# speed ~ textual + visual'
# # Estimate the parameters of the latent regression model with lavaan
# fit<-sem(model,data=HolzingerSwineford1939,std.lv = TRUE)
# # determine the sample size
# ngroup<-nobs(fit)
# # collect the "standardized" estimates of the latent regression
# # coefficients in a vector, typing standardizedSolution(fit)
# # in the console pane shows that the estimates can be
# # found in the fourth column of rows 10 and 11.
# estimate<-standardizedSolution(fit)[10:11,4]
# # assign names to the estimates
# names(estimate) <- c("textual","visual")
# # determine the covariance matrix of the estimates typing
# # lavInspect(fit, "vcov.std.all") in the console pane shows that the
# # estimates can be found in the rows 10 and 11 crossed with
# # columns 10 and 11
# covariance<-list(lavInspect(fit, "vcov.std.all")[10:11,10:11])
# # set a seed value
# set.seed(100)
# # test hypotheses with bain
# results <- bain(estimate,"visual=textual=0; visual > textual >
# 0",n=ngroup,Sigma=covariance,group_parameters=2,joint_parameters = 0)
# # display the results
# print(results)
# # obtain the descriptives table
# summary(results, ci = 0.95)
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/basis-funs.R
\name{basis}
\alias{basis}
\title{Basis expansions for smooths}
\usage{
basis(smooth, data, knots = NULL, constraints = FALSE, ...)
}
\arguments{
\item{smooth}{a smooth specification, the result of a call to one of
\code{\link[mgcv:s]{mgcv::s()}}., \code{\link[mgcv:te]{mgcv::te()}}, \code{\link[mgcv:ti]{mgcv::ti()}}, or \code{\link[mgcv:t2]{mgcv::t2()}}.}
\item{data}{a data frame containing the variables used in \code{smooth}.}
\item{knots}{a list or data frame with named components containing
knots locations. Names must match the covariates for which the basis
is required. See \code{\link[mgcv:smoothCon]{mgcv::smoothCon()}}.}
\item{constraints}{logical; should identifiability constraints be applied to
the smooth basis. See argument \code{absorb.cons} in \code{\link[mgcv:smoothCon]{mgcv::smoothCon()}}.}
\item{...}{other arguments passed to \code{\link[mgcv:smoothCon]{mgcv::smoothCon()}}.}
}
\value{
A tibble.
}
\description{
Creates a basis expansion from a definition of a smoother using the syntax
of \emph{mgcv}'s smooths via \code{\link[mgcv:s]{mgcv::s()}}., \code{\link[mgcv:te]{mgcv::te()}}, \code{\link[mgcv:ti]{mgcv::ti()}}, and
\code{\link[mgcv:t2]{mgcv::t2()}}.
}
\examples{
load_mgcv()
\dontshow{set.seed(42)}
df <- gamSim(4, n = 400, verbose = FALSE)
bf <- basis(s(x0), data = df)
bf <- basis(s(x2, by = fac, bs = 'bs'), data = df, constraints = TRUE)
}
\author{
Gavin L. Simpson
}
|
/man/basis.Rd
|
permissive
|
romainfrancois/gratia
|
R
| false | true | 1,503 |
rd
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/basis-funs.R
\name{basis}
\alias{basis}
\title{Basis expansions for smooths}
\usage{
basis(smooth, data, knots = NULL, constraints = FALSE, ...)
}
\arguments{
\item{smooth}{a smooth specification, the result of a call to one of
\code{\link[mgcv:s]{mgcv::s()}}., \code{\link[mgcv:te]{mgcv::te()}}, \code{\link[mgcv:ti]{mgcv::ti()}}, or \code{\link[mgcv:t2]{mgcv::t2()}}.}
\item{data}{a data frame containing the variables used in \code{smooth}.}
\item{knots}{a list or data frame with named components containing
knots locations. Names must match the covariates for which the basis
is required. See \code{\link[mgcv:smoothCon]{mgcv::smoothCon()}}.}
\item{constraints}{logical; should identifiability constraints be applied to
the smooth basis. See argument \code{absorb.cons} in \code{\link[mgcv:smoothCon]{mgcv::smoothCon()}}.}
\item{...}{other arguments passed to \code{\link[mgcv:smoothCon]{mgcv::smoothCon()}}.}
}
\value{
A tibble.
}
\description{
Creates a basis expansion from a definition of a smoother using the syntax
of \emph{mgcv}'s smooths via \code{\link[mgcv:s]{mgcv::s()}}., \code{\link[mgcv:te]{mgcv::te()}}, \code{\link[mgcv:ti]{mgcv::ti()}}, and
\code{\link[mgcv:t2]{mgcv::t2()}}.
}
\examples{
load_mgcv()
\dontshow{set.seed(42)}
df <- gamSim(4, n = 400, verbose = FALSE)
bf <- basis(s(x0), data = df)
bf <- basis(s(x2, by = fac, bs = 'bs'), data = df, constraints = TRUE)
}
\author{
Gavin L. Simpson
}
|
rm(list=ls())
datatable<-read.table("household_power_consumption.txt",
sep=";",
nrows= 2075260,
header=TRUE,
quote= "",
strip.white=TRUE,
stringsAsFactors = FALSE,
na.strings= "?")
datedata<-subset(datatable, (datatable$Date == "1/2/2007" | datatable$Date== "2/2/2007"))
datedata$Date <- as.Date(datedata$Date, format = "%d/%m/%Y")
datedata$Datetime <- as.POSIXct(paste(datedata$Date, datedata$Time))
png("plot2.png", width = 480, height = 480)
plot(datedata$Datetime,
datedata$Global_active_power,
type="l",
ylab= "Global Active Power (kilowatts)",
xlab="")
dev.off()
|
/plot2.R
|
no_license
|
ozkuran/ExData_Plotting1
|
R
| false | false | 762 |
r
|
rm(list=ls())
datatable<-read.table("household_power_consumption.txt",
sep=";",
nrows= 2075260,
header=TRUE,
quote= "",
strip.white=TRUE,
stringsAsFactors = FALSE,
na.strings= "?")
datedata<-subset(datatable, (datatable$Date == "1/2/2007" | datatable$Date== "2/2/2007"))
datedata$Date <- as.Date(datedata$Date, format = "%d/%m/%Y")
datedata$Datetime <- as.POSIXct(paste(datedata$Date, datedata$Time))
png("plot2.png", width = 480, height = 480)
plot(datedata$Datetime,
datedata$Global_active_power,
type="l",
ylab= "Global Active Power (kilowatts)",
xlab="")
dev.off()
|
# Code for computing likelihoods and posteriors
## Defining a helper function
# This function creates a data frame will all possible choices and probabilities
#associated with them, and matches it with participants' responses. This is used for computing likelihoods.
get_function <- here::here("bayesian_modeling", "fill_in_probs.R")
source(get_function)
# template that is used to save probabilities of data (agent's selection) given a specific strategy
probability_template <- expand.grid(prob_strategy = unique(expected_matrix$prob_strategy),
exp_choice = unique(expected_matrix$exp_choice))
list_of_probabilities = list()
# splitting adult data into individual data frames by id to be processed below
list_of_participants <- split(behavioral_data, behavioral_data$agent_id)
# computing probabilities of data (agent's selection) given a specific strategy
# Separate data frame for each agent
# Saving all to a list
for(i in 1:length(list_of_participants)){
z <- inner_join(expected_matrix, list_of_participants[[i]])
z <- merge(probability_template, z, all = TRUE)
id <- list_of_participants[[i]]$agent_id[1]
list_of_probabilities[[i]] <- fill_in_probs(z, expected_matrix, id)
}
# combining list of probabilities into single data frame
probabilities <- plyr::rbind.fill(list_of_probabilities)
# list to store likelihood dfs
list_of_likelihoods <- list()
# function to compute likelihood of each strategy by individual
calculate_ll <- function(df, strategy){
a <- strategy
b <- df %>%
filter(agent_id == current_agent) %>%
filter(prob_strategy == a) %>%
summarize(likelihood = prod(probability), strategy_ll = a)
return(b)
}
i <- 0
for(iteration in 1:(as.numeric(nrow(probabilities))/count(probabilities$agent_id)[1,2])){
# initializing likelihood df template
likelihoods <- as.data.frame(matrix(ncol = 3, nrow = 0))
current_agent <- probabilities$agent_id[iteration*count(probabilities$agent_id)[1,2]]
for(i in 1:length(strategies)){
# initializing likelihood df template
y <- calculate_ll(probabilities, strategies[i])
y$agent_id <- probabilities$agent_id[iteration*count(probabilities$agent_id)[1,2]]
likelihoods <- rbind(likelihoods, y)
i <- i + 1
}
likelihoods$likelihoodXprior <- likelihoods$likelihood / length(strategies)
list_of_likelihoods[[iteration]] <- likelihoods
i <- 0
iteration <- iteration + 1
}
likelihoods <- plyr::rbind.fill(list_of_likelihoods)
# computing the sum of likelihoods (the denominator in Bayes' Rule)
sum_ll <- likelihoods %>% group_by(agent_id) %>% dplyr::summarise(sum_ll = sum(likelihoodXprior))
likelihoods <- merge(sum_ll, likelihoods, by = "agent_id")
# computing the posterior probabilities
# aka probability that agent was using a given strategy given the data observed
likelihoods$posterior <- likelihoods$likelihoodXprior / likelihoods$sum_ll
|
/01_diversity_analyses/bayesian_modeling/compute_likelihoods_posteriors.R
|
no_license
|
nyu-cdsc/diversity
|
R
| false | false | 2,915 |
r
|
# Code for computing likelihoods and posteriors
## Defining a helper function
# This function creates a data frame will all possible choices and probabilities
#associated with them, and matches it with participants' responses. This is used for computing likelihoods.
get_function <- here::here("bayesian_modeling", "fill_in_probs.R")
source(get_function)
# template that is used to save probabilities of data (agent's selection) given a specific strategy
probability_template <- expand.grid(prob_strategy = unique(expected_matrix$prob_strategy),
exp_choice = unique(expected_matrix$exp_choice))
list_of_probabilities = list()
# splitting adult data into individual data frames by id to be processed below
list_of_participants <- split(behavioral_data, behavioral_data$agent_id)
# computing probabilities of data (agent's selection) given a specific strategy
# Separate data frame for each agent
# Saving all to a list
for(i in 1:length(list_of_participants)){
z <- inner_join(expected_matrix, list_of_participants[[i]])
z <- merge(probability_template, z, all = TRUE)
id <- list_of_participants[[i]]$agent_id[1]
list_of_probabilities[[i]] <- fill_in_probs(z, expected_matrix, id)
}
# combining list of probabilities into single data frame
probabilities <- plyr::rbind.fill(list_of_probabilities)
# list to store likelihood dfs
list_of_likelihoods <- list()
# function to compute likelihood of each strategy by individual
calculate_ll <- function(df, strategy){
a <- strategy
b <- df %>%
filter(agent_id == current_agent) %>%
filter(prob_strategy == a) %>%
summarize(likelihood = prod(probability), strategy_ll = a)
return(b)
}
i <- 0
for(iteration in 1:(as.numeric(nrow(probabilities))/count(probabilities$agent_id)[1,2])){
# initializing likelihood df template
likelihoods <- as.data.frame(matrix(ncol = 3, nrow = 0))
current_agent <- probabilities$agent_id[iteration*count(probabilities$agent_id)[1,2]]
for(i in 1:length(strategies)){
# initializing likelihood df template
y <- calculate_ll(probabilities, strategies[i])
y$agent_id <- probabilities$agent_id[iteration*count(probabilities$agent_id)[1,2]]
likelihoods <- rbind(likelihoods, y)
i <- i + 1
}
likelihoods$likelihoodXprior <- likelihoods$likelihood / length(strategies)
list_of_likelihoods[[iteration]] <- likelihoods
i <- 0
iteration <- iteration + 1
}
likelihoods <- plyr::rbind.fill(list_of_likelihoods)
# computing the sum of likelihoods (the denominator in Bayes' Rule)
sum_ll <- likelihoods %>% group_by(agent_id) %>% dplyr::summarise(sum_ll = sum(likelihoodXprior))
likelihoods <- merge(sum_ll, likelihoods, by = "agent_id")
# computing the posterior probabilities
# aka probability that agent was using a given strategy given the data observed
likelihoods$posterior <- likelihoods$likelihoodXprior / likelihoods$sum_ll
|
# program: spuRs/resources/scripts/quad1.r
# find the zeros of a2*x^2 + a1*x + a0 = 0
# clear the workspace
rm(list=ls())
# input
a2 <- 1
a1 <- 4
a0 <- 2
# calculation
root1 <- (-a1 + sqrt(a1^2 - 4*a2*a0))/(2*a2)
root2 <- (-a1 - sqrt(a1^2 - 4*a2*a0))/(2*a2)
# output
show(c(root1, root2))
|
/R Tutorials/Book spuRs/scripts/quad1.r
|
no_license
|
chengjun/Research
|
R
| false | false | 293 |
r
|
# program: spuRs/resources/scripts/quad1.r
# find the zeros of a2*x^2 + a1*x + a0 = 0
# clear the workspace
rm(list=ls())
# input
a2 <- 1
a1 <- 4
a0 <- 2
# calculation
root1 <- (-a1 + sqrt(a1^2 - 4*a2*a0))/(2*a2)
root2 <- (-a1 - sqrt(a1^2 - 4*a2*a0))/(2*a2)
# output
show(c(root1, root2))
|
log.val = function(beta, Xtst) {
#################### INIT
Xtst = as.matrix(Xtst)
beta = as.matrix(beta)
if(ncol(beta)>nrow(Xtst)) {Xtst = as.matrix(cbind(rep(1,nrow(Xtst)),Xtst))} ### then add intercept if necessary
prob = matrix(0,nrow=nrow(Xtst),ncol=2)
colnames(prob) = c("w1","w2")
#################### classement
prob[,"w1"] = exp(Xtst%*%beta) / (1+exp(Xtst%*%beta))
prob[,"w2"] = 1 - prob[,1]
classement = as.integer( prob[,"w1"] < prob[,"w2"] ) + 1
return(list(prob=prob, classement=classement))
}
|
/TP4/fonctions du rapport/log.val.R
|
no_license
|
mdepuydt/SY09
|
R
| false | false | 566 |
r
|
log.val = function(beta, Xtst) {
#################### INIT
Xtst = as.matrix(Xtst)
beta = as.matrix(beta)
if(ncol(beta)>nrow(Xtst)) {Xtst = as.matrix(cbind(rep(1,nrow(Xtst)),Xtst))} ### then add intercept if necessary
prob = matrix(0,nrow=nrow(Xtst),ncol=2)
colnames(prob) = c("w1","w2")
#################### classement
prob[,"w1"] = exp(Xtst%*%beta) / (1+exp(Xtst%*%beta))
prob[,"w2"] = 1 - prob[,1]
classement = as.integer( prob[,"w1"] < prob[,"w2"] ) + 1
return(list(prob=prob, classement=classement))
}
|
testlist <- list(x = structure(c(1.35248279137152e-309, 1.98730118526674e-168, 5.28313590379074e-312), .Dim = c(3L, 1L)))
result <- do.call(bravo:::colSumSq_matrix,testlist)
str(result)
|
/bravo/inst/testfiles/colSumSq_matrix/libFuzzer_colSumSq_matrix/colSumSq_matrix_valgrind_files/1609959947-test.R
|
no_license
|
akhikolla/updated-only-Issues
|
R
| false | false | 186 |
r
|
testlist <- list(x = structure(c(1.35248279137152e-309, 1.98730118526674e-168, 5.28313590379074e-312), .Dim = c(3L, 1L)))
result <- do.call(bravo:::colSumSq_matrix,testlist)
str(result)
|
testlist <- list(doy = numeric(0), latitude = numeric(0), temp = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))
result <- do.call(meteor:::ET0_ThornthwaiteWilmott,testlist)
str(result)
|
/meteor/inst/testfiles/ET0_ThornthwaiteWilmott/libFuzzer_ET0_ThornthwaiteWilmott/ET0_ThornthwaiteWilmott_valgrind_files/1612735241-test.R
|
no_license
|
akhikolla/updatedatatype-list3
|
R
| false | false | 207 |
r
|
testlist <- list(doy = numeric(0), latitude = numeric(0), temp = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))
result <- do.call(meteor:::ET0_ThornthwaiteWilmott,testlist)
str(result)
|
Time <- c(11048,11262,11504,12418)
Pipeline <- c(0.45,0.45,0.45,0.37,0.44,0.43,0.43,0.37,0.45,
0.45,0.45,0.40,0.43,0.42,0.43,0.43,0.42,0.41,
0.41,0.35,0.41,0.42,0.42,0.42,0.46,0.46,0.46,
0.43,0.43,0.42,0.43,0.42,0.45,0.45,0.45,0.44,
0.45,0.44,0.45,0.44,0.44,0.43,0.44,0.44,0.44,
0.44,0.44,0.44,0.43,0.43,0.43,0.43,0.42,0.43,
0.42,0.42,0.43,0.44,0.44,0.43,0.45,0.44,0.45,
0.44,0.45,0.44,0.45,0.41,0.42,0.42,0.42,0.39,
0.44,0.44,0.44,0.41,0.42,0.42,0.42,0.42,0.41,
0.41,0.41,0.37,0.42,0.42,0.42,0.39,0.43,0.44,
0.43,0.43,0.44,0.44,0.44,0.42,0.43,0.44,0.45,
0.45,0.43,0.43,0.43,0.42,0.44,0.43,0.43,0.42,
0.44,0.43,0.43,0.40,0.51,0.51,0.52,0.47,0.51,
0.51,0.52,0.49,0.55,0.55,0.56,0.55,0.51,0.50,
0.51,0.51,0.52,0.52,0.52,0.52)
Y <- matrix(Pipeline,nrow = 33, byrow = T)
Q1_data <- list(N_elbow=12, N_pipe=16, N=33, K=4, y=Y, t=Time)
library(rstan)
rstan_options(auto_write = TRUE)
options(mc.cores = parallel::detectCores())
fit3 <- stan(file = "/Users/pro/Projects/Pipelines/Complex/Complex_Model1_Lognormal.stan",iter = 80000,warmup = 8000, thin = 100,control = list(adapt_delta = 0.95,max_treedepth = 12),data = Q1_data)
summary(fit3)$summary[c(1:9,109),]
|
/Complex/Complex_Model1_Lognormal_Drive.r
|
no_license
|
ISUCyclone/Pipelines
|
R
| false | false | 1,357 |
r
|
Time <- c(11048,11262,11504,12418)
Pipeline <- c(0.45,0.45,0.45,0.37,0.44,0.43,0.43,0.37,0.45,
0.45,0.45,0.40,0.43,0.42,0.43,0.43,0.42,0.41,
0.41,0.35,0.41,0.42,0.42,0.42,0.46,0.46,0.46,
0.43,0.43,0.42,0.43,0.42,0.45,0.45,0.45,0.44,
0.45,0.44,0.45,0.44,0.44,0.43,0.44,0.44,0.44,
0.44,0.44,0.44,0.43,0.43,0.43,0.43,0.42,0.43,
0.42,0.42,0.43,0.44,0.44,0.43,0.45,0.44,0.45,
0.44,0.45,0.44,0.45,0.41,0.42,0.42,0.42,0.39,
0.44,0.44,0.44,0.41,0.42,0.42,0.42,0.42,0.41,
0.41,0.41,0.37,0.42,0.42,0.42,0.39,0.43,0.44,
0.43,0.43,0.44,0.44,0.44,0.42,0.43,0.44,0.45,
0.45,0.43,0.43,0.43,0.42,0.44,0.43,0.43,0.42,
0.44,0.43,0.43,0.40,0.51,0.51,0.52,0.47,0.51,
0.51,0.52,0.49,0.55,0.55,0.56,0.55,0.51,0.50,
0.51,0.51,0.52,0.52,0.52,0.52)
Y <- matrix(Pipeline,nrow = 33, byrow = T)
Q1_data <- list(N_elbow=12, N_pipe=16, N=33, K=4, y=Y, t=Time)
library(rstan)
rstan_options(auto_write = TRUE)
options(mc.cores = parallel::detectCores())
fit3 <- stan(file = "/Users/pro/Projects/Pipelines/Complex/Complex_Model1_Lognormal.stan",iter = 80000,warmup = 8000, thin = 100,control = list(adapt_delta = 0.95,max_treedepth = 12),data = Q1_data)
summary(fit3)$summary[c(1:9,109),]
|
plot4 <- function(){
library("stringr");
library("dplyr");
data <- read.csv("household_power_consumption.txt", sep = ";", header = TRUE, stringsAsFactors=FALSE, na.strings = "?");
data$Date <- as.Date(data$Date, "%d/%m/%Y");
filtered <- filter(data, Date == "2007-02-01" | Date == "2007-02-02");
filtered$Time <- as.POSIXct(paste(filtered$Date, filtered$Time), format = "%Y-%m-%d %H:%M:%S");
png(file = "plot4.png");
par(mfrow=c(2,2))
plot(y = filtered$Global_active_power, x = filtered$Time, xlab = "", ylab = "Global Active Power (kilowatts)", type = "l")
plot(y = filtered$Voltage, x = filtered$Time, xlab = "datetime", ylab = "Voltage", type = "l")
plot(y = filtered$Sub_metering_1, x = filtered$Time, xlab = "", ylab = "Energy sub metering", type = "l");
lines(y = plot2data$Sub_metering_2, x = plot2data$Time, col = "red");
lines(y = plot2data$Sub_metering_3, x = plot2data$Time, col = "blue");
legend("topright", legend = c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"), col = c("black", "red", "blue"), lty=1);
plot(y = filtered$Global_reactive_power, x = filtered$Time, xlab = "datetime", ylab = "Global_reactive_power", type = "l");
dev.off();
return("plot4 created");
}
|
/plot4.R
|
no_license
|
23Mbennett/exploratory-data-anlaysis-assignment-1
|
R
| false | false | 1,258 |
r
|
plot4 <- function(){
library("stringr");
library("dplyr");
data <- read.csv("household_power_consumption.txt", sep = ";", header = TRUE, stringsAsFactors=FALSE, na.strings = "?");
data$Date <- as.Date(data$Date, "%d/%m/%Y");
filtered <- filter(data, Date == "2007-02-01" | Date == "2007-02-02");
filtered$Time <- as.POSIXct(paste(filtered$Date, filtered$Time), format = "%Y-%m-%d %H:%M:%S");
png(file = "plot4.png");
par(mfrow=c(2,2))
plot(y = filtered$Global_active_power, x = filtered$Time, xlab = "", ylab = "Global Active Power (kilowatts)", type = "l")
plot(y = filtered$Voltage, x = filtered$Time, xlab = "datetime", ylab = "Voltage", type = "l")
plot(y = filtered$Sub_metering_1, x = filtered$Time, xlab = "", ylab = "Energy sub metering", type = "l");
lines(y = plot2data$Sub_metering_2, x = plot2data$Time, col = "red");
lines(y = plot2data$Sub_metering_3, x = plot2data$Time, col = "blue");
legend("topright", legend = c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"), col = c("black", "red", "blue"), lty=1);
plot(y = filtered$Global_reactive_power, x = filtered$Time, xlab = "datetime", ylab = "Global_reactive_power", type = "l");
dev.off();
return("plot4 created");
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.