问:
h2o server fails when I start a grid search
I'm doing a grid search on a classification model.  When the h20 server starts I get:

```<code>R is connected to the H2O cluster:
    H2O cluster uptime:         9 minutes 35 seconds
    H2O cluster version:        3.10.4.8
    H2O cluster version age:    14 days, 4 hours and 1 minute
    H2O cluster name:           H2O_started_from_R_Charles_huu844
    H2O cluster total nodes:    1
    H2O cluster total memory:   21.31 GB
    H2O cluster total cores:    8
    H2O cluster allowed cores:  8
    H2O cluster healthy:        TRUE
    H2O Connection ip:          localhost
    H2O Connection port:        54321
    H2O Connection proxy:       NA
    H2O Internal Security:      FALSE
    R Version:                  R version 3.2.2 (2015-08-14)
</code>```

When my model enters the grid search, I get the following error message:

```<code>ERROR: Unexpected HTTP Status code: 412 Precondition Failed (url = http://localhost:54321/99/Grids/mygrid?sort_by=auc&decreasing=TRUE)

water.exceptions.H2OIllegalArgumentException
 [1] "water.exceptions.H2OIllegalArgumentException: Invalid argument for sort_by specified. Must be one of: [r2, mean_per_class_accuracy, max_per_class_error, err, total_rows, rmse, accuracy, err_count, logloss, mse, mean_per_class_error]"
 [2] "    hex.schemas.GridSchemaV99.fillFromImpl(GridSchemaV99.java:114)"
</code>```

My R script is as follows:

```<code>rm(list=ls())
options(scipen=999) # remove E notation
ptm <- proc.time()

if (Sys.info()["sysname"] == "Windows") {
  filePath = "//bigsur/sm/Trending/model.csv"
  homedir = "c:/sm/Trending/"
  setwd("c:/sm/Trending/R")
  sink("C:/Users/Charles/Desktop/log.txt")
} else {
  filePath = "/Volumes/sm/Trending/model.csv"
  homedir = "/Volumes/sm/Trending/"
  setwd("/Volumes/sm/Trending/R")
  sink("~/Desktop/log.txt")
}

#install.packages("ggplot2")
#install.packages("dplyr")

sink.reset <- function(){
  for(i in seq_len(sink.number())){
    sink(NULL)
  }
}

printf <- function(...) print(sprintf(...))

results = function(title, best_model) {
  best_params = best_model@parameters
  best_activation            <<- best_model@parameters$activation
  best_hidden                <<- best_model@parameters$hidden
  best_l1                    <<- best_model@parameters$l1
  best_l2                    <<- best_model@parameters$l2
  best_input_dropout_ratio   <<- best_model@parameters$input_dropout_ratio
  best_hidden_dropout_ratios <<- best_model@parameters$hidden_dropout_ratios

  printf(" ")
  printf("%s", title)
  best_model
  plot(best_model)
  h2o.performance(best_model)
  h2o.performance(best_model, valid = TRUE)
  h2o.mse(best_model, valid = TRUE)

  printf("mse: %f", best_model@model$validation_metrics@metrics$MSE)
  printf("best activation: %s", best_activation)
  cat("best hidden layers: ", best_hidden, "\n")
  printf("Best l1: %f", best_l1)
  printf("Best l2: %f", best_l2)
  #printf("best_input_dropout_ratio: %f", best_input_dropout_ratio)
  #cat("Best best_hidden_dropout_ratios: ", best_hidden_dropout_ratios, "\n")

  predictions = h2o.predict(best_model, test)
  summary(predictions, exact_quantiles=TRUE)
  predicted = predictions[,1]
  test_targets = test[, 5]
  correct = predicted == test_targets
  numCorrect = as.integer(sum(correct))
  ntotal = as.integer(nrow(correct))
  percent = round(numCorrect/ntotal*100, 2)
  printf("Correct classifications on all data: %d/%d (%f)", numCorrect, ntotal, percent)

  #predicted.h2o = h2o.assign(predicted, key = "predicted.h2o")
  #correct.h2o = h2o.assign(correct, key = "correct.h2o")

  perf_test = h2o.performance(model = best_model, newdata = test)
  cat("\nPerformance on test dataset\n")
  print(perf_test)
  cat("\nConfusion matrix on test dataset\n")
  h2o.confusionMatrix(perf_test)

  # Plot Receiver Operating Characteristic (ROC) curve and find its Area Under the Curve (AUC)
  # A ROC curve is a graph of the true positive rate (recall) against the false positive
  # rate for a binary classifier.
  #plot(f1_best_model, type = "cutoffs", col = "blue")

  cm = h2o.confusionMatrix(best_model, train)
  print("Confusion Matrix: ")
  print(cm)
  true_negative = cm[1,1]
  true_positive = cm[2,2]
  false_negative = cm[2,1]
  false_positive = cm[1,2]
  total = true_negative + true_positive + false_negative + false_positive
  accuracy = (true_positive + true_negative)/total
  printf("accuracy: %f", accuracy)

  misclassification_rate = (false_positive + false_negative)/total
  printf("misclassification_rate: %f", misclassification_rate)

  cat("\nVariable importance\n")
  print(best_model@model$variable_importance)

  return_list = c(best_activation,
                  best_hidden,
                  best_l1,
                  best_l2,
                  best_input_dropout_ratio,
                  best_hidden_dropout_ratios)

  return (return_list)
}

library(h2o)
library(dplyr)
library(data.table)
library(ggplot2)

localH2O = h2o.init(ip = "localhost",
                    port = 54321,
                    startH2O = TRUE,
                    max_mem_size="24G",
                    nthreads = -1)
h2o.no_progress()
h2o.removeAll() ## clean slate - just in case the cluster was already running

print(filePath)
model.full <- read.csv(filePath, header = TRUE, sep = ",")
head(model.full)
remove = !colnames(model.full) %in% c("Date",
                                      "Symbol",
                                      "BuyIndex",
                                      "SellIndex",
                                      "BoxRatio",
                                      "Acceleration",
                                      "nPosVelo",
                                      "Gain")
model_orig = model.full[, remove]
head(model_orig)
model = model_orig[sample(nrow(model_orig)),] # shuffle the rows
head(model)

df <- as.h2o(model, destination_frame = "df")

splits <- h2o.splitFrame(df, c(0.6,0.2), seed=1234)
train  <- h2o.assign(splits[[1]], "train.hex") # 60%
valid  <- h2o.assign(splits[[2]], "valid.hex") # 20%
test   <- h2o.assign(splits[[3]], "test.hex")  # 20%

printf("train----------------------------------------")
head(train)
train
printf("valid----------------------------------------")
#head(valid)
valid
printf("test-----------------------------------------")
#head(test)
test

p1 = train$Thrust
p2 = train$Velocity
p3 = train$OnBalRun
p4 = train$vwapGain
p1d = rbind(lapply(p1, as.double))  # p1 is an environment variable, we need doubles
p2d = rbind(lapply(p2, as.double))
p3d = rbind(lapply(p3, as.double))
p4d = rbind(lapply(p4, as.double))
a = unlist(p1d)
b = unlist(p2d)
c = unlist(p3d)
d = unlist(p4d)

pairs(train[1:4], main = "Scatterplot of predictors", pch = 21, cex = 0.8, bg = c("green3", "red")[unclass(model$Altitude)])

cat("\n\n1. Summary of train dataset------------------------------------------------------\n")
summary(train, exact_quantiles=TRUE)

cat("\n\n2. Grid Search on valid data ----------------------------------------------------\n")

activation_opts = c("RectifierWithDropout","TanhWithDropout","MaxoutWithDropout")
hidden_opts = list(c(80),c(100),c(200),c(300),c(400),c(500),
                   c(80,80),c(100,100),c(200,200),c(300,300),c(400,400),c(500,500),
                   c(80,80,80,80),c(100,100,100,100),c(200,200,200,200),c(300,300,300,300),
                   c(80,80,80,80,80),c(100,100,100,100,100),c(200,200,200,200,200),
                   c(300,300,300,300,300),c(400,400,400,400,400),c(500,500,500,500,500),
                   c(80,80,80,80,80,80),c(100,100,100,100,100,100),c(200,200,200,200,200,200),
                   c(300,300,300,300,300,300),c(400,400,400,400,400,400),
                   c(500,500,500,500,500,500)
                   )
l1_opts = runif(1, 0, 0.0001)
l2_opts = runif(1, 0, 0.0001)

hyperparams = list(
  activation = activation_opts,
  hidden = hidden_opts,
  l1 = l1_opts,
  l2 = l2_opts,
  max_w2 = 10
)

search_criteria = list(strategy = "RandomDiscrete",
                       stopping_metric = "misclassification",
                       max_models = 10000,
                       max_runtime_secs = 72000,
                       stopping_tolerance = 0.00001,
                       stopping_rounds = 10)

grid_model = h2o.grid(algorithm = "deeplearning",
                      grid_id = "mygrid",
                      hyper_params = hyperparams,
                      search_criteria = search_criteria,
                      x = 1:4,
                      y = 5,
                      training_frame = train,
                      validation_frame = valid,
                      variable_importances = TRUE,
                      balance_classes=TRUE,
                      score_training_samples=1000,
                      score_validation_samples=1000,
                      score_validation_sampling="Stratified",
                      epochs = 1000000,
                      seed = 7)

cat("\n\n3. Summary of grid_model---------------------------------------------------------\n")
grid = h2o.getGrid("mygrid", sort_by="auc", decreasing=TRUE)
summary(grid)

cat("\n\n4. Performance of best_model-----------------------------------------------------\n")
best_model = h2o.getModel(grid@model_ids[[1]])

results("5.best_model", best_model)

cat("\n\n6. Performance valid dataset-----------------------------------------------------\n")
perf_valid = h2o.performance(model = best_model, newdata = valid)
perf_valid

cat("\n\n7. Performance on test dataset---------------------------------------------------\n")
perf_test = h2o.performance(model = best_model, newdata = test)
perf_test

plot(perf_test, type="roc")     # Plot the roc curve

predicted <- h2o.predict( best_model, test )
actual = test[,5]
cat("\n\n8. Mean prediction on the test set: ", 100*mean( predicted$predict == actual ), "%\n")
correct = predicted == actual
numCorrect = as.integer(sum(correct))
ntotal = as.integer(nrow(correct))
percent = round(numCorrect/ntotal*100, 2)
printf("9. Test of Mean prediction on the test set: %d/%d (%f)", numCorrect, ntotal, percent)
cat("\n\n10. The 'test' set auc is: ", h2o.auc(perf_test), "\n")

p = h2o.saveModel(best_model, path = "C:\\sm\\Trending\\h2o_model", force = TRUE)
p

minutes = (proc.time() - ptm)[1]
printf("Elapsed time: %.2f minutes", minutes)

unlink("log.txt")
sink.reset()
</code>```

My log is:

```<code> Connection successful!

R is connected to the H2O cluster:
    H2O cluster uptime:         9 minutes 35 seconds
    H2O cluster version:        3.10.4.8
    H2O cluster version age:    14 days, 4 hours and 1 minute
    H2O cluster name:           H2O_started_from_R_Charles_huu844
    H2O cluster total nodes:    1
    H2O cluster total memory:   21.31 GB
    H2O cluster total cores:    8
    H2O cluster allowed cores:  8
    H2O cluster healthy:        TRUE
    H2O Connection ip:          localhost
    H2O Connection port:        54321
    H2O Connection proxy:       NA
    H2O Internal Security:      FALSE
    R Version:                  R version 3.2.2 (2015-08-14)

[1] 0
[1] "//bigsur/sm/Trending/model.csv"
        Date Symbol BuyIndex SellIndex BoxRatio  Thrust Acceleration Velocity nPosVelo
1   4/5/2017 GBX         132       199   77.724 49.7190     107.5811   2.9236       59
2   1/5/2017 RH          216       259    4.838  4.8380     137.0574   0.3381       14
3  9/28/2016 DDS         149       444    0.150  0.4860      99.1360   0.1081       59
4 11/25/2016 JKS         132       186    0.932  0.8686      38.9931   0.6057       59
5 12/12/2016 JNUG        132       177    0.582  0.3242      87.1144   1.1274       18
6   3/7/2017 LPL         134       180    8.954  8.9540      34.1691   0.4778       59
  OnBalRun vwapGain    Gain Altitude
1  12.6378  90.0656 -0.1659       no
2   1.5157   0.9495 -0.6496       no
3   0.5476   2.2887  4.1439      yes
4   3.2719   3.8235  0.5051       no
5   2.5006  12.0472 -0.8942       no
6   2.9935   1.1234 -0.1617       no
   Thrust Velocity OnBalRun vwapGain Altitude
1 49.7190   2.9236  12.6378  90.0656       no
2  4.8380   0.3381   1.5157   0.9495       no
3  0.4860   0.1081   0.5476   2.2887      yes
4  0.8686   0.6057   3.2719   3.8235       no
5  0.3242   1.1274   2.5006  12.0472       no
6  8.9540   0.4778   2.9935   1.1234       no
     Thrust Velocity OnBalRun vwapGain Altitude
4427 0.9370   0.3176   1.2786   2.3151       no
3079 2.2060   0.9261   1.1257   1.2506       no
3952 0.0702   0.4430   1.1485   0.9928       no
7765 1.1596   1.1067   6.2563   2.1164      yes
1682 0.6708   0.4519   1.3848   2.1808       no
5145 4.5600   0.3462   1.7386   0.7722       no
[1] "train----------------------------------------"
  Thrust Velocity OnBalRun vwapGain Altitude
1 2.2060   0.9261   1.1257   1.2506       no
2 0.6708   0.4519   1.3848   2.1808       no
3 4.5600   0.3462   1.7386   0.7722       no
4 3.6930   3.2778  11.4092  49.3335       no
5 0.9980   0.4035   1.6667   1.1264       no
6 0.2016   0.5627   2.4101   1.2642       no
  Thrust Velocity OnBalRun vwapGain Altitude
1 2.2060   0.9261   1.1257   1.2506       no
2 0.6708   0.4519   1.3848   2.1808       no
3 4.5600   0.3462   1.7386   0.7722       no
4 3.6930   3.2778  11.4092  49.3335       no
5 0.9980   0.4035   1.6667   1.1264       no
6 0.2016   0.5627   2.4101   1.2642       no

[5548 rows x 5 columns]
[1] "valid----------------------------------------"
  Thrust Velocity OnBalRun vwapGain Altitude
1 0.9370   0.3176   1.2786   2.3151       no
2 0.0702   0.4430   1.1485   0.9928       no
3 1.0230   0.3119   3.0922   0.8788       no
4 6.4100   0.9966   5.3490   2.9436      yes
5 6.9620   0.7004   3.5810   4.8905       no
6 1.6800   1.4518   5.1933   1.7955       no

[1875 rows x 5 columns]
[1] "test-----------------------------------------"
  Thrust Velocity OnBalRun vwapGain Altitude
1 1.1596   1.1067   6.2563   2.1164      yes
2 4.7010   0.5369   1.1266   7.5566       no
3 1.7110   0.9247   3.5819   3.0598       no
4 1.4620   0.3315   4.3097   0.4129       no
5 0.5610   0.4494   1.8738   1.3942       no
6 6.7255   1.7309   5.6268   4.4937      yes

[1823 rows x 5 columns]

1. Summary of train dataset------------------------------------------------------
 Thrust               Velocity          OnBalRun           vwapGain           Altitude
 Min.   :   -1.4845   Min.   :-0.1241   Min.   : -0.5299   Min.   : -4.7648    no :4875
 1st Qu.:    0.3984   1st Qu.: 0.3281   1st Qu.:  1.1468   1st Qu.:  0.8684    yes: 671
 Median :    1.0425   Median : 0.3815   Median :  1.6439   Median :  1.9954       :   2
 Mean   :   12.1332   Mean   : 0.5913   Mean   :  2.5911   Mean   :  4.8876
 3rd Qu.:    1.9723   3rd Qu.: 0.5716   3rd Qu.:  2.6507   3rd Qu.:  4.7500
 Max.   :41279.8960   Max.   :29.4449   Max.   :154.5988   Max.   :314.7143
 NA's   :2            NA's   :2         NA's   :2          NA's   :2

2. Grid Search on valid data ----------------------------------------------------

3. Summary of grid_model---------------------------------------------------------

ERROR: Unexpected HTTP Status code: 412 Precondition Failed (url = http://localhost:54321/99/Grids/mygrid?sort_by=auc&decreasing=TRUE)

water.exceptions.H2OIllegalArgumentException
 [1] "water.exceptions.H2OIllegalArgumentException: Invalid argument for sort_by specified. Must be one of: [r2, mean_per_class_accuracy, max_per_class_error, err, total_rows, rmse, accuracy, err_count, logloss, mse, mean_per_class_error]"
 [2] "    hex.schemas.GridSchemaV99.fillFromImpl(GridSchemaV99.java:114)"
 [3] "    water.api.GridsHandler.fetch(GridsHandler.java:41)"
 [4] "    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)"
 [5] "    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)"
 [6] "    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)"
 [7] "    java.lang.reflect.Method.invoke(Method.java:498)"
 [8] "    water.api.Handler.handle(Handler.java:61)"
 [9] "    water.api.RequestServer.serve(RequestServer.java:436)"
[10] "    water.api.RequestServer.doGeneric(RequestServer.java:285)"
[11] "    water.api.RequestServer.doGet(RequestServer.java:220)"
[12] "    javax.servlet.http.HttpServlet.service(HttpServlet.java:735)"
[13] "    javax.servlet.http.HttpServlet.service(HttpServlet.java:848)"
[14] "    org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:684)"
[15] "    org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:503)"
[16] "    org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1086)"
[17] "    org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:429)"
[18] "    org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1020)"
[19] "    org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:135)"
[20] "    org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:154)"
[21] "    org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:116)"
[22] "    water.JettyHTTPD$LoginHandler.handle(JettyHTTPD.java:417)"
[23] "    org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:154)"
[24] "    org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:116)"
[25] "    org.eclipse.jetty.server.Server.handle(Server.java:370)"
[26] "    org.eclipse.jetty.server.AbstractHttpConnection.handleRequest(AbstractHttpConnection.java:494)"
[27] "    org.eclipse.jetty.server.BlockingHttpConnection.handleRequest(BlockingHttpConnection.java:53)"
[28] "    org.eclipse.jetty.server.AbstractHttpConnection.headerComplete(AbstractHttpConnection.java:971)"
[29] "    org.eclipse.jetty.server.AbstractHttpConnection$RequestHandler.headerComplete(AbstractHttpConnection.java:1033)"
[30] "    org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:644)"
[31] "    org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:235)"
[32] "    org.eclipse.jetty.server.BlockingHttpConnection.handle(BlockingHttpConnection.java:72)"
[33] "    org.eclipse.jetty.server.bio.SocketConnector$ConnectorEndPoint.run(SocketConnector.java:264)"
[34] "    org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:608)"
[35] "    org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:543)"
[36] "    java.lang.Thread.run(Thread.java:745)"

4. Performance of best_model-----------------------------------------------------

6. Performance valid dataset-----------------------------------------------------

7. Performance on test dataset---------------------------------------------------
Called from: sprintf(...)
[1] "Elapsed time: 85.98 minutes"
</code>```

Please help.

Charles

答: AUC is a metric for classification, you're creating a ~regression~ model from what I see therefore you cannot use auc in grid = h2o.getGrid("mygrid", sort_by="auc", decreasing=TRUE). Instead use, as the error message suggests, one of the following metrics: r2, mean_per_class_accuracy, max_per_class_error, err, total_rows, rmse, accuracy, err_count, logloss, mse, mean_per_class_error.

Body:
I'm doing a grid search on a classification model.  When the h20 server starts I get:

R is connected to the H2O cluster:
    H2O cluster uptime:         9 minutes 35 seconds
    H2O cluster version:        3.10.4.8
    H2O cluster version age:    14 days, 4 hours and 1 minute
    H2O cluster name:           H2O_started_from_R_Charles_huu844
    H2O cluster total nodes:    1
    H2O cluster total memory:   21.31 GB
    H2O cluster total cores:    8
    H2O cluster allowed cores:  8
    H2O cluster healthy:        TRUE
    H2O Connection ip:          localhost
    H2O Connection port:        54321
    H2O Connection proxy:       NA
    H2O Internal Security:      FALSE
    R Version:                  R version 3.2.2 (2015-08-14)

When my model enters the grid search, I get the following error message:

ERROR: Unexpected HTTP Status code: 412 Precondition Failed (url = http://localhost:54321/99/Grids/mygrid?sort_by=auc&decreasing=TRUE)

water.exceptions.H2OIllegalArgumentException
 [1] "water.exceptions.H2OIllegalArgumentException: Invalid argument for sort_by specified. Must be one of: [r2, mean_per_class_accuracy, max_per_class_error, err, total_rows, rmse, accuracy, err_count, logloss, mse, mean_per_class_error]"
 [2] "    hex.schemas.GridSchemaV99.fillFromImpl(GridSchemaV99.java:114)"

My R script is as follows:

rm(list=ls())
options(scipen=999) # remove E notation
ptm <- proc.time()

if (Sys.info()["sysname"] == "Windows") {
  filePath = "//bigsur/sm/Trending/model.csv"
  homedir = "c:/sm/Trending/"
  setwd("c:/sm/Trending/R")
  sink("C:/Users/Charles/Desktop/log.txt")
} else {
  filePath = "/Volumes/sm/Trending/model.csv"
  homedir = "/Volumes/sm/Trending/"
  setwd("/Volumes/sm/Trending/R")
  sink("~/Desktop/log.txt")
}

#install.packages("ggplot2")
#install.packages("dplyr")

sink.reset <- function(){
  for(i in seq_len(sink.number())){
    sink(NULL)
  }
}

printf <- function(...) print(sprintf(...))

results = function(title, best_model) {
  best_params = best_model@parameters
  best_activation            <<- best_model@parameters$activation
  best_hidden                <<- best_model@parameters$hidden
  best_l1                    <<- best_model@parameters$l1
  best_l2                    <<- best_model@parameters$l2
  best_input_dropout_ratio   <<- best_model@parameters$input_dropout_ratio
  best_hidden_dropout_ratios <<- best_model@parameters$hidden_dropout_ratios

  printf(" ")
  printf("%s", title)
  best_model
  plot(best_model)
  h2o.performance(best_model)
  h2o.performance(best_model, valid = TRUE)
  h2o.mse(best_model, valid = TRUE)

  printf("mse: %f", best_model@model$validation_metrics@metrics$MSE)
  printf("best activation: %s", best_activation)
  cat("best hidden layers: ", best_hidden, "\n")
  printf("Best l1: %f", best_l1)
  printf("Best l2: %f", best_l2)
  #printf("best_input_dropout_ratio: %f", best_input_dropout_ratio)
  #cat("Best best_hidden_dropout_ratios: ", best_hidden_dropout_ratios, "\n")

  predictions = h2o.predict(best_model, test)
  summary(predictions, exact_quantiles=TRUE)
  predicted = predictions[,1]
  test_targets = test[, 5]
  correct = predicted == test_targets
  numCorrect = as.integer(sum(correct))
  ntotal = as.integer(nrow(correct))
  percent = round(numCorrect/ntotal*100, 2)
  printf("Correct classifications on all data: %d/%d (%f)", numCorrect, ntotal, percent)

  #predicted.h2o = h2o.assign(predicted, key = "predicted.h2o")
  #correct.h2o = h2o.assign(correct, key = "correct.h2o")

  perf_test = h2o.performance(model = best_model, newdata = test)
  cat("\nPerformance on test dataset\n")
  print(perf_test)
  cat("\nConfusion matrix on test dataset\n")
  h2o.confusionMatrix(perf_test)

  # Plot Receiver Operating Characteristic (ROC) curve and find its Area Under the Curve (AUC)
  # A ROC curve is a graph of the true positive rate (recall) against the false positive
  # rate for a binary classifier.
  #plot(f1_best_model, type = "cutoffs", col = "blue")

  cm = h2o.confusionMatrix(best_model, train)
  print("Confusion Matrix: ")
  print(cm)
  true_negative = cm[1,1]
  true_positive = cm[2,2]
  false_negative = cm[2,1]
  false_positive = cm[1,2]
  total = true_negative + true_positive + false_negative + false_positive
  accuracy = (true_positive + true_negative)/total
  printf("accuracy: %f", accuracy)

  misclassification_rate = (false_positive + false_negative)/total
  printf("misclassification_rate: %f", misclassification_rate)

  cat("\nVariable importance\n")
  print(best_model@model$variable_importance)

  return_list = c(best_activation,
                  best_hidden,
                  best_l1,
                  best_l2,
                  best_input_dropout_ratio,
                  best_hidden_dropout_ratios)

  return (return_list)
}

library(h2o)
library(dplyr)
library(data.table)
library(ggplot2)

localH2O = h2o.init(ip = "localhost",
                    port = 54321,
                    startH2O = TRUE,
                    max_mem_size="24G",
                    nthreads = -1)
h2o.no_progress()
h2o.removeAll() ## clean slate - just in case the cluster was already running

print(filePath)
model.full <- read.csv(filePath, header = TRUE, sep = ",")
head(model.full)
remove = !colnames(model.full) %in% c("Date",
                                      "Symbol",
                                      "BuyIndex",
                                      "SellIndex",
                                      "BoxRatio",
                                      "Acceleration",
                                      "nPosVelo",
                                      "Gain")
model_orig = model.full[, remove]
head(model_orig)
model = model_orig[sample(nrow(model_orig)),] # shuffle the rows
head(model)

df <- as.h2o(model, destination_frame = "df")

splits <- h2o.splitFrame(df, c(0.6,0.2), seed=1234)
train  <- h2o.assign(splits[[1]], "train.hex") # 60%
valid  <- h2o.assign(splits[[2]], "valid.hex") # 20%
test   <- h2o.assign(splits[[3]], "test.hex")  # 20%

printf("train----------------------------------------")
head(train)
train
printf("valid----------------------------------------")
#head(valid)
valid
printf("test-----------------------------------------")
#head(test)
test

p1 = train$Thrust
p2 = train$Velocity
p3 = train$OnBalRun
p4 = train$vwapGain
p1d = rbind(lapply(p1, as.double))  # p1 is an environment variable, we need doubles
p2d = rbind(lapply(p2, as.double))
p3d = rbind(lapply(p3, as.double))
p4d = rbind(lapply(p4, as.double))
a = unlist(p1d)
b = unlist(p2d)
c = unlist(p3d)
d = unlist(p4d)

pairs(train[1:4], main = "Scatterplot of predictors", pch = 21, cex = 0.8, bg = c("green3", "red")[unclass(model$Altitude)])

cat("\n\n1. Summary of train dataset------------------------------------------------------\n")
summary(train, exact_quantiles=TRUE)

cat("\n\n2. Grid Search on valid data ----------------------------------------------------\n")

activation_opts = c("RectifierWithDropout","TanhWithDropout","MaxoutWithDropout")
hidden_opts = list(c(80),c(100),c(200),c(300),c(400),c(500),
                   c(80,80),c(100,100),c(200,200),c(300,300),c(400,400),c(500,500),
                   c(80,80,80,80),c(100,100,100,100),c(200,200,200,200),c(300,300,300,300),
                   c(80,80,80,80,80),c(100,100,100,100,100),c(200,200,200,200,200),
                   c(300,300,300,300,300),c(400,400,400,400,400),c(500,500,500,500,500),
                   c(80,80,80,80,80,80),c(100,100,100,100,100,100),c(200,200,200,200,200,200),
                   c(300,300,300,300,300,300),c(400,400,400,400,400,400),
                   c(500,500,500,500,500,500)
                   )
l1_opts = runif(1, 0, 0.0001)
l2_opts = runif(1, 0, 0.0001)

hyperparams = list(
  activation = activation_opts,
  hidden = hidden_opts,
  l1 = l1_opts,
  l2 = l2_opts,
  max_w2 = 10
)

search_criteria = list(strategy = "RandomDiscrete",
                       stopping_metric = "misclassification",
                       max_models = 10000,
                       max_runtime_secs = 72000,
                       stopping_tolerance = 0.00001,
                       stopping_rounds = 10)

grid_model = h2o.grid(algorithm = "deeplearning",
                      grid_id = "mygrid",
                      hyper_params = hyperparams,
                      search_criteria = search_criteria,
                      x = 1:4,
                      y = 5,
                      training_frame = train,
                      validation_frame = valid,
                      variable_importances = TRUE,
                      balance_classes=TRUE,
                      score_training_samples=1000,
                      score_validation_samples=1000,
                      score_validation_sampling="Stratified",
                      epochs = 1000000,
                      seed = 7)

cat("\n\n3. Summary of grid_model---------------------------------------------------------\n")
grid = h2o.getGrid("mygrid", sort_by="auc", decreasing=TRUE)
summary(grid)

cat("\n\n4. Performance of best_model-----------------------------------------------------\n")
best_model = h2o.getModel(grid@model_ids[[1]])

results("5.best_model", best_model)

cat("\n\n6. Performance valid dataset-----------------------------------------------------\n")
perf_valid = h2o.performance(model = best_model, newdata = valid)
perf_valid

cat("\n\n7. Performance on test dataset---------------------------------------------------\n")
perf_test = h2o.performance(model = best_model, newdata = test)
perf_test

plot(perf_test, type="roc")     # Plot the roc curve

predicted <- h2o.predict( best_model, test )
actual = test[,5]
cat("\n\n8. Mean prediction on the test set: ", 100*mean( predicted$predict == actual ), "%\n")
correct = predicted == actual
numCorrect = as.integer(sum(correct))
ntotal = as.integer(nrow(correct))
percent = round(numCorrect/ntotal*100, 2)
printf("9. Test of Mean prediction on the test set: %d/%d (%f)", numCorrect, ntotal, percent)
cat("\n\n10. The 'test' set auc is: ", h2o.auc(perf_test), "\n")

p = h2o.saveModel(best_model, path = "C:\\sm\\Trending\\h2o_model", force = TRUE)
p

minutes = (proc.time() - ptm)[1]
printf("Elapsed time: %.2f minutes", minutes)

unlink("log.txt")
sink.reset()

My log is:

 Connection successful!

R is connected to the H2O cluster:
    H2O cluster uptime:         9 minutes 35 seconds
    H2O cluster version:        3.10.4.8
    H2O cluster version age:    14 days, 4 hours and 1 minute
    H2O cluster name:           H2O_started_from_R_Charles_huu844
    H2O cluster total nodes:    1
    H2O cluster total memory:   21.31 GB
    H2O cluster total cores:    8
    H2O cluster allowed cores:  8
    H2O cluster healthy:        TRUE
    H2O Connection ip:          localhost
    H2O Connection port:        54321
    H2O Connection proxy:       NA
    H2O Internal Security:      FALSE
    R Version:                  R version 3.2.2 (2015-08-14)

[1] 0
[1] "//bigsur/sm/Trending/model.csv"
        Date Symbol BuyIndex SellIndex BoxRatio  Thrust Acceleration Velocity nPosVelo
1   4/5/2017 GBX         132       199   77.724 49.7190     107.5811   2.9236       59
2   1/5/2017 RH          216       259    4.838  4.8380     137.0574   0.3381       14
3  9/28/2016 DDS         149       444    0.150  0.4860      99.1360   0.1081       59
4 11/25/2016 JKS         132       186    0.932  0.8686      38.9931   0.6057       59
5 12/12/2016 JNUG        132       177    0.582  0.3242      87.1144   1.1274       18
6   3/7/2017 LPL         134       180    8.954  8.9540      34.1691   0.4778       59
  OnBalRun vwapGain    Gain Altitude
1  12.6378  90.0656 -0.1659       no
2   1.5157   0.9495 -0.6496       no
3   0.5476   2.2887  4.1439      yes
4   3.2719   3.8235  0.5051       no
5   2.5006  12.0472 -0.8942       no
6   2.9935   1.1234 -0.1617       no
   Thrust Velocity OnBalRun vwapGain Altitude
1 49.7190   2.9236  12.6378  90.0656       no
2  4.8380   0.3381   1.5157   0.9495       no
3  0.4860   0.1081   0.5476   2.2887      yes
4  0.8686   0.6057   3.2719   3.8235       no
5  0.3242   1.1274   2.5006  12.0472       no
6  8.9540   0.4778   2.9935   1.1234       no
     Thrust Velocity OnBalRun vwapGain Altitude
4427 0.9370   0.3176   1.2786   2.3151       no
3079 2.2060   0.9261   1.1257   1.2506       no
3952 0.0702   0.4430   1.1485   0.9928       no
7765 1.1596   1.1067   6.2563   2.1164      yes
1682 0.6708   0.4519   1.3848   2.1808       no
5145 4.5600   0.3462   1.7386   0.7722       no
[1] "train----------------------------------------"
  Thrust Velocity OnBalRun vwapGain Altitude
1 2.2060   0.9261   1.1257   1.2506       no
2 0.6708   0.4519   1.3848   2.1808       no
3 4.5600   0.3462   1.7386   0.7722       no
4 3.6930   3.2778  11.4092  49.3335       no
5 0.9980   0.4035   1.6667   1.1264       no
6 0.2016   0.5627   2.4101   1.2642       no
  Thrust Velocity OnBalRun vwapGain Altitude
1 2.2060   0.9261   1.1257   1.2506       no
2 0.6708   0.4519   1.3848   2.1808       no
3 4.5600   0.3462   1.7386   0.7722       no
4 3.6930   3.2778  11.4092  49.3335       no
5 0.9980   0.4035   1.6667   1.1264       no
6 0.2016   0.5627   2.4101   1.2642       no

[5548 rows x 5 columns]
[1] "valid----------------------------------------"
  Thrust Velocity OnBalRun vwapGain Altitude
1 0.9370   0.3176   1.2786   2.3151       no
2 0.0702   0.4430   1.1485   0.9928       no
3 1.0230   0.3119   3.0922   0.8788       no
4 6.4100   0.9966   5.3490   2.9436      yes
5 6.9620   0.7004   3.5810   4.8905       no
6 1.6800   1.4518   5.1933   1.7955       no

[1875 rows x 5 columns]
[1] "test-----------------------------------------"
  Thrust Velocity OnBalRun vwapGain Altitude
1 1.1596   1.1067   6.2563   2.1164      yes
2 4.7010   0.5369   1.1266   7.5566       no
3 1.7110   0.9247   3.5819   3.0598       no
4 1.4620   0.3315   4.3097   0.4129       no
5 0.5610   0.4494   1.8738   1.3942       no
6 6.7255   1.7309   5.6268   4.4937      yes

[1823 rows x 5 columns]

1. Summary of train dataset------------------------------------------------------
 Thrust               Velocity          OnBalRun           vwapGain           Altitude
 Min.   :   -1.4845   Min.   :-0.1241   Min.   : -0.5299   Min.   : -4.7648    no :4875
 1st Qu.:    0.3984   1st Qu.: 0.3281   1st Qu.:  1.1468   1st Qu.:  0.8684    yes: 671
 Median :    1.0425   Median : 0.3815   Median :  1.6439   Median :  1.9954       :   2
 Mean   :   12.1332   Mean   : 0.5913   Mean   :  2.5911   Mean   :  4.8876
 3rd Qu.:    1.9723   3rd Qu.: 0.5716   3rd Qu.:  2.6507   3rd Qu.:  4.7500
 Max.   :41279.8960   Max.   :29.4449   Max.   :154.5988   Max.   :314.7143
 NA's   :2            NA's   :2         NA's   :2          NA's   :2

2. Grid Search on valid data ----------------------------------------------------

3. Summary of grid_model---------------------------------------------------------

ERROR: Unexpected HTTP Status code: 412 Precondition Failed (url = http://localhost:54321/99/Grids/mygrid?sort_by=auc&decreasing=TRUE)

water.exceptions.H2OIllegalArgumentException
 [1] "water.exceptions.H2OIllegalArgumentException: Invalid argument for sort_by specified. Must be one of: [r2, mean_per_class_accuracy, max_per_class_error, err, total_rows, rmse, accuracy, err_count, logloss, mse, mean_per_class_error]"
 [2] "    hex.schemas.GridSchemaV99.fillFromImpl(GridSchemaV99.java:114)"
 [3] "    water.api.GridsHandler.fetch(GridsHandler.java:41)"
 [4] "    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)"
 [5] "    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)"
 [6] "    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)"
 [7] "    java.lang.reflect.Method.invoke(Method.java:498)"
 [8] "    water.api.Handler.handle(Handler.java:61)"
 [9] "    water.api.RequestServer.serve(RequestServer.java:436)"
[10] "    water.api.RequestServer.doGeneric(RequestServer.java:285)"
[11] "    water.api.RequestServer.doGet(RequestServer.java:220)"
[12] "    javax.servlet.http.HttpServlet.service(HttpServlet.java:735)"
[13] "    javax.servlet.http.HttpServlet.service(HttpServlet.java:848)"
[14] "    org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:684)"
[15] "    org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:503)"
[16] "    org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1086)"
[17] "    org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:429)"
[18] "    org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1020)"
[19] "    org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:135)"
[20] "    org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:154)"
[21] "    org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:116)"
[22] "    water.JettyHTTPD$LoginHandler.handle(JettyHTTPD.java:417)"
[23] "    org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:154)"
[24] "    org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:116)"
[25] "    org.eclipse.jetty.server.Server.handle(Server.java:370)"
[26] "    org.eclipse.jetty.server.AbstractHttpConnection.handleRequest(AbstractHttpConnection.java:494)"
[27] "    org.eclipse.jetty.server.BlockingHttpConnection.handleRequest(BlockingHttpConnection.java:53)"
[28] "    org.eclipse.jetty.server.AbstractHttpConnection.headerComplete(AbstractHttpConnection.java:971)"
[29] "    org.eclipse.jetty.server.AbstractHttpConnection$RequestHandler.headerComplete(AbstractHttpConnection.java:1033)"
[30] "    org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:644)"
[31] "    org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:235)"
[32] "    org.eclipse.jetty.server.BlockingHttpConnection.handle(BlockingHttpConnection.java:72)"
[33] "    org.eclipse.jetty.server.bio.SocketConnector$ConnectorEndPoint.run(SocketConnector.java:264)"
[34] "    org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:608)"
[35] "    org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:543)"
[36] "    java.lang.Thread.run(Thread.java:745)"

4. Performance of best_model-----------------------------------------------------

6. Performance valid dataset-----------------------------------------------------

7. Performance on test dataset---------------------------------------------------
Called from: sprintf(...)
[1] "Elapsed time: 85.98 minutes"

Please help.

Charles


来源: stackexchange

问:
Importing an instantiated class sets global prototype
Given the following react component, I am able to import the following component from multiple components. I'm confused on why after importing into each module and calling increment, it will increment the value as if it were the same instance. I don't think it's attached to the 'window', because I did some inspection.

Could this be, because this sets a global prototype? That still doesn't explain why it's seemingly updating the same instantiated class.

```<code>import React, { Component } from 'react';

class FeatureFlags extends Component {
  constructor (props) {
    super (props);
    this.featureFlagList = [ 'test': true ];
    this.i = 0;
  }

  get showFeatureFlagList () {
    return this.featureFlagList;
  }

  increment () {
    this.i++;
    return this.i;
  }

  setList (list) {
    this.featureFlagList = list;
    return this.featureFlagList;
  }

  render () {
    return (
      <div></div>
    );
  }
}

export default new FeatureFlags;

//First component -
import FeatureFlags from './FeatureFlags';
console.log('first module ',  FeatureFlags.increment() );  //Logs 1

//Second component
import FeatureFlags from './FeatureFlags';
console.log('second module ',  FeatureFlags.increment() );  //Logs 2
</code>```

答:
No, it's because you

```<code>export default new FeatureFlags;
</code>```

That's one single instance! Importing the module multiple times will always import the same value.

Instead, you should always export the class:

```<code>export default class FeatureFlags extends Component { … }
</code>```

and instantiate it in the other modules as often as you need it:

```<code>import FeatureFlags from './FeatureFlags';
const myLocalFlags = new FeatureFlags;
console.log('first module ', myLocalFlags.increment());  //Logs 1
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Given the following react component, I am able to import the following component from multiple components. I'm confused on why after importing into each module and calling increment, it will increment the value as if it were the same instance. I don't think it's attached to the 'window', because I did some inspection.

Could this be, because this sets a global prototype? That still doesn't explain why it's seemingly updating the same instantiated class.

import React, { Component } from 'react';

class FeatureFlags extends Component {
  constructor (props) {
    super (props);
    this.featureFlagList = [ 'test': true ];
    this.i = 0;
  }

  get showFeatureFlagList () {
    return this.featureFlagList;
  }

  increment () {
    this.i++;
    return this.i;
  }

  setList (list) {
    this.featureFlagList = list;
    return this.featureFlagList;
  }

  render () {
    return (

    );
  }
}

export default new FeatureFlags;

//First component -
import FeatureFlags from './FeatureFlags';
console.log('first module ',  FeatureFlags.increment() );  //Logs 1

//Second component
import FeatureFlags from './FeatureFlags';
console.log('second module ',  FeatureFlags.increment() );  //Logs 2

Body:
No, it's because you

export default new FeatureFlags;

That's one single instance! Importing the module multiple times will always import the same value.

Instead, you should always export the class:

export default class FeatureFlags extends Component { … }

and instantiate it in the other modules as often as you need it:

import FeatureFlags from './FeatureFlags';
const myLocalFlags = new FeatureFlags;
console.log('first module ', myLocalFlags.increment());  //Logs 1


问:
Return a pointer to 2D array from a function - C++
So what I am trying to achieve is to return a pointer to a 2D array from the function so it could accessed in main(). I know there are some C++ libraries that does it for you like std::vector but I am trying to avoid dynamic memory allocation since I am working on embedded board (STM32) so I will stick to just normal pointers and arrays. (ALSO for some reason I can't use std::array in KEIL uVision, which is also why I am forced to work with pointers/arrays)

In addition, I understand that returning a pointer to a local array int arr[2][2] defined inside the function is not a good idea since it will no longer be valid after the function returns, which is why I creating test_array, declaring it inside a class and defining it in a function (acting as a global variable) so I assume this shouldn't be a problem. What do you guys think? However, doing it this way gives an error "Excess elements in scalar initializer"

```<code>#include <iostream>
#include "file.hpp"

int main() {

  myClass class_object;

  class_object.value = class_object.foo();

}
</code>```

```<code>//file.hpp

#include <stdio.h>

class myClass{

  int array[2][2];
  int (*foo())[2];
  int (*value)[2];

  int test_array[2][2];   //declaring here!

};
</code>```

```<code>//file.cpp

#include "file.hpp"

int (*myClass::foo())[2]{

    test_array[2][2]={ {10,20}, {30, 40} }; //defining here - ERROR!!

    int arr[2][2]= {
        {1, 10},
        {20, 30}
    };

return arr;

}
</code>```

答:
If you really want to work with C-Array, use typedef to have normal syntax:

```<code>class myClass{
    public:
    using array2 = int[2][2];

    myClass() {
        test_array[0][0] = 0;
        test_array[0][1] = 1;
        test_array[1][0] = 2;
        test_array[1][1] = 3;
    }

    const array2& getArray() const { return test_array; }
    array2& getArray() { return test_array; }

private:
    array2 test_array;
};
</code>```

Body:
So what I am trying to achieve is to return a pointer to a 2D array from the function so it could accessed in main(). I know there are some C++ libraries that does it for you like std::vector but I am trying to avoid dynamic memory allocation since I am working on embedded board (STM32) so I will stick to just normal pointers and arrays. (ALSO for some reason I can't use std::array in KEIL uVision, which is also why I am forced to work with pointers/arrays)

In addition, I understand that returning a pointer to a local array int arr[2][2] defined inside the function is not a good idea since it will no longer be valid after the function returns, which is why I creating test_array, declaring it inside a class and defining it in a function (acting as a global variable) so I assume this shouldn't be a problem. What do you guys think? However, doing it this way gives an error "Excess elements in scalar initializer"

#include <iostream>
#include "file.hpp"

int main() {

  myClass class_object;

  class_object.value = class_object.foo();

}

//file.hpp

#include <stdio.h>

class myClass{

  int array[2][2];
  int (*foo())[2];
  int (*value)[2];

  int test_array[2][2];   //declaring here!

};

//file.cpp

#include "file.hpp"

int (*myClass::foo())[2]{

    test_array[2][2]={ {10,20}, {30, 40} }; //defining here - ERROR!!

    int arr[2][2]= {
        {1, 10},
        {20, 30}
    };

return arr;

}

Body:
If you really want to work with C-Array, use typedef to have normal syntax:

class myClass{
    public:
    using array2 = int[2][2];

    myClass() {
        test_array[0][0] = 0;
        test_array[0][1] = 1;
        test_array[1][0] = 2;
        test_array[1][1] = 3;
    }

    const array2& getArray() const { return test_array; }
    array2& getArray() { return test_array; }

private:
    array2 test_array;
};


问:
Tooltip not appearing?
Looking around, it seems that the general consensus for adding a Tooltip is through the Tooltip#install method:

```<code>Tooltip.install(button, new Tooltip("This is a tooltip"));
</code>```

However, binding this to a button doesn't seem to do anything of the sort.

I'm using JavaFX scene builder and the button I want to have a tooltip added to is configured in my Controller class through @FXML tags.

This is the button in action:

How does one go about adding a tooltip, then?

答:
Borrowing from one of a duplicate question's answer:

```<code>Button btn = new Button("Step");
btn.setTooltip(new Tooltip("This is a tooltip"));
</code>```

As for the time it takes for the Tooltip to appear:

Typically, the tooltip is "activated" when the mouse moves over a
  Control. There is usually some delay between when the Tooltip becomes
  "activated" and when it is actually shown. The details (such as the
  amount of delay, etc) is left to the Skin implementation.

Taken from https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/Tooltip.html

Title: Tooltip not appearing?

Body:
Looking around, it seems that the general consensus for adding a Tooltip is through the Tooltip#install method:

Tooltip.install(button, new Tooltip("This is a tooltip"));

However, binding this to a button doesn't seem to do anything of the sort.

I'm using JavaFX scene builder and the button I want to have a tooltip added to is configured in my Controller class through @FXML tags.

This is the button in action:

How does one go about adding a tooltip, then?

Body:
Borrowing from one of a duplicate question's answer:

Button btn = new Button("Step");
btn.setTooltip(new Tooltip("This is a tooltip"));

As for the time it takes for the Tooltip to appear:

Typically, the tooltip is "activated" when the mouse moves over a
  Control. There is usually some delay between when the Tooltip becomes
  "activated" and when it is actually shown. The details (such as the
  amount of delay, etc) is left to the Skin implementation.

Taken from https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/Tooltip.html


问:
SQL count rows of one table in relation to another table
I have 3 different tables :

Client

```<code>+----+-----------+----------+
| id | firstName | lastName |
+----+-----------+----------+
|  1 | John      | Doe      |
|  2 | Jane      | Doe      |
+----+-----------+----------+
</code>```

Loan

```<code>+----+--------+-----------+----------------+
| id | amount | client_id | institution_id |
+----+--------+-----------+----------------+
|  1 |    200 |         2 |              3 |
|  2 |    400 |         1 |              1 |
+----+--------+-----------+----------------+
</code>```

Institution

```<code>+----+---------------+
| id |     name      |
+----+---------------+
|  1 | Institution A |
|  2 | Institution B |
|  3 | Institution C |
+----+---------------+
</code>```

I am looking to create a list of the number of loans a client has with each institution (for every row in the institution table). Including when a client has 0 loans with an institution.

Something that looks like :

```<code>+-----------+-----------+----------+--------------------------+-----------+
| client_id | firstName | lastName | financialInstitutionName | loanCount |
+-----------+-----------+----------+--------------------------+-----------+
|         1 | John      | Doe      | Institution A            |         1 |
|         1 | John      | Doe      | Institution B            |         0 |
|         1 | John      | Doe      | Institution C            |         0 |
|         2 | Jane      | Doe      | Institution A            |         0 |
|         2 | Jane      | Doe      | Institution B            |         0 |
|         2 | Jane      | Doe      | Institution C            |         1 |
+-----------+-----------+----------+--------------------------+-----------+
</code>```

I have tried all manners of joins, subqueries and where clauses but without success. The concept that I do not grasp is how to get a row per institution, per client (total count institution x client). I would love if that query was possible without subqueries or union joins.

Thank you for your time!

答:
First subquery in the FROM setups that data so each client has a record for each of the institutions.  This is then joined to a subquery that counts the number of loans.

```<code>SELECT
    d.client_id,
    d.firstName,
    d.lastName,
    d.name AS financialInstitutionName,
    CASE WHEN l IS NULL
        THEN 0
        ELSE l.loanCount
    END AS loanCount

FROM
(
    SELECT
        Client.id AS client_id,
        Client.firstName,
        Client.lastName,
        Institution.id AS institution_id,
        Institution.name
    FROM Client, Institution
) AS d

LEFT JOIN (
    SELECT client_id, institution_id, COUNT(id) AS loanCount
    FROM Loan
    GROUP BY client_id, institution_id
) AS l ON d.client_id = l.client_id AND d.institution_id = l.institution_id
</code>```

Edit: Includes a record for each institution

Edit: Spelling

Body:
I have 3 different tables :

Client

+----+-----------+----------+
| id | firstName | lastName |
+----+-----------+----------+
|  1 | John      | Doe      |
|  2 | Jane      | Doe      |
+----+-----------+----------+

Loan

+----+--------+-----------+----------------+
| id | amount | client_id | institution_id |
+----+--------+-----------+----------------+
|  1 |    200 |         2 |              3 |
|  2 |    400 |         1 |              1 |
+----+--------+-----------+----------------+

Institution

+----+---------------+
| id |     name      |
+----+---------------+
|  1 | Institution A |
|  2 | Institution B |
|  3 | Institution C |
+----+---------------+

I am looking to create a list of the number of loans a client has with each institution (for every row in the institution table). Including when a client has 0 loans with an institution.

Something that looks like :

+-----------+-----------+----------+--------------------------+-----------+
| client_id | firstName | lastName | financialInstitutionName | loanCount |
+-----------+-----------+----------+--------------------------+-----------+
|         1 | John      | Doe      | Institution A            |         1 |
|         1 | John      | Doe      | Institution B            |         0 |
|         1 | John      | Doe      | Institution C            |         0 |
|         2 | Jane      | Doe      | Institution A            |         0 |
|         2 | Jane      | Doe      | Institution B            |         0 |
|         2 | Jane      | Doe      | Institution C            |         1 |
+-----------+-----------+----------+--------------------------+-----------+

I have tried all manners of joins, subqueries and where clauses but without success. The concept that I do not grasp is how to get a row per institution, per client (total count institution x client). I would love if that query was possible without subqueries or union joins.

Thank you for your time!

Body:
First subquery in the FROM setups that data so each client has a record for each of the institutions.  This is then joined to a subquery that counts the number of loans.

SELECT
    d.client_id,
    d.firstName,
    d.lastName,
    d.name AS financialInstitutionName,
    CASE WHEN l IS NULL
        THEN 0
        ELSE l.loanCount
    END AS loanCount

FROM
(
    SELECT
        Client.id AS client_id,
        Client.firstName,
        Client.lastName,
        Institution.id AS institution_id,
        Institution.name
    FROM Client, Institution
) AS d

LEFT JOIN (
    SELECT client_id, institution_id, COUNT(id) AS loanCount
    FROM Loan
    GROUP BY client_id, institution_id
) AS l ON d.client_id = l.client_id AND d.institution_id = l.institution_id

Edit: Includes a record for each institution

Edit: Spelling


问:
Why does adding a second column to a dataframe prohibit usage of loc to set an array as a value?
If I create a dataframe with a single column

```<code>a = pd.DataFrame({'x': [np.array([1,2,3,4]), np.array([1,2,3])]})
</code>```

then reassign the value of the first row

```<code>a.loc[0, 'x'] = a.loc[0, 'x']
</code>```

a.loc[0, 'x'] is unchanged. All is well!

However, if I add a second column

```<code>a = pd.DataFrame({'x': [np.array([1,2,3,4]), np.array([1,2,3])], 'y':[1,2]})
</code>```

then a.loc[0, 'x'] = a.loc[0, 'x'] throws the error:

ValueError: Must have equal len keys and value when setting with an iterable

Can someone explain what I'm doing wrong here? I've found a solution here: i.e. use set_value instead of loc, but I'd like to know why loc doesn't work.

Also, is this an appropriate usage of the pandas DataFrame? I have a bunch of vectors x that I would like to associate with some other variables and an index, and a DataFrame seemed to be the best way to store them and run operations on them (df.apply works very well to perform operations in bulk on these arrays!).

Body:
If I create a dataframe with a single column

a = pd.DataFrame({'x': [np.array([1,2,3,4]), np.array([1,2,3])]})

then reassign the value of the first row

a.loc[0, 'x'] = a.loc[0, 'x']

a.loc[0, 'x'] is unchanged. All is well!

However, if I add a second column

a = pd.DataFrame({'x': [np.array([1,2,3,4]), np.array([1,2,3])], 'y':[1,2]})

then a.loc[0, 'x'] = a.loc[0, 'x'] throws the error:

ValueError: Must have equal len keys and value when setting with an iterable

Can someone explain what I'm doing wrong here? I've found a solution here: i.e. use set_value instead of loc, but I'd like to know why loc doesn't work.

Also, is this an appropriate usage of the pandas DataFrame? I have a bunch of vectors x that I would like to associate with some other variables and an index, and a DataFrame seemed to be the best way to store them and run operations on them (df.apply works very well to perform operations in bulk on these arrays!).

Body:
You can use set_value:

a.set_value(0,'x',a.loc[0, 'x'])
Out[619]:
              x  y
0  [1, 2, 3, 4]  1
1     [1, 2, 3]  2


问:
Delphi ARC under Firemonkey for Windows
I am watching this video where Marco is talking about Automatic Reference Counting. I already knew that under Android and iOS (Firemonkey) my objects are ref counted so I don't need the try finally block.

Does the reference count implementation work according with the platform (VLC or FMX) or with the OS?

What I mean is:

```<code>var a: TObject;
begin
 a := TObject.Create;
 a.use1;
 a.use2;
end;
</code>```

This is good in Firemonkey if it runs on Android/iOS/Mac, I have no memory leak. But if I ran this under Windows (and I have used Firemonkey) do I still have the memory leak due to no ref count?

Anyway from the video I have understood that a try finally with a call of Free, even under ARC, is not bad usage but it's just useless.

答:
The reference count ARC is something very confusing under delphi, and it's make development much more harder that it's must be because it is badly designed (under delphi).

First it's build in RTL, and it's quite similar to what you have with String. it's work on plateform (firemonkey) and also on OS (work only on android/ios/unix). So if you want to build multi plateform code that target also window (most probable, a least just to debug you code) you will anyway need to keep the try ... finally .. end; (yes i say you, very bad design). so forget about your example without .free except if you want to debug under mobile (and good luck with 3 min compilation everytime, it's simply not possible)

NOTE: To keep you code compatible as most as possible a good rule to acquire is to replace all you .free by .disposeOF followed by nil because under mobile, free is a no-ops operation and you object is not destroyed, and can be destroyed at a very unexpected time (or simply never be destroyed in worst case, quite common if you use for example TTask). these scenarios are not so rare, especially if you use often anonymous procedure (reference to procedure) that create in the background capture to your object.

Always keep in mind that circular ref are quite easy to meet and quite
  hard to detect

.

after you must know also (you didn't ask, but i extend a little the answer) that their is delphi Tobject, java object, IOS objective C object and Interface. All have their own rules and confuse everyone and at the end no-one really know how it's work (yes part of the badly design of ARC is also the confusion it's gave), even emb developer do mistake in their delphi source code, look for exemple this question: delphi + ios: release / retain and reference counting with objective-c object that is quite trivial, but without any answer

ARC and Objective-C wrapped objects

Delphi NextGen compiler implements automatic reference counting (ARC) for all Delphi objects. The compiler will manage the logic to TObject’s __ObjAddRef and __ObjRelease for you. Objective-C code uses the same logic to call retain and release. Unfortunately there is no ARC for the Objective-C objects represented by the import wrapper class and the interfaces discussed above. When dealing with Objective-C objects you’ll have to call retain and release yourself at the correct points.

ARC and JAVA object

On the paper it's must work, but personally i don't trust it, for exemple if you do in loop :

```<code>for i := 0 to 100000 do begin
  aJstring := StringToJstring('a text');
  aStr := JstringToString(aJstring);
end;
</code>```

normally this must run without any trouble in a normal world, but under delphi, it's will crash :( but anyway here you don't have .release so you don't have choice (except assigning the variable to nil). But when you have choice this why i recommend always to use .disposeOF followed by nil, you will probably win days/weeks/month of development escaping some nasty bug.

NOTE: i call this function when i want to destroy an object:

```<code>{******************************}
Procedure ALFreeAndNil(var Obj);
var Temp: TObject;
begin
  Temp := TObject(Obj);
  if temp = nil then exit;
  TObject(Obj) := nil;

    {$IF defined(AUTOREFCOUNT)}
    if AtomicCmpExchange(temp.refcount{Target}, 0{NewValue}, 0{Compareand}) = 1 then begin // it's seam it's not an atomic operation (http://stackoverflow.com/questions/39987850/is-reading-writing-an-integer-4-bytes-atomic-on-ios-android-like-on-win32-win6)
      temp.Free;
      temp := nil;
    end
    else begin
      Temp.DisposeOf; // TComponent Free Notification mechanism notifies registered components that particular
                      // component instance is being freed. Notified components can handle that notification inside
                      // virtual Notification method and make sure that they clear all references they may hold on
                      // component being destroyed.
                      //
                      // Free Notification mechanism is being triggered in TComponent destructor and without DisposeOf
                      // and direct execution of destructor, two components could hold strong references to each
                      // other keeping themselves alive during whole application lifetime.
      {$IF defined(DEBUG)}
        if (Temp.RefCount - 1) and (not $40000000{Temp.objDisposedFlag}) <> 0 then
          ALLog('ALFreeAndNil', Temp.ClassName + ' | Refcount is not null (' + Inttostr((Temp.RefCount - 1) and (not $40000000{Temp.objDisposedFlag})) + ')', TalLogType.warn);
      {$IFEND}
      temp := nil;
    end;
    {$ELSE}
    temp.Free;
    temp := nil;
    {$IFEND}

end;
</code>```

In this way, if the refcount is not 0 after calling ALFreeAndNil, then it's generate a warning in the log (under debug) and you can investigate

Title: Delphi ARC under Firemonkey for Windows

Body:
I am watching this video where Marco is talking about Automatic Reference Counting. I already knew that under Android and iOS (Firemonkey) my objects are ref counted so I don't need the try finally block.

Does the reference count implementation work according with the platform (VLC or FMX) or with the OS?

What I mean is:

var a: TObject;
begin
 a := TObject.Create;
 a.use1;
 a.use2;
end;

This is good in Firemonkey if it runs on Android/iOS/Mac, I have no memory leak. But if I ran this under Windows (and I have used Firemonkey) do I still have the memory leak due to no ref count?

Anyway from the video I have understood that a try finally with a call of Free, even under ARC, is not bad usage but it's just useless.

Body:
The reference count ARC is something very confusing under delphi, and it's make development much more harder that it's must be because it is badly designed (under delphi).

First it's build in RTL, and it's quite similar to what you have with String. it's work on plateform (firemonkey) and also on OS (work only on android/ios/unix). So if you want to build multi plateform code that target also window (most probable, a least just to debug you code) you will anyway need to keep the try ... finally .. end; (yes i say you, very bad design). so forget about your example without .free except if you want to debug under mobile (and good luck with 3 min compilation everytime, it's simply not possible)

NOTE: To keep you code compatible as most as possible a good rule to acquire is to replace all you .free by .disposeOF followed by nil because under mobile, free is a no-ops operation and you object is not destroyed, and can be destroyed at a very unexpected time (or simply never be destroyed in worst case, quite common if you use for example TTask). these scenarios are not so rare, especially if you use often anonymous procedure (reference to procedure) that create in the background capture to your object.

Always keep in mind that circular ref are quite easy to meet and quite
  hard to detect

.

after you must know also (you didn't ask, but i extend a little the answer) that their is delphi Tobject, java object, IOS objective C object and Interface. All have their own rules and confuse everyone and at the end no-one really know how it's work (yes part of the badly design of ARC is also the confusion it's gave), even emb developer do mistake in their delphi source code, look for exemple this question: delphi + ios: release / retain and reference counting with objective-c object that is quite trivial, but without any answer

ARC and Objective-C wrapped objects

Delphi NextGen compiler implements automatic reference counting (ARC) for all Delphi objects. The compiler will manage the logic to TObject’s __ObjAddRef and __ObjRelease for you. Objective-C code uses the same logic to call retain and release. Unfortunately there is no ARC for the Objective-C objects represented by the import wrapper class and the interfaces discussed above. When dealing with Objective-C objects you’ll have to call retain and release yourself at the correct points.

ARC and JAVA object

On the paper it's must work, but personally i don't trust it, for exemple if you do in loop :

for i := 0 to 100000 do begin
  aJstring := StringToJstring('a text');
  aStr := JstringToString(aJstring);
end;

normally this must run without any trouble in a normal world, but under delphi, it's will crash :( but anyway here you don't have .release so you don't have choice (except assigning the variable to nil). But when you have choice this why i recommend always to use .disposeOF followed by nil, you will probably win days/weeks/month of development escaping some nasty bug.

NOTE: i call this function when i want to destroy an object:

{******************************}
Procedure ALFreeAndNil(var Obj);
var Temp: TObject;
begin
  Temp := TObject(Obj);
  if temp = nil then exit;
  TObject(Obj) := nil;

    {$IF defined(AUTOREFCOUNT)}
    if AtomicCmpExchange(temp.refcount{Target}, 0{NewValue}, 0{Compareand}) = 1 then begin // it's seam it's not an atomic operation (http://stackoverflow.com/questions/39987850/is-reading-writing-an-integer-4-bytes-atomic-on-ios-android-like-on-win32-win6)
      temp.Free;
      temp := nil;
    end
    else begin
      Temp.DisposeOf; // TComponent Free Notification mechanism notifies registered components that particular
                      // component instance is being freed. Notified components can handle that notification inside
                      // virtual Notification method and make sure that they clear all references they may hold on
                      // component being destroyed.
                      //
                      // Free Notification mechanism is being triggered in TComponent destructor and without DisposeOf
                      // and direct execution of destructor, two components could hold strong references to each
                      // other keeping themselves alive during whole application lifetime.
      {$IF defined(DEBUG)}
        if (Temp.RefCount - 1) and (not $40000000{Temp.objDisposedFlag}) <> 0 then
          ALLog('ALFreeAndNil', Temp.ClassName + ' | Refcount is not null (' + Inttostr((Temp.RefCount - 1) and (not $40000000{Temp.objDisposedFlag})) + ')', TalLogType.warn);
      {$IFEND}
      temp := nil;
    end;
    {$ELSE}
    temp.Free;
    temp := nil;
    {$IFEND}

end;

In this way, if the refcount is not 0 after calling ALFreeAndNil, then it's generate a warning in the log (under debug) and you can investigate


问:
Behavior of Array.prototype.slice with strings in an Array
The MDN page on Array#slice states:

For strings, numbers and booleans (not String, Number and Boolean
  objects), slice copies the values into the new array. Changes to the
  string, number or boolean in one array do not affect the other array.

Surely string literals, being reference types (admittedly with a value semantic), are not copied. Instead a reference is copied?

答:
No, string literals are considered primitive types in JavaScript, just like numbers.

See MDN - Strings # Distinction between string primitives and String objects


答:
String literals produce immutable primitive values. Those are not reference values.

That strings might be implemented with shared references to character arrays in JS engines is just that, an implementation detail. As you say yourself, strings do have value semantics in JS, and that's all what matters.

Title: Behavior of Array.prototype.slice with strings in an Array

Body:
The MDN page on Array#slice states:

For strings, numbers and booleans (not String, Number and Boolean
  objects), slice copies the values into the new array. Changes to the
  string, number or boolean in one array do not affect the other array.

Surely string literals, being reference types (admittedly with a value semantic), are not copied. Instead a reference is copied?


问:
Piping (redirecting input from a text file) into a Java program using DrJava
I'm piping a text file into a java program. This is what the text file "input.txt" holds:

```<code>4
5
</code>```

That is, the numbers 4 and 5 in seperated lines. I want the program to read those numbers and print them out. This code should work:

```<code>public class readFile {
  public static void main(String[] args) {

    while (!StdIn.isEmpty()) {
      System.out.println( StdIn.readInt() );
    }
  }
}
</code>```

But when I do the following in DrJava:

```<code>run readFile < input.txt
</code>```

I don't get

```<code>4
5
</code>```

but I get a box asking me for input instead of printing the numbers out: http://oi50.tinypic.com/3585kxc.jpg

What am I doing wrong?

答:
To pipe a text file into a java program using Dr Java, you need to read the file from standard input by using the class edu.princeton.cs.algs4.In. Your code would have to look like this:

```<code>import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.StdOut;

public class readFile {
  public static void main(String[] args) {
    //Read file
    In in = new In(args[0]);
    while (!in.isEmpty()) {
      StdOut.println( in.readInt() );
    }
  }
}
</code>```

In this way, you won't get the box asking you for an input.

Body:
I'm piping a text file into a java program. This is what the text file "input.txt" holds:

4
5

That is, the numbers 4 and 5 in seperated lines. I want the program to read those numbers and print them out. This code should work:

public class readFile {
  public static void main(String[] args) {

    while (!StdIn.isEmpty()) {
      System.out.println( StdIn.readInt() );
    }
  }
}

But when I do the following in DrJava:

run readFile < input.txt

I don't get

4
5

but I get a box asking me for input instead of printing the numbers out: http://oi50.tinypic.com/3585kxc.jpg

What am I doing wrong?

Body:
To pipe a text file into a java program using Dr Java, you need to read the file from standard input by using the class edu.princeton.cs.algs4.In. Your code would have to look like this:

import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.StdOut;

public class readFile {
  public static void main(String[] args) {
    //Read file
    In in = new In(args[0]);
    while (!in.isEmpty()) {
      StdOut.println( in.readInt() );
    }
  }
}

In this way, you won't get the box asking you for an input.


问:
How do you remove last comma in a PHP for loop to build a JSON string
When building a JSON string from a php for loop from an SQL query there is an unnessary comma at the end of the build string. How do I control the final comma.

```<code>$count =  label::grabAll()->count();

echo '{"data": { "graph": {';

for ($x = 0; $x < $count; $x++){

if($x <= 3){
    $cm = ',';
}else{
    $cm .= '';
}

    echo '"'.$x.'": "'.label::grabAll()->results()[$x]->count.'"'.$cm;

}
</code>```

I get this result from the code above.

How do I remove the final comma?

答:
```<code>$count =  label::graball()->count();

$arr = array();

for ($x = 0; $x < $count; $x++){

 array_push($arr, label::graball()->results()[$x]->count);

}

echo json_encode($arr);
</code>```

<p>Thanks everyone for the quick responses. This works. </p>

Body:
When building a JSON string from a php for loop from an SQL query there is an unnessary comma at the end of the build string. How do I control the final comma.

$count =  label::grabAll()->count();

echo '{"data": { "graph": {';

for ($x = 0; $x < $count; $x++){

if($x <= 3){
    $cm = ',';
}else{
    $cm .= '';
}

    echo '"'.$x.'": "'.label::grabAll()->results()[$x]->count.'"'.$cm;

}

I get this result from the code above.

How do I remove the final comma?

Body:
$count =  label::graball()->count();

$arr = array();

for ($x = 0; $x < $count; $x++){

 array_push($arr, label::graball()->results()[$x]->count);

}

echo json_encode($arr);

Thanks everyone for the quick responses. This works.


问:
Auto height and the float issue
I have had this issue before and can't remember if and how I fixed it.

I have to create a scenario where I have 2 DIV's floated left and right inside a parent DIV. The 2 floating DIV's have height:auto, but the parent ignores them (perfectly logical) and the background of the parent DIV can't be seen. I know what the issue is, but are there any suggestions of how to solve it? Or any alternatives, I am willing to try a new approach.

Thanks in advance for any help.

答:
I know , it's tooo late to answer this question but anyone who is coming here after me can benefit from this answer.

USE
 display: inline-flex
instead of floats and be happy.

Note : you'll need to check for the support of inline-flex value

ContentLicense: CC BY-SA 2.5

Title: Auto height and the float issue


问:
"Warning: Do not place Android context classes in static fields; this is a memory leak (and also breaks Instant Run)"
Similar question have been asked here, here and here but the context  is quite different from this and moreover the code that gave from this error is written by the makers of Android and Android Studio.

This is the code:

```<code>public class MySingleton {
    private static MySingleton mInstance;
    private RequestQueue mRequestQueue;
    private ImageLoader mImageLoader;
    private static Context mCtx;

    private MySingleton(Context context) {
        mCtx = context;
        mRequestQueue = getRequestQueue();

        mImageLoader = new ImageLoader(mRequestQueue,
                new ImageLoader.ImageCache() {
            private final LruCache<String, Bitmap>
                    cache = new LruCache<String, Bitmap>(20);

            @Override
            public Bitmap getBitmap(String url) {
                return cache.get(url);
            }

            @Override
            public void putBitmap(String url, Bitmap bitmap) {
                cache.put(url, bitmap);
            }
        });
    }

    public static synchronized MySingleton getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new MySingleton(context);
        }
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            // getApplicationContext() is key, it keeps you from leaking the
            // Activity or BroadcastReceiver if someone passes one in.
            mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
        }
        return mRequestQueue;
    }

    public <T> void addToRequestQueue(Request<T> req) {
        getRequestQueue().add(req);
    }

    public ImageLoader getImageLoader() {
        return mImageLoader;
    }
}
</code>```

The lines giving the warning are:

```<code>private static MySingleton mInstance;
private static Context mCtx;
</code>```

Now if I remove the static keyword, change public static synchronized MySingleton getInstance(Context... to public synchronized MySingleton getInstance(Context... the error disappers but another problem comes up.

I use MySingleton in RecyclerView. So this line

@Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
        ImageLoader imageLoader = MySingleton.getInstance(mContext).getImageLoader();

tells me

Non-static method 'getInstance(android.content.Context)' cannot be refrenced from a static context.

Please anybody knows how to fix this?

答:
I ended up putting this in AppController which has no warning.

```<code>public class AppController extends MultiDexApplication {

    public static Context getContext() {
        return mInstance.getApplicationContext();
    }

    private static AppController mInstance;

    public static synchronized AppController getInstance() {
        return mInstance;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        mInstance = this;

    }
}
</code>```

So whenever you need it just call AppController.getContext()

Body:
Similar question have been asked here, here and here but the context  is quite different from this and moreover the code that gave from this error is written by the makers of Android and Android Studio.

This is the code:

public class MySingleton {
    private static MySingleton mInstance;
    private RequestQueue mRequestQueue;
    private ImageLoader mImageLoader;
    private static Context mCtx;

    private MySingleton(Context context) {
        mCtx = context;
        mRequestQueue = getRequestQueue();

        mImageLoader = new ImageLoader(mRequestQueue,
                new ImageLoader.ImageCache() {
            private final LruCache<String, Bitmap>
                    cache = new LruCache<String, Bitmap>(20);

            @Override
            public Bitmap getBitmap(String url) {
                return cache.get(url);
            }

            @Override
            public void putBitmap(String url, Bitmap bitmap) {
                cache.put(url, bitmap);
            }
        });
    }

    public static synchronized MySingleton getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new MySingleton(context);
        }
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            // getApplicationContext() is key, it keeps you from leaking the
            // Activity or BroadcastReceiver if someone passes one in.
            mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
        }
        return mRequestQueue;
    }

    public <T> void addToRequestQueue(Request<T> req) {
        getRequestQueue().add(req);
    }

    public ImageLoader getImageLoader() {
        return mImageLoader;
    }
}

The lines giving the warning are:

private static MySingleton mInstance;
private static Context mCtx;

Now if I remove the static keyword, change public static synchronized MySingleton getInstance(Context... to public synchronized MySingleton getInstance(Context... the error disappers but another problem comes up.

I use MySingleton in RecyclerView. So this line

@Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
        ImageLoader imageLoader = MySingleton.getInstance(mContext).getImageLoader();

tells me

Non-static method 'getInstance(android.content.Context)' cannot be refrenced from a static context.

Please anybody knows how to fix this?

Body:
I ended up putting this in AppController which has no warning.

public class AppController extends MultiDexApplication {

    public static Context getContext() {
        return mInstance.getApplicationContext();
    }

    private static AppController mInstance;

    public static synchronized AppController getInstance() {
        return mInstance;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        mInstance = this;

    }
}

So whenever you need it just call AppController.getContext()


问:
cannot get deepwater to run on MBP with TF
I am trying to run to get R + deepwater + tensorflow to work on a MBP.

The following have been installed.

```<code>Python 3.6.1
TensorFlow 1.1
</code>```

The Hello, TensorFlow example on the TensorFlow website is working fine.

```<code>R version 3.4.0

curl -O http://h2o-release.s3.amazonaws.com/h2o/master/3904/R/src/contrib/h2o_3.11.0.3904.tar.gz
R CMD INSTALL h2o_3.11.0.3904.tar.gz

curl -O http://s3.amazonaws.com/h2o-deepwater/public/nightly/latest/h2o_3.11.0.tar.gz
R CMD INSTALL h2o_3.11.0.tar.gz
</code>```

I am trying run the following example provided on the h2o website.

```<code>require(h2o)

h2o.init()

train <- h2o.importFile("https://h2o-public-test-data.s3.amazonaws.com/bigdata/laptop/mnist/train.csv.gz")

target <- "C785"
features <- setdiff(names(train), target)

train[target] <- as.factor(train[target])

model <- h2o.deepwater(x=features, y=target, training_frame=train, epochs=100, activation="Rectifier",
    hidden=c(200,200), ignore_const_cols=FALSE, mini_batch_size=256, input_dropout_ratio=0.1,
    hidden_dropout_ratios=c(0.5,0.5), stopping_rounds=3, stopping_tolerance=0.05,
    stopping_metric="misclassification", score_interval=2, score_duty_cycle=0.5, score_training_samples=1000,
    score_validation_samples=1000, nfolds=5, gpu=FALSE, seed=1234, backend="tensorflow")
</code>```

The error I get is Error: java.lang.RuntimeException: Unable to initialize backend: Cannot find TensorFlow native library for OS: darwin, architecture: x86_64.  Based on what I read on SO and the git page, I was under the impression that one does not need to build for the Mac platform.

One other thing that I tried was to use the info from https://github.com/rstudio/tensorflow.  When I run install_tensorflow() I get Error: Prerequisites for installing TensorFlow not available.  Please help!

答:
We don't provide H2O+deepwater builds for MacOS. The one you downloaded is built for Linux machines (tested on Ubuntu), it's mentioned on the download page.

If you want to run it on MacOS you'd have to build both DeepWater and then H2O yourself.

Body:
I am trying to run to get R + deepwater + tensorflow to work on a MBP.

The following have been installed.

Python 3.6.1
TensorFlow 1.1

The Hello, TensorFlow example on the TensorFlow website is working fine.

R version 3.4.0

curl -O http://h2o-release.s3.amazonaws.com/h2o/master/3904/R/src/contrib/h2o_3.11.0.3904.tar.gz
R CMD INSTALL h2o_3.11.0.3904.tar.gz

curl -O http://s3.amazonaws.com/h2o-deepwater/public/nightly/latest/h2o_3.11.0.tar.gz
R CMD INSTALL h2o_3.11.0.tar.gz

I am trying run the following example provided on the h2o website.

require(h2o)

h2o.init()

train <- h2o.importFile("https://h2o-public-test-data.s3.amazonaws.com/bigdata/laptop/mnist/train.csv.gz")

target <- "C785"
features <- setdiff(names(train), target)

train[target] <- as.factor(train[target])

model <- h2o.deepwater(x=features, y=target, training_frame=train, epochs=100, activation="Rectifier",
    hidden=c(200,200), ignore_const_cols=FALSE, mini_batch_size=256, input_dropout_ratio=0.1,
    hidden_dropout_ratios=c(0.5,0.5), stopping_rounds=3, stopping_tolerance=0.05,
    stopping_metric="misclassification", score_interval=2, score_duty_cycle=0.5, score_training_samples=1000,
    score_validation_samples=1000, nfolds=5, gpu=FALSE, seed=1234, backend="tensorflow")

The error I get is Error: java.lang.RuntimeException: Unable to initialize backend: Cannot find TensorFlow native library for OS: darwin, architecture: x86_64.  Based on what I read on SO and the git page, I was under the impression that one does not need to build for the Mac platform.

One other thing that I tried was to use the info from https://github.com/rstudio/tensorflow.  When I run install_tensorflow() I get Error: Prerequisites for installing TensorFlow not available.  Please help!


问:
How do I get my Flex box nav to resize to a smaller height for mobile
So I have a simple flexbox layout made up of a parent element that contains two children elements.  The first child element (.child1) represents my menu, it's on the left, taking up about 0.125 of my viewport and spanning the entire height of the parent element.  The second child element (.child2) represents my content, it takes up the remainder of the width of the page.

I have it set up for when the viewport shrinks to a point were .child2 hits it's flex-basis of 400px it wraps below and the page layout becomes a psuedo "column" style layout. When .child2 wraps,  I want the height of .child1 to shrink to something like 50px and or a height more suitable for mobile nav. However, in my code, when the viewport gets down to mobile size, both child elements take up equal amounts of height.

how do I shrink .child1 's height when the elements are wrapping but have it full height when the elements are not wrapping?

*if it's possible to do this without media queries that would be ideal.

.parentContainer {
  display: flex;
  flex-wrap: wrap;
  background-color: LightCoral;
  padding: 20px;
  height: 100vh;
  max-width: 100vw;
  align-content: stretch;
  align-items: stretch;
  justify-content: flex-start;
}

.child1 {
  background-color: DarkTurquoise;
  flex: 2 2 100px;
}

.child2 {
  background-color: DodgerBlue;
  flex: 20 1 400px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parentContainer">
  <div class="childContainer child1">
  </div>
  <div class="childContainer child2">
  </div>
</div></code>```

答:
Its quite simple..

change the flex basis from px to %

Such as:

```<code>.child1 {
background-color: DarkTurquoise;
flex: 2 2 25%;
}

.child2 {
background-color: DodgerBlue;
flex: 20 1 75%;
}
</code>```

Then add in this simple media query..

```<code>@media (max-width:768px) {
.parentContainer{  flex-direction: column}
}
</code>```

This will swap things round but keep similar proportions..

If, of course you decide you want a bigger or smaller Nav in Mobile.

You can add the following to the media query..

```<code>@media (max-width:768px) {
.child1{
flex-basis: 50%
}
.child2{
flex-basis: 50%
}
 }
</code>```

Body:
Its quite simple..

change the flex basis from px to %

Such as:

.child1 {
background-color: DarkTurquoise;
flex: 2 2 25%;
}

.child2 {
background-color: DodgerBlue;
flex: 20 1 75%;
}

Then add in this simple media query..

@media (max-width:768px) {
.parentContainer{  flex-direction: column}
}

This will swap things round but keep similar proportions..

If, of course you decide you want a bigger or smaller Nav in Mobile.

You can add the following to the media query..

@media (max-width:768px) {
.child1{
flex-basis: 50%
}
.child2{
flex-basis: 50%
}
 }


问:
Can I programmatically update a wix.com website?
I have a wix.com website with a number of sections including a blog. Each day I have a number of Python scripts that run and generate dynamic content. Mostly in tabular form. Like so:

```<code>2017-03-21  306.67  2017-05-17  308.16  closed  0.49 %
2017-04-13  305.45  2017-05-17  308.16  closed  0.89 %
2017-05-17  308.16  2017-06-02  311.88  open    3.43 %
</code>```

Currently we are cutting and pasting the content, but I would like to update the blog section of the site automatically each day when the scripts run. Is there a way to do this? Python would be my language of choice, but I am open to any workable solution.

答:
It appears that there is a work around using either the wix.com table app or their Google Docs app. Either of those appear to automatically update based on changes a Google doc. The update cycle appears to be every five minutes. Here is a local thread on programmatically updating Google Docs.

Programatically updating a spreadsheet hosted on google docs

This seems like a long way around, but it may work.

https://www.wix.com/app-market/table-master/overview
https://www.wix.com/app-market/google-docs/overview

I'll test this and circle back.

ContentLicense: CC BY-SA 4.0

Body:
I have a wix.com website with a number of sections including a blog. Each day I have a number of Python scripts that run and generate dynamic content. Mostly in tabular form. Like so:

2017-03-21  306.67  2017-05-17  308.16  closed  0.49 %
2017-04-13  305.45  2017-05-17  308.16  closed  0.89 %
2017-05-17  308.16  2017-06-02  311.88  open    3.43 %

Currently we are cutting and pasting the content, but I would like to update the blog section of the site automatically each day when the scripts run. Is there a way to do this? Python would be my language of choice, but I am open to any workable solution.


问:
How can I convert this for loop pseudocode into Python code without inducing infinite recursion?
I would like to turn the following pseudocode into Python code without inducing infinite recursion.

```<code>u(x) = x^2

for i = 0 to 5
v(x) = u(x)^2
u(x) = v(x)

print(u(x))
</code>```

Here is my attempt, which produces the error "maximum recursion depth exceeded":

```<code>import sympy as sym

u = lambda a: a**2

for i in range(0,5):
  print('Starting loop',i)
  v = lambda b: u(b)**2
  u = lambda c: v(c)
  print('Ending loop',i)

x = sym.symbols('x')
print(u(x))
</code>```

答:
Try using these two lines:

```<code>v = lambda b, u=u: u(b)**2
u = lambda c, v=v: v(c)
</code>```

This forces the values of u and v to be captured at the moment of lambda construction. Otherwise, the evaluation will be deferred until the lambdas are invoked.

Here is the complete program:

```<code>import sympy as sym

u = lambda a: a**2

for i in range(0,5):
  print('Starting loop',i)
  v = lambda b, u=u: u(b)**2
  u = lambda c, v=v: v(c)
  print('Ending loop',i)

x = sym.symbols('x')
print(u(x))
</code>```

And here is the result:

```<code>$ python3 xx.py
Starting loop 0
Ending loop 0
Starting loop 1
Ending loop 1
Starting loop 2
Ending loop 2
Starting loop 3
Ending loop 3
Starting loop 4
Ending loop 4
x**64
</code>```

Body:
I would like to turn the following pseudocode into Python code without inducing infinite recursion.

u(x) = x^2

for i = 0 to 5
v(x) = u(x)^2
u(x) = v(x)

print(u(x))

Here is my attempt, which produces the error "maximum recursion depth exceeded":

import sympy as sym

u = lambda a: a**2

for i in range(0,5):
  print('Starting loop',i)
  v = lambda b: u(b)**2
  u = lambda c: v(c)
  print('Ending loop',i)

x = sym.symbols('x')
print(u(x))

Body:
Try using these two lines:

v = lambda b, u=u: u(b)**2
u = lambda c, v=v: v(c)

This forces the values of u and v to be captured at the moment of lambda construction. Otherwise, the evaluation will be deferred until the lambdas are invoked.

Here is the complete program:

import sympy as sym

u = lambda a: a**2

for i in range(0,5):
  print('Starting loop',i)
  v = lambda b, u=u: u(b)**2
  u = lambda c, v=v: v(c)
  print('Ending loop',i)

x = sym.symbols('x')
print(u(x))

And here is the result:

$ python3 xx.py
Starting loop 0
Ending loop 0
Starting loop 1
Ending loop 1
Starting loop 2
Ending loop 2
Starting loop 3
Ending loop 3
Starting loop 4
Ending loop 4
x**64


问:
Does Scipy have techniques to import&export optimisation model files such as LP?
I am trying to manage problems from Scipy. So does Scipy provide techniques to import and export model files?</p>

答: No as Sascha mentioned in the comment. Use other alternatives such as cvxpy/cvxopt.</p>


问:
@Input property is undefined
I have 2 components one of them sets input property of another component.
The problem is that the input property is undefined at time of use.

First component:

```<code>import {Component, Input, OnInit} from "@angular/core";
import {Comparison} from "../../../common/domain/comparison";
@Component({
    selector: 'oe-comparison-list',
        template: `<div class="row" *ngFor="let comparisons of comparisonRows">
    <oe-comparison-thumbnail *ngFor="let comparison of comparisons" [comparison]="comparison"></oe-comparison-thumbnail>
</div>`,
    styleUrls: ['./comparison-list.component.css']
})
export class ComparisonListComponent implements OnInit {

    @Input("comparisons")
    private comparisons: Array<Comparison>;
    private comparisonRows: Array<Array<Comparison>>;
    private static readonly COLUMNS: number = 4;

    constructor() {
    }

    ngOnInit(): void {
        this.rows();
    }

    private rows(): void {
        //todo
        this.comparisonRows = [];
        let comparisonArray = [];
        for (let i: number = 0; i < this.comparisons.length; ++i) {
            if (i == 0 || i % ComparisonListComponent.COLUMNS != 0) {
                comparisonArray.push(this.comparisons[i]);
            } else {
                this.comparisonRows.push(comparisonArray);
                comparisonArray = [];
            }
        }
        if (this.comparisons.length < ComparisonListComponent.COLUMNS) {
            this.comparisonRows.push(comparisonArray);
        }
    }
}
</code>```

Second component

```<code>import {AfterViewChecked, Component, Inject, OnInit} from "@angular/core";
import {Comparison} from "../../../common/domain/comparison";
import {IComparisonService} from "../../../common/services/icomparison.service";
@Component({
    selector: 'oe-comparisons-view',
    template: `<oe-comparison-list [comparisons]="comparisons"></oe-comparison-list>`,
    styleUrls: ['./comparisons-view.component.css']
})
export class ComparisonsViewComponent implements AfterViewChecked, OnInit {

    private comparisons: Array<Comparison>;

    constructor(@Inject('IComparisonService') private comparisonService: IComparisonService) {

    }

    ngOnInit(): void {
        this.comparisonService.fetchComparisons()
            .then(comparisons => this.comparisons = comparisons);
    }
    ngAfterViewChecked(): void {
    }
}
</code>```

If i pass simple array from ngOnInit() from second component without promise everything works just fine.
How can i resolve this problem?

ADDED
Service implementation

```<code>import {Injectable} from '@angular/core';
import {Comparison} from "../../../domain/comparison";
import {IComparisonService} from "../../icomparison.service";

@Injectable()
export class ComparisonServiceMock implements IComparisonService {

    private selectedComparison: Comparison;

    constructor() {
    }

    fetchComparisons(): Promise<Array<Comparison>> {
        let comparison: Array<Comparison> = [
            new Comparison(0, "Toys", "Toys comparison description", new Date(), "toys"),
            new Comparison(1, "Tablets", "Tablets comparison description", new Date(), "tablets"),
            new Comparison(2, "Jogurts", "Jogurts comparison description", new Date(), "jogurts"),
        ];
        return Promise.resolve(comparison);
    }

    selectComparison(comparison: Comparison): void {
        this.selectedComparison = comparison;
    }

    getSelectedComparison(): Comparison {
        return this.selectedComparison;
    }

}
</code>```

答:
Please try following changes in your second component

```<code>import {AfterViewChecked, Component, Inject, OnInit} from "@angular/core";
import {Comparison} from "../../../common/domain/comparison";
import {IComparisonService} from "../../../common/services/icomparison.service";
@Component({
    selector: 'oe-comparisons-view',
    template: `<oe-comparison-list [comparisons]="comparisons" *ngIf="!isLoading"></oe-comparison-list>`,
    styleUrls: ['./comparisons-view.component.css']
})
export class ComparisonsViewComponent implements AfterViewChecked, OnInit {

    private comparisons: Array<Comparison>;
    private isLoading: boolean = true;

    constructor(@Inject('IComparisonService') private comparisonService: IComparisonService) {

    }

    ngOnInit(): void {
        this.comparisonService.fetchComparisons()
            .then(comparisons => {
              this.comparisons = comparisons;
              this.isLoading = false;
            });
    }
    ngAfterViewChecked(): void {
    }
}
</code>```

You can read this 3 Ways to Pass Async Data to Angular 2+ Child Components to know more about the problem.

Title: @Input property is undefined

Body:
I have 2 components one of them sets input property of another component.
The problem is that the input property is undefined at time of use.

First component:

import {Component, Input, OnInit} from "@angular/core";
import {Comparison} from "../../../common/domain/comparison";
@Component({
    selector: 'oe-comparison-list',
        template: `

    <oe-comparison-thumbnail *ngFor="let comparison of comparisons" [comparison]="comparison"></oe-comparison-thumbnail>

`,
    styleUrls: ['./comparison-list.component.css']
})
export class ComparisonListComponent implements OnInit {

    @Input("comparisons")
    private comparisons: Array<Comparison>;
    private comparisonRows: Array<Array<Comparison>>;
    private static readonly COLUMNS: number = 4;

    constructor() {
    }

    ngOnInit(): void {
        this.rows();
    }

    private rows(): void {
        //todo
        this.comparisonRows = [];
        let comparisonArray = [];
        for (let i: number = 0; i < this.comparisons.length; ++i) {
            if (i == 0 || i % ComparisonListComponent.COLUMNS != 0) {
                comparisonArray.push(this.comparisons[i]);
            } else {
                this.comparisonRows.push(comparisonArray);
                comparisonArray = [];
            }
        }
        if (this.comparisons.length < ComparisonListComponent.COLUMNS) {
            this.comparisonRows.push(comparisonArray);
        }
    }
}

Second component

import {AfterViewChecked, Component, Inject, OnInit} from "@angular/core";
import {Comparison} from "../../../common/domain/comparison";
import {IComparisonService} from "../../../common/services/icomparison.service";
@Component({
    selector: 'oe-comparisons-view',
    template: `<oe-comparison-list [comparisons]="comparisons"></oe-comparison-list>`,
    styleUrls: ['./comparisons-view.component.css']
})
export class ComparisonsViewComponent implements AfterViewChecked, OnInit {

    private comparisons: Array<Comparison>;

    constructor(@Inject('IComparisonService') private comparisonService: IComparisonService) {

    }

    ngOnInit(): void {
        this.comparisonService.fetchComparisons()
            .then(comparisons => this.comparisons = comparisons);
    }
    ngAfterViewChecked(): void {
    }
}

If i pass simple array from ngOnInit() from second component without promise everything works just fine.
How can i resolve this problem?

ADDED
Service implementation

import {Injectable} from '@angular/core';
import {Comparison} from "../../../domain/comparison";
import {IComparisonService} from "../../icomparison.service";

@Injectable()
export class ComparisonServiceMock implements IComparisonService {

    private selectedComparison: Comparison;

    constructor() {
    }

    fetchComparisons(): Promise<Array<Comparison>> {
        let comparison: Array<Comparison> = [
            new Comparison(0, "Toys", "Toys comparison description", new Date(), "toys"),
            new Comparison(1, "Tablets", "Tablets comparison description", new Date(), "tablets"),
            new Comparison(2, "Jogurts", "Jogurts comparison description", new Date(), "jogurts"),
        ];
        return Promise.resolve(comparison);
    }

    selectComparison(comparison: Comparison): void {
        this.selectedComparison = comparison;
    }

    getSelectedComparison(): Comparison {
        return this.selectedComparison;
    }

}

Body:
Please try following changes in your second component

import {AfterViewChecked, Component, Inject, OnInit} from "@angular/core";
import {Comparison} from "../../../common/domain/comparison";
import {IComparisonService} from "../../../common/services/icomparison.service";
@Component({
    selector: 'oe-comparisons-view',
    template: `<oe-comparison-list [comparisons]="comparisons" *ngIf="!isLoading"></oe-comparison-list>`,
    styleUrls: ['./comparisons-view.component.css']
})
export class ComparisonsViewComponent implements AfterViewChecked, OnInit {

    private comparisons: Array<Comparison>;
    private isLoading: boolean = true;

    constructor(@Inject('IComparisonService') private comparisonService: IComparisonService) {

    }

    ngOnInit(): void {
        this.comparisonService.fetchComparisons()
            .then(comparisons => {
              this.comparisons = comparisons;
              this.isLoading = false;
            });
    }
    ngAfterViewChecked(): void {
    }
}

You can read this 3 Ways to Pass Async Data to Angular 2+ Child Components to know more about the problem.