问:
Extract all model statistics from rms fits?
The rms package contains a wealth of useful statistical functions. However, I cannot find a proper way to extract certain fit statistics from the fitted object. Consider an example:

```<code>library(pacman)
p_load(rms, stringr, readr)

#fit
> (fit = rms::ols(Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width + Species, data = iris))
Linear Regression Model

 rms::ols(formula = Sepal.Length ~ Sepal.Width + Petal.Length +
     Petal.Width + Species, data = iris)

                Model Likelihood     Discrimination
                   Ratio Test           Indexes
 Obs     150    LR chi2    302.96    R2       0.867
 sigma0.3068    d.f.            5    R2 adj   0.863
 d.f.    144    Pr(> chi2) 0.0000    g        0.882

 Residuals

       Min        1Q    Median        3Q       Max
 -0.794236 -0.218743  0.008987  0.202546  0.731034

                    Coef    S.E.   t     Pr(>|t|)
 Intercept           2.1713 0.2798  7.76 <0.0001
 Sepal.Width         0.4959 0.0861  5.76 <0.0001
 Petal.Length        0.8292 0.0685 12.10 <0.0001
 Petal.Width        -0.3152 0.1512 -2.08 0.0389
 Species=versicolor -0.7236 0.2402 -3.01 0.0031
 Species=virginica  -1.0235 0.3337 -3.07 0.0026
</code>```

So, the print function for the fit prints a lot of useful stuff including standard errors and adjusted R2. Unfortunately, if we inspect the model fit object, the values don't seem to be present anywhere.

```<code>> str(fit)
List of 19
 $ coefficients     : Named num [1:6] 2.171 0.496 0.829 -0.315 -0.724 ...
  ..- attr(*, "names")= chr [1:6] "Intercept" "Sepal.Width" "Petal.Length" "Petal.Width" ...
 $ residuals        : Named num [1:150] 0.0952 0.1432 -0.0731 -0.2894 -0.0544 ...
  ..- attr(*, "names")= chr [1:150] "1" "2" "3" "4" ...
 $ effects          : Named num [1:150] -71.5659 -1.1884 9.1884 -1.3724 -0.0587 ...
  ..- attr(*, "names")= chr [1:150] "Intercept" "Sepal.Width" "Petal.Length" "Petal.Width" ...
 $ rank             : int 6
 $ fitted.values    : Named num [1:150] 5 4.76 4.77 4.89 5.05 ...
  ..- attr(*, "names")= chr [1:150] "1" "2" "3" "4" ...
 $ assign           :List of 4
  ..$ Sepal.Width : int 2
  ..$ Petal.Length: int 3
  ..$ Petal.Width : int 4
  ..$ Species     : int [1:2] 5 6
 $ qr               :List of 5
  ..$ qr   : num [1:150, 1:6] -12.2474 0.0816 0.0816 0.0816 0.0816 ...
  .. ..- attr(*, "dimnames")=List of 2
  .. .. ..$ : chr [1:150] "1" "2" "3" "4" ...
  .. .. ..$ : chr [1:6] "Intercept" "Sepal.Width" "Petal.Length" "Petal.Width" ...
  ..$ qraux: num [1:6] 1.08 1.02 1.11 1.02 1.02 ...
  ..$ pivot: int [1:6] 1 2 3 4 5 6
  ..$ tol  : num 1e-07
  ..$ rank : int 6
  ..- attr(*, "class")= chr "qr"
 $ df.residual      : int 144
 $ var              : num [1:6, 1:6] 0.07828 -0.02258 -0.00198 0.01589 -0.02837 ...
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : chr [1:6] "Intercept" "Sepal.Width" "Petal.Length" "Petal.Width" ...
  .. ..$ : chr [1:6] "Intercept" "Sepal.Width" "Petal.Length" "Petal.Width" ...
 $ stats            : Named num [1:6] 150 302.964 5 0.867 0.882 ...
  ..- attr(*, "names")= chr [1:6] "n" "Model L.R." "d.f." "R2" ...
 $ linear.predictors: Named num [1:150] 5 4.76 4.77 4.89 5.05 ...
  ..- attr(*, "names")= chr [1:150] "1" "2" "3" "4" ...
 $ call             : language rms::ols(formula = Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width + Species, data = iris)
 $ terms            :Classes 'terms', 'formula'  language Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width + Species
  .. ..- attr(*, "variables")= language list(Sepal.Length, Sepal.Width, Petal.Length, Petal.Width, Species)
  .. ..- attr(*, "factors")= int [1:5, 1:4] 0 1 0 0 0 0 0 1 0 0 ...
  .. .. ..- attr(*, "dimnames")=List of 2
  .. .. .. ..$ : chr [1:5] "Sepal.Length" "Sepal.Width" "Petal.Length" "Petal.Width" ...
  .. .. .. ..$ : chr [1:4] "Sepal.Width" "Petal.Length" "Petal.Width" "Species"
  .. ..- attr(*, "term.labels")= chr [1:4] "Sepal.Width" "Petal.Length" "Petal.Width" "Species"
  .. ..- attr(*, "order")= int [1:4] 1 1 1 1
  .. ..- attr(*, "intercept")= num 1
  .. ..- attr(*, "response")= int 1
  .. ..- attr(*, ".Environment")=<environment: R_GlobalEnv>
  .. ..- attr(*, "predvars")= language list(Sepal.Length, Sepal.Width, Petal.Length, Petal.Width, Species)
  .. ..- attr(*, "dataClasses")= Named chr [1:5] "numeric" "numeric" "numeric" "numeric" ...
  .. .. ..- attr(*, "names")= chr [1:5] "Sepal.Length" "Sepal.Width" "Petal.Length" "Petal.Width" ...
  .. ..- attr(*, "formula")=Class 'formula'  language Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width + Species
  .. .. .. ..- attr(*, ".Environment")=<environment: R_GlobalEnv>
 $ Design           :List of 12
  ..$ name        : chr [1:4] "Sepal.Width" "Petal.Length" "Petal.Width" "Species"
  ..$ label       : chr [1:4] "Sepal.Width" "Petal.Length" "Petal.Width" "Species"
  ..$ units       : Named chr [1:4] "" "" "" ""
  .. ..- attr(*, "names")= chr [1:4] "Sepal.Width" "Petal.Length" "Petal.Width" "Species"
  ..$ colnames    : chr [1:5] "Sepal.Width" "Petal.Length" "Petal.Width" "Species=versicolor" ...
  ..$ mmcolnames  : chr [1:5] "Sepal.Width" "Petal.Length" "Petal.Width" "Speciesversicolor" ...
  ..$ assume      : chr [1:4] "asis" "asis" "asis" "category"
  ..$ assume.code : int [1:4] 1 1 1 5
  ..$ parms       :List of 1
  .. ..$ Species: chr [1:3] "setosa" "versicolor" "virginica"
  ..$ limits      : list()
  ..$ values      : list()
  ..$ nonlinear   :List of 4
  .. ..$ Sepal.Width : logi FALSE
  .. ..$ Petal.Length: logi FALSE
  .. ..$ Petal.Width : logi FALSE
  .. ..$ Species     : logi [1:2] FALSE FALSE
  ..$ interactions: NULL
 $ non.slopes       : num 1
 $ na.action        : NULL
 $ scale.pred       : chr "Sepal.Length"
 $ fail             : logi FALSE
 $ sformula         :Class 'formula'  language Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width + Species
  .. ..- attr(*, ".Environment")=<environment: R_GlobalEnv>
 - attr(*, "class")= chr [1:3] "ols" "rms" "lm"
</code>```

There is a 7 year old question on R help where the package creator explains a solution to getting these:

On Wed, 11 Aug 2010, david dav wrote:

Hi,
    I would like to extract the coefficients of a logistic regression
    (estimates and standard error as well) in lrm as in glm with

summary(fit.glm)$coef

Thanks
    David

coef(fit) sqrt(diag(vcov(fit)))

But these will not be very helpful except in the trivial case where
  everything is linear, nothing interacts, and factors have two levels.

Frank

And the solution is according to the author not optimal. This leaves one wondering how the displayed values are calculated. Tracing down the code results in a hunt through the undocumented package code (the package code is on Github). I.e. we begin with print.ols():

```<code>> rms:::print.ols
function (x, digits = 4, long = FALSE, coefs = TRUE, title = "Linear Regression Model",
    ...)
{
    latex <- prType() == "latex"
    k <- 0
    z <- list()
    if (length(zz <- x$na.action)) {
        k <- k + 1
        z[[k]] <- list(type = paste("naprint", class(zz)[1],
            sep = "."), list(zz))
    }
    stats <- x$stats
...
</code>```

Reading further we do find that e.g. R2 adj. is calculated in the print function:

```<code>rsqa <- 1 - (1 - r2) * (n - 1) / rdf
</code>```

We also find some standard error calculations, though no p values.

```<code>  se <- sqrt(diag(x$var))
  z[[k]] <- list(type='coefmatrix',
                 list(coef    = x$coefficients,
                      se      = se,
                      errordf = rdf))
</code>```

All the results are passed down further to prModFit(). We can look it up and find the p value calculation etc. Unfortunately, the print command returns NULL so these values are not available anywhere for programmatic reuse:

```<code>> x = print((fit = rms::ols(Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width + Species, data = iris)))
#printed output...
> x
NULL
</code>```

How does one get all the statistics?

答:
Package broom is a great way to extract model info.

```<code>library(pacman)
library(rms)
library(broom)

fit = ols(Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width + Species,
               data = iris)

tidy(summary.lm(fit))

#                 term   estimate  std.error statistic      p.value
# 1          Intercept  2.1712663 0.27979415  7.760227 1.429502e-12
# 2        Sepal.Width  0.4958889 0.08606992  5.761466 4.867516e-08
# 3       Petal.Length  0.8292439 0.06852765 12.100867 1.073592e-23
# 4        Petal.Width -0.3151552 0.15119575 -2.084418 3.888826e-02
# 5 Species=versicolor -0.7235620 0.24016894 -3.012721 3.059634e-03
# 6  Species=virginica -1.0234978 0.33372630 -3.066878 2.584344e-03

glance(fit)

#   r.squared adj.r.squared     sigma statistic      p.value df    logLik      AIC      BIC df.residual
# 1 0.8673123      0.862705 0.3068261   188.251 2.666942e-61  6 -32.55801 79.11602 100.1905         144
</code>```

The object fit also contains some easily accessible info that you can get and store in a dataframe:

```<code>fit$coefficients

# Intercept        Sepal.Width       Petal.Length        Petal.Width Species=versicolor  Species=virginica
# 2.1712663          0.4958889          0.8292439         -0.3151552         -0.7235620         -1.0234978

fit$stats

#           n  Model L.R.        d.f.          R2           g       Sigma
# 150.0000000 302.9635115   5.0000000   0.8673123   0.8820479   0.3068261
</code>```

Body:
The rms package contains a wealth of useful statistical functions. However, I cannot find a proper way to extract certain fit statistics from the fitted object. Consider an example:

library(pacman)
p_load(rms, stringr, readr)

#fit
> (fit = rms::ols(Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width + Species, data = iris))
Linear Regression Model

 rms::ols(formula = Sepal.Length ~ Sepal.Width + Petal.Length +
     Petal.Width + Species, data = iris)

                Model Likelihood     Discrimination
                   Ratio Test           Indexes
 Obs     150    LR chi2    302.96    R2       0.867
 sigma0.3068    d.f.            5    R2 adj   0.863
 d.f.    144    Pr(> chi2) 0.0000    g        0.882

 Residuals

       Min        1Q    Median        3Q       Max
 -0.794236 -0.218743  0.008987  0.202546  0.731034

                    Coef    S.E.   t     Pr(>|t|)
 Intercept           2.1713 0.2798  7.76 <0.0001
 Sepal.Width         0.4959 0.0861  5.76 <0.0001
 Petal.Length        0.8292 0.0685 12.10 <0.0001
 Petal.Width        -0.3152 0.1512 -2.08 0.0389
 Species=versicolor -0.7236 0.2402 -3.01 0.0031
 Species=virginica  -1.0235 0.3337 -3.07 0.0026

So, the print function for the fit prints a lot of useful stuff including standard errors and adjusted R2. Unfortunately, if we inspect the model fit object, the values don't seem to be present anywhere.

> str(fit)
List of 19
 $ coefficients     : Named num [1:6] 2.171 0.496 0.829 -0.315 -0.724 ...
  ..- attr(*, "names")= chr [1:6] "Intercept" "Sepal.Width" "Petal.Length" "Petal.Width" ...
 $ residuals        : Named num [1:150] 0.0952 0.1432 -0.0731 -0.2894 -0.0544 ...
  ..- attr(*, "names")= chr [1:150] "1" "2" "3" "4" ...
 $ effects          : Named num [1:150] -71.5659 -1.1884 9.1884 -1.3724 -0.0587 ...
  ..- attr(*, "names")= chr [1:150] "Intercept" "Sepal.Width" "Petal.Length" "Petal.Width" ...
 $ rank             : int 6
 $ fitted.values    : Named num [1:150] 5 4.76 4.77 4.89 5.05 ...
  ..- attr(*, "names")= chr [1:150] "1" "2" "3" "4" ...
 $ assign           :List of 4
  ..$ Sepal.Width : int 2
  ..$ Petal.Length: int 3
  ..$ Petal.Width : int 4
  ..$ Species     : int [1:2] 5 6
 $ qr               :List of 5
  ..$ qr   : num [1:150, 1:6] -12.2474 0.0816 0.0816 0.0816 0.0816 ...
  .. ..- attr(*, "dimnames")=List of 2
  .. .. ..$ : chr [1:150] "1" "2" "3" "4" ...
  .. .. ..$ : chr [1:6] "Intercept" "Sepal.Width" "Petal.Length" "Petal.Width" ...
  ..$ qraux: num [1:6] 1.08 1.02 1.11 1.02 1.02 ...
  ..$ pivot: int [1:6] 1 2 3 4 5 6
  ..$ tol  : num 1e-07
  ..$ rank : int 6
  ..- attr(*, "class")= chr "qr"
 $ df.residual      : int 144
 $ var              : num [1:6, 1:6] 0.07828 -0.02258 -0.00198 0.01589 -0.02837 ...
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : chr [1:6] "Intercept" "Sepal.Width" "Petal.Length" "Petal.Width" ...
  .. ..$ : chr [1:6] "Intercept" "Sepal.Width" "Petal.Length" "Petal.Width" ...
 $ stats            : Named num [1:6] 150 302.964 5 0.867 0.882 ...
  ..- attr(*, "names")= chr [1:6] "n" "Model L.R." "d.f." "R2" ...
 $ linear.predictors: Named num [1:150] 5 4.76 4.77 4.89 5.05 ...
  ..- attr(*, "names")= chr [1:150] "1" "2" "3" "4" ...
 $ call             : language rms::ols(formula = Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width + Species, data = iris)
 $ terms            :Classes 'terms', 'formula'  language Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width + Species
  .. ..- attr(*, "variables")= language list(Sepal.Length, Sepal.Width, Petal.Length, Petal.Width, Species)
  .. ..- attr(*, "factors")= int [1:5, 1:4] 0 1 0 0 0 0 0 1 0 0 ...
  .. .. ..- attr(*, "dimnames")=List of 2
  .. .. .. ..$ : chr [1:5] "Sepal.Length" "Sepal.Width" "Petal.Length" "Petal.Width" ...
  .. .. .. ..$ : chr [1:4] "Sepal.Width" "Petal.Length" "Petal.Width" "Species"
  .. ..- attr(*, "term.labels")= chr [1:4] "Sepal.Width" "Petal.Length" "Petal.Width" "Species"
  .. ..- attr(*, "order")= int [1:4] 1 1 1 1
  .. ..- attr(*, "intercept")= num 1
  .. ..- attr(*, "response")= int 1
  .. ..- attr(*, ".Environment")=<environment: R_GlobalEnv>
  .. ..- attr(*, "predvars")= language list(Sepal.Length, Sepal.Width, Petal.Length, Petal.Width, Species)
  .. ..- attr(*, "dataClasses")= Named chr [1:5] "numeric" "numeric" "numeric" "numeric" ...
  .. .. ..- attr(*, "names")= chr [1:5] "Sepal.Length" "Sepal.Width" "Petal.Length" "Petal.Width" ...
  .. ..- attr(*, "formula")=Class 'formula'  language Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width + Species
  .. .. .. ..- attr(*, ".Environment")=<environment: R_GlobalEnv>
 $ Design           :List of 12
  ..$ name        : chr [1:4] "Sepal.Width" "Petal.Length" "Petal.Width" "Species"
  ..$ label       : chr [1:4] "Sepal.Width" "Petal.Length" "Petal.Width" "Species"
  ..$ units       : Named chr [1:4] "" "" "" ""
  .. ..- attr(*, "names")= chr [1:4] "Sepal.Width" "Petal.Length" "Petal.Width" "Species"
  ..$ colnames    : chr [1:5] "Sepal.Width" "Petal.Length" "Petal.Width" "Species=versicolor" ...
  ..$ mmcolnames  : chr [1:5] "Sepal.Width" "Petal.Length" "Petal.Width" "Speciesversicolor" ...
  ..$ assume      : chr [1:4] "asis" "asis" "asis" "category"
  ..$ assume.code : int [1:4] 1 1 1 5
  ..$ parms       :List of 1
  .. ..$ Species: chr [1:3] "setosa" "versicolor" "virginica"
  ..$ limits      : list()
  ..$ values      : list()
  ..$ nonlinear   :List of 4
  .. ..$ Sepal.Width : logi FALSE
  .. ..$ Petal.Length: logi FALSE
  .. ..$ Petal.Width : logi FALSE
  .. ..$ Species     : logi [1:2] FALSE FALSE
  ..$ interactions: NULL
 $ non.slopes       : num 1
 $ na.action        : NULL
 $ scale.pred       : chr "Sepal.Length"
 $ fail             : logi FALSE
 $ sformula         :Class 'formula'  language Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width + Species
  .. ..- attr(*, ".Environment")=<environment: R_GlobalEnv>
 - attr(*, "class")= chr [1:3] "ols" "rms" "lm"

There is a 7 year old question on R help where the package creator explains a solution to getting these:

On Wed, 11 Aug 2010, david dav wrote:

Hi,
    I would like to extract the coefficients of a logistic regression
    (estimates and standard error as well) in lrm as in glm with

summary(fit.glm)$coef

Thanks
    David

coef(fit) sqrt(diag(vcov(fit)))

But these will not be very helpful except in the trivial case where
  everything is linear, nothing interacts, and factors have two levels.

Frank

And the solution is according to the author not optimal. This leaves one wondering how the displayed values are calculated. Tracing down the code results in a hunt through the undocumented package code (the package code is on Github). I.e. we begin with print.ols():

> rms:::print.ols
function (x, digits = 4, long = FALSE, coefs = TRUE, title = "Linear Regression Model",
    ...)
{
    latex <- prType() == "latex"
    k <- 0
    z <- list()
    if (length(zz <- x$na.action)) {
        k <- k + 1
        z[[k]] <- list(type = paste("naprint", class(zz)[1],
            sep = "."), list(zz))
    }
    stats <- x$stats
...

Reading further we do find that e.g. R2 adj. is calculated in the print function:

rsqa <- 1 - (1 - r2) * (n - 1) / rdf

We also find some standard error calculations, though no p values.

  se <- sqrt(diag(x$var))
  z[[k]] <- list(type='coefmatrix',
                 list(coef    = x$coefficients,
                      se      = se,
                      errordf = rdf))

All the results are passed down further to prModFit(). We can look it up and find the p value calculation etc. Unfortunately, the print command returns NULL so these values are not available anywhere for programmatic reuse:

> x = print((fit = rms::ols(Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width + Species, data = iris)))
#printed output...
> x
NULL

How does one get all the statistics?

Body:
Package broom is a great way to extract model info.

library(pacman)
library(rms)
library(broom)

fit = ols(Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width + Species,
               data = iris)

tidy(summary.lm(fit))

#                 term   estimate  std.error statistic      p.value
# 1          Intercept  2.1712663 0.27979415  7.760227 1.429502e-12
# 2        Sepal.Width  0.4958889 0.08606992  5.761466 4.867516e-08
# 3       Petal.Length  0.8292439 0.06852765 12.100867 1.073592e-23
# 4        Petal.Width -0.3151552 0.15119575 -2.084418 3.888826e-02
# 5 Species=versicolor -0.7235620 0.24016894 -3.012721 3.059634e-03
# 6  Species=virginica -1.0234978 0.33372630 -3.066878 2.584344e-03

glance(fit)

#   r.squared adj.r.squared     sigma statistic      p.value df    logLik      AIC      BIC df.residual
# 1 0.8673123      0.862705 0.3068261   188.251 2.666942e-61  6 -32.55801 79.11602 100.1905         144

The object fit also contains some easily accessible info that you can get and store in a dataframe:

fit$coefficients

# Intercept        Sepal.Width       Petal.Length        Petal.Width Species=versicolor  Species=virginica
# 2.1712663          0.4958889          0.8292439         -0.3151552         -0.7235620         -1.0234978

fit$stats

#           n  Model L.R.        d.f.          R2           g       Sigma
# 150.0000000 302.9635115   5.0000000   0.8673123   0.8820479   0.3068261


来源: stackexchange

问:
structureMap in a multiTier application
I have a asp.net mvc app having three layers
1. dataAccess layer (class library)
2. business layer (class library)
3. web layer (asp.net mvc project)

and also have a domain project (class library for poco)

I am doing the structureMap mappings in my Application_start of the MVC project, but to map the TYPES in dataAccesslayer (for eg. personRepository with IPersonReository) i need the reference of the DAL in my web layer, which i dont think is correct.

What are your suggestions
Thanks

答:
There is nothing wrong in having a reference to the DAL in your web project as long as you are not directly making calls to that assembly. But if you are uncomfortable with that approach, you can use a Registry in your Business layer and there register types for the DAL. Since the Web layer would anyway need to have a reference to the Business layer, you can use that registry from the Business layer in Web's App start

Here is some sample code

The registry class in your Bsns layer

```<code>public class BusinessRegistry:Registry
{
    public BusinessRegistry()
    {
         For<IDALInterface1>().Use<DALImpl1>();
    }
}
</code>```

and in the Application start method

```<code>var container = new Container(x => x.AddRegistry(new BusinessRegistry()));
</code>```

ContentLicense: CC BY-SA 2.5

Title: structureMap in a multiTier application

Body:
There is nothing wrong in having a reference to the DAL in your web project as long as you are not directly making calls to that assembly. But if you are uncomfortable with that approach, you can use a Registry in your Business layer and there register types for the DAL. Since the Web layer would anyway need to have a reference to the Business layer, you can use that registry from the Business layer in Web's App start

Here is some sample code

The registry class in your Bsns layer

public class BusinessRegistry:Registry
{
    public BusinessRegistry()
    {
         For<IDALInterface1>().Use<DALImpl1>();
    }
}

and in the Application start method

var container = new Container(x => x.AddRegistry(new BusinessRegistry()));


问:
Failed to claim interface 0: Device or resource busy
I am trying to communicate with usb device using WEBUSB API. BUT when I am trying to claim Interface it shows

"DOMException: Unable to claim interface"

the bConfigurationvalue is 1 and interface number is 0. I am adding the output of command lsusb -v below

```<code>~$ lsusb -v
Bus 001 Device 005: ID 0930:6544 Toshiba Corp. TransMemory-Mini / Kingston DataTraveler 2.0 Stick (2GB)
Device Descriptor:
  bLength                18
  bDescriptorType         1
  bcdUSB               2.00
  bDeviceClass            0 (Defined at Interface level)
  bDeviceSubClass         0
  bDeviceProtocol         0
  bMaxPacketSize0        64
  idVendor           0x0930 Toshiba Corp.
  idProduct          0x6544 TransMemory-Mini / Kingston DataTraveler 2.0 Stick (2GB)
  bcdDevice            1.00
  iManufacturer           1 TOSHIBA
  iProduct                2 TransMemory
  iSerial                 3 C412F52D6C84CFC0A0012AEF
  bNumConfigurations      1
  Configuration Descriptor:
    bLength                 9
    bDescriptorType         2
    wTotalLength           32
    bNumInterfaces          1
    bConfigurationValue     1
    iConfiguration          0
    bmAttributes         0x80
      (Bus Powered)
    MaxPower              200mA
    Interface Descriptor:
      bLength                 9
      bDescriptorType         4
      bInterfaceNumber        0
      bAlternateSetting       0
      bNumEndpoints           2
      bInterfaceClass         8 Mass Storage
      bInterfaceSubClass      6 SCSI
      bInterfaceProtocol     80 Bulk-Only
      iInterface              0
      Endpoint Descriptor:
        bLength                 7
        bDescriptorType         5
        bEndpointAddress     0x81  EP 1 IN
        bmAttributes            2
          Transfer Type            Bulk
          Synch Type               None
          Usage Type               Data
        wMaxPacketSize     0x0200  1x 512 bytes
        bInterval             255
      Endpoint Descriptor:
        bLength                 7
        bDescriptorType         5
        bEndpointAddress     0x02  EP 2 OUT
        bmAttributes            2
          Transfer Type            Bulk
          Synch Type               None
          Usage Type               Data
        wMaxPacketSize     0x0200  1x 512 bytes
        bInterval             255
Device Qualifier (for other device speed):
  bLength                10
  bDescriptorType         6
  bcdUSB               2.00
  bDeviceClass            0 (Defined at Interface level)
  bDeviceSubClass         0
  bDeviceProtocol         0
  bMaxPacketSize0        64
  bNumConfigurations      1
Device Status:     0x0000
  (Bus Powered)
</code>```

Why does it shows the device or resources busy. How to claim the interface?.

答:
The device is shown as busy because this is a USB Mass Storage class device and Linux will automatically load a kernel driver when it is connected that claims interface 0.

You can manually unbind the USB device driver with the following command:

echo -n "1-1:1.0" > /sys/bus/usb/drivers/usb-storage/unbind

"1-1:1.0" specifies the device and interface that the usb-storage driver should unbind from. "1-1" means bus 1, port 1 and "1.0" means configuration 1, interface 0. This information is printed in the kernel log when the device is connected like this,

usb-storage 1-1:1.0: USB Mass Storage device detected

The bus and port number for your device will likely differ.

While this should allow you to use this device with WebUSB it is not likely useful as a long term solution because of the manual steps involved. WebUSB is designed for devices without built-in operating system drivers.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to communicate with usb device using WEBUSB API. BUT when I am trying to claim Interface it shows

"DOMException: Unable to claim interface"

the bConfigurationvalue is 1 and interface number is 0. I am adding the output of command lsusb -v below

~$ lsusb -v
Bus 001 Device 005: ID 0930:6544 Toshiba Corp. TransMemory-Mini / Kingston DataTraveler 2.0 Stick (2GB)
Device Descriptor:
  bLength                18
  bDescriptorType         1
  bcdUSB               2.00
  bDeviceClass            0 (Defined at Interface level)
  bDeviceSubClass         0
  bDeviceProtocol         0
  bMaxPacketSize0        64
  idVendor           0x0930 Toshiba Corp.
  idProduct          0x6544 TransMemory-Mini / Kingston DataTraveler 2.0 Stick (2GB)
  bcdDevice            1.00
  iManufacturer           1 TOSHIBA
  iProduct                2 TransMemory
  iSerial                 3 C412F52D6C84CFC0A0012AEF
  bNumConfigurations      1
  Configuration Descriptor:
    bLength                 9
    bDescriptorType         2
    wTotalLength           32
    bNumInterfaces          1
    bConfigurationValue     1
    iConfiguration          0
    bmAttributes         0x80
      (Bus Powered)
    MaxPower              200mA
    Interface Descriptor:
      bLength                 9
      bDescriptorType         4
      bInterfaceNumber        0
      bAlternateSetting       0
      bNumEndpoints           2
      bInterfaceClass         8 Mass Storage
      bInterfaceSubClass      6 SCSI
      bInterfaceProtocol     80 Bulk-Only
      iInterface              0
      Endpoint Descriptor:
        bLength                 7
        bDescriptorType         5
        bEndpointAddress     0x81  EP 1 IN
        bmAttributes            2
          Transfer Type            Bulk
          Synch Type               None
          Usage Type               Data
        wMaxPacketSize     0x0200  1x 512 bytes
        bInterval             255
      Endpoint Descriptor:
        bLength                 7
        bDescriptorType         5
        bEndpointAddress     0x02  EP 2 OUT
        bmAttributes            2
          Transfer Type            Bulk
          Synch Type               None
          Usage Type               Data
        wMaxPacketSize     0x0200  1x 512 bytes
        bInterval             255
Device Qualifier (for other device speed):
  bLength                10
  bDescriptorType         6
  bcdUSB               2.00
  bDeviceClass            0 (Defined at Interface level)
  bDeviceSubClass         0
  bDeviceProtocol         0
  bMaxPacketSize0        64
  bNumConfigurations      1
Device Status:     0x0000
  (Bus Powered)

Why does it shows the device or resources busy. How to claim the interface?.


问:
How to console log table id?
Just simple question, im very little bit in JS.

in the add table button, im adding and append new table into .tab-content div. (No need to show the button code) .

```<code>if (typeof (Storage) !== "undefined") {
    if (localStorage.Index) {
        localStorage.Index = Number(localStorage.Index) + 1;
    } else {
        localStorage.Index = 1;
    }
} else {

}

function getTableList() {
    var addTable = '<div class="tab-pane" id="folder' + localStorage.Index + '">' +
        '<div class="zf-table">' +
        '<table id="table' + localStorage.Index + '" class="table table-bordered table-hover myFade">' +
        '<thead>' +
        '<tr>' +
        '<th style="border-color:rgb(221, 221, 221);"></th>' +
        '<th>Audience Name</th>' +
        '<th>Type</th>' +
        '<th>Size</th>' +
        '<th>Date Created</th>' +
        '<th>Action</th>' +
        '</tr>' +
        '</thead>' +
        '</table>' +
        '</div>' +
        '</div>';
    return addTable;
}

let newtableHTML = getTableList();
$('.tab-content').append(newtableHTML);
</code>```

How to store table ID into console.log?

```<code><table id="table' + localStorage.Index + '" class="table table-bordered table-hover myFade">
</code>```

Log will be display

table1

table2

when user adding new table.

答:
Just add a log statement in your getTableList function...

```<code>function getTableList() {
  console.log("table" + localStorage.Index);
  // rest of your function...
</code>```

That way each time it is called the log with output the table id.

Title: How to console log table id?

Body:
Just simple question, im very little bit in JS.

in the add table button, im adding and append new table into .tab-content div. (No need to show the button code) .

if (typeof (Storage) !== "undefined") {
    if (localStorage.Index) {
        localStorage.Index = Number(localStorage.Index) + 1;
    } else {
        localStorage.Index = 1;
    }
} else {

}

function getTableList() {
    var addTable = '
' +
        '
' +
        '
' +
        '
' +
        '
' +
        '	' +
        'Audience Name	' +
        'Type	' +
        'Size	' +
        'Date Created	' +
        'Action	' +
        '
' +
        '
' +
        '
' +
        '
' +
        '
';
    return addTable;
}

let newtableHTML = getTableList();
$('.tab-content').append(newtableHTML);

How to store table ID into console.log?

Log will be display

table1

table2

when user adding new table.

Body:
Just add a log statement in your getTableList function...

function getTableList() {
  console.log("table" + localStorage.Index);
  // rest of your function...

That way each time it is called the log with output the table id.


Title: How to console log table id?

Body: console.log('table' + localStorage.Index)


问:
Gradle build error using react native
I get this error when trying to run an app on an android emulator(Android Studio) from a console window:

$ react-native run-android
Scanning folders for symlinks in C:\Users\Brian\desktop\codervets\arrive-alive\aa_app\node_modules (27726ms)
Starting JS server...
Building and installing the app on the device (cd android && gradlew.bat installDebug)...
Starting a Gradle Daemon (subsequent builds will be faster)
Configuration 'compile' in project ':app' is deprecated. Use 'implementation' instead.

FAILURE: Build failed with an exception.

What went wrong:
A problem occurred configuring project ':app'.

The SDK directory 'c:\Users\eelia001\AppData\local\android\sdk1' does not exist.

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

Get more help at https://help.gradle.org

BUILD FAILED in 4m 51s
Could not install the app on the device, read the error above for details.
Make sure you have an Android emulator running or a device connected and have
set up your Android development environment:
https://facebook.github.io/react-native/docs/android-setup.html

And yet my sdk directory in android studio has the following directory:
C:\Users\Brian\AppData\Local\Android\Sdk

Has anyone else ran into this issue? If so, how do I fix it?

答:
The error states:

The SDK directory 'c:\Users\eelia001\AppData\local\android\sdk1' does not exist.

And you say your SDK is in:

C:\Users\Brian\AppData\Local\Android\Sdk

Since those aren't the same directory, my guess is that's the problem. Are you perhaps logged in as the wrong user? You're going to want to check that ANDROID_HOME is set correctly.

Title: Gradle build error using react native


问:
Selecting multiple rows in same table in the same JOIN
In the picture is my table situation right now:

The central table in this case right now is tblJob, here is everything defined what I need (not all in the picture).

The address table needs to return 2 values (1 of the company and 1 of the job itself). The only thing I need to do right now is to add the company address (the job address is already in my query) My query already looks like this:

```<code>SELECT
tblJob.jobID,
tblJob.amount        AS jobAmount,
tblJob.extraInfo     AS jobExtraInfo,
tblJob.views         AS jobViews,
tblJob.description   AS jobDescription,
tblJob.dateCreated   AS jobDateCreated,
tblJobFunction.jobFunctionID,
tblJobFunction.jobFunction,
tblAddress.zipcode   AS jobAddress,
tblAddress.city      AS jobCity,
tblAddress.street    AS jobStreet,
tblAddress.number    AS jobNumber,
tblAddress.bus       AS jobBus,
tblCountry.countryID AS jobCountryID,
tblCountry.country   AS jobCountry,
tblCountry.areaCode  AS jobAreaCode,
tblCompany.companyID,
tblCompany.name,
tblCompany.email,
tblCompany.GSM,
tblCompany.phoneNumber,
tblCompany.photoURL  AS companyPhotoURL,
tblCompany.VATNumber,
tblCompany.websiteURL,
tblEvent.eventID,
tblEvent.event,
tblEvent.description AS eventDescription,
tblEvent.startDate   AS eventStartDate,
tblEvent.endDate     AS eventEndDate,
tblEvent.facebookURL,
tblEvent.photoURL    AS eventPhotoURL,
tblEvent.views       AS eventViews,
tblEvent.dateCreated AS eventDateCreated
FROM tblJob
JOIN tblAddress ON tblAddress.addressID = tblJob.addressID
JOIN tblCountry ON tblAddress.countryID = tblCountry.countryID
JOIN tblJobFunction ON tblJob.jobFunctionID =
                       tblJobFunction.jobFunctionID
JOIN tblCompany ON tblJob.companyID = tblCompany.companyID
LEFT JOIN tblEvent ON tblJob.eventID = tblEvent.eventID
</code>```

Now the question is: how can I add the address from the company in the same query?

答:
Use the address table as many times as you need it, but each time you must give it a new alias:

```<code>FROM tblJob
JOIN tblAddress ON tblAddress.addressID = tblJob.addressID
JOIN tblCountry ON tblAddress.countryID = tblCountry.countryID
JOIN tblJobFunction ON tblJob.jobFunctionID =  tblJobFunction.jobFunctionID
JOIN tblCompany ON tblJob.companyID = tblCompany.companyID

JOIN tblAddress a2 ON a2.addressID = tblCompany.addressID

LEFT JOIN tblEvent ON tblJob.eventID = tblEvent.eventID
</code>```

perhaps more like this:

```
SELECT <b>JobAddress</b>.street, <b>CompanyAddress</b>.street
FROM tblJob
JOIN tblAddress <b>JobAddress</b> ON <b>JobAddress</b>.addressID = tblJob.addressID
JOIN tblCompany ON tblJob.companyID = tblCompany.companyID
JOIN tblAddress <b>CompanyAddress</b> ON <b>CompanyAddress</b>.addressID = tblCompany.addressID
```

Body:
In the picture is my table situation right now:

The central table in this case right now is tblJob, here is everything defined what I need (not all in the picture).

The address table needs to return 2 values (1 of the company and 1 of the job itself). The only thing I need to do right now is to add the company address (the job address is already in my query) My query already looks like this:

SELECT
tblJob.jobID,
tblJob.amount        AS jobAmount,
tblJob.extraInfo     AS jobExtraInfo,
tblJob.views         AS jobViews,
tblJob.description   AS jobDescription,
tblJob.dateCreated   AS jobDateCreated,
tblJobFunction.jobFunctionID,
tblJobFunction.jobFunction,
tblAddress.zipcode   AS jobAddress,
tblAddress.city      AS jobCity,
tblAddress.street    AS jobStreet,
tblAddress.number    AS jobNumber,
tblAddress.bus       AS jobBus,
tblCountry.countryID AS jobCountryID,
tblCountry.country   AS jobCountry,
tblCountry.areaCode  AS jobAreaCode,
tblCompany.companyID,
tblCompany.name,
tblCompany.email,
tblCompany.GSM,
tblCompany.phoneNumber,
tblCompany.photoURL  AS companyPhotoURL,
tblCompany.VATNumber,
tblCompany.websiteURL,
tblEvent.eventID,
tblEvent.event,
tblEvent.description AS eventDescription,
tblEvent.startDate   AS eventStartDate,
tblEvent.endDate     AS eventEndDate,
tblEvent.facebookURL,
tblEvent.photoURL    AS eventPhotoURL,
tblEvent.views       AS eventViews,
tblEvent.dateCreated AS eventDateCreated
FROM tblJob
JOIN tblAddress ON tblAddress.addressID = tblJob.addressID
JOIN tblCountry ON tblAddress.countryID = tblCountry.countryID
JOIN tblJobFunction ON tblJob.jobFunctionID =
                       tblJobFunction.jobFunctionID
JOIN tblCompany ON tblJob.companyID = tblCompany.companyID
LEFT JOIN tblEvent ON tblJob.eventID = tblEvent.eventID

Now the question is: how can I add the address from the company in the same query?

Body:
Use the address table as many times as you need it, but each time you must give it a new alias:

FROM tblJob
JOIN tblAddress ON tblAddress.addressID = tblJob.addressID
JOIN tblCountry ON tblAddress.countryID = tblCountry.countryID
JOIN tblJobFunction ON tblJob.jobFunctionID =  tblJobFunction.jobFunctionID
JOIN tblCompany ON tblJob.companyID = tblCompany.companyID

JOIN tblAddress a2 ON a2.addressID = tblCompany.addressID

LEFT JOIN tblEvent ON tblJob.eventID = tblEvent.eventID

perhaps more like this:

SELECT JobAddress.street, CompanyAddress.street
FROM tblJob
JOIN tblAddress JobAddress ON JobAddress.addressID = tblJob.addressID
JOIN tblCompany ON tblJob.companyID = tblCompany.companyID
JOIN tblAddress CompanyAddress ON CompanyAddress.addressID = tblCompany.addressID


问:
How do I create a pip requirements file for a tarball on my local filesystem?
Tell me if what I'm trying to do doesn't make sense.

I want to create a virtual environment that, among other things, includes MySQLDb 1.2.3.  This library is distributed as a gzipped tarball (.tgz) file.  I want to install everything—including tarballs on my local filesystem—from a requirements file in requirements/apps.txt (this is based on a setup I saw in http://thraxil.org/users/anders/posts/2009/06/12/Django-Deployment-with-virtualenv-and-pip/):

```<code>pip.py install -E ve --enable-site-packages --requirement requirements/apps.txt
</code>```

I couldn't find any documentation on the pip requirements file format for local files.

What does the requirements file (apps.txt) need to contain if the directory requirements/ contains the file MySQL-python-1.2.3.tgz?

答:
You can use absolute/relative paths in requirements files e.g.:</p>

```<code>--extra-index-url=http://example.com
my-apps/apps1.tar.gz
# put apps2-1.0.1.tar.gz to http://example.com/apps2/
apps2
</code>```

Body:
Tell me if what I'm trying to do doesn't make sense.

I want to create a virtual environment that, among other things, includes MySQLDb 1.2.3.  This library is distributed as a gzipped tarball (.tgz) file.  I want to install everything—including tarballs on my local filesystem—from a requirements file in requirements/apps.txt (this is based on a setup I saw in http://thraxil.org/users/anders/posts/2009/06/12/Django-Deployment-with-virtualenv-and-pip/):

pip.py install -E ve --enable-site-packages --requirement requirements/apps.txt

I couldn't find any documentation on the pip requirements file format for local files.

What does the requirements file (apps.txt) need to contain if the directory requirements/ contains the file MySQL-python-1.2.3.tgz?

Body:
You can use absolute/relative paths in requirements files e.g.:

--extra-index-url=http://example.com
my-apps/apps1.tar.gz
# put apps2-1.0.1.tar.gz to http://example.com/apps2/
apps2


问:
Excel VBA running Access query may return multiple records
I'm running the following query in a macro (with Excel VBA) to an Access database.  It works good when only 1 record is returned.  I've been made aware that multiple records could be returned.

I'm stuck on trying to identify when there are multiple records so I can add each additional record to the worksheet.  Once I know there are multiple records, I'll write the 1st record and then increment the row number (x) by 1 to write the 2nd, 3rd, etc.

I haven't had this situation before so I'm not sure how (1) to identify if there are multiple records and (2) how to write the 2nd record.  Is the first field in the 2nd record going to be Recordset.Fields(11)?

Thanks for the help..........

```<code>Dim Recordset As ADODB.Recordset
Set Recordset = New ADODB.Recordset

vDataBase = "Y:\Groups\Corporate Accounting\AutoMonarch\ Translate\Titles.mdb"
ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= '" & vDataBase & "';Persist Security Info=False"

vSql = ""
vSql = "Select bo_id, buyers_order_date, mileage, contact_name, contact_phone, cust_legal_name, address, city, state, zip, country, location_phone from buyerinfo where unit = '" & vArrUnit(q) & "'"

Call Recordset.Open(vSql, ConnectionString, adOpenForwardOnly, adLockReadOnly, CommandTypeEnum.adCmdText)

If Recordset.BOF And Recordset.EOF Then
'      do something to indicate no records returned
Else

   Cells(x, 4) = Recordset.Fields(1).Value
   Cells(x, 5) = Recordset.Fields(2).Value
   ....
   Cells(x, 12) = Recordset.Fields(10).Value

End If
</code>```

答:
Sorry, but this sound like a weird setup.  Can you run a 'Find Duplicates Query Wizard'?  Maybe you can do a Countif in Excel, if that's your ask.

https://www.extendoffice.com/documents/excel/1499-count-duplicate-values-in-column.html

Body:
I'm running the following query in a macro (with Excel VBA) to an Access database.  It works good when only 1 record is returned.  I've been made aware that multiple records could be returned.

I'm stuck on trying to identify when there are multiple records so I can add each additional record to the worksheet.  Once I know there are multiple records, I'll write the 1st record and then increment the row number (x) by 1 to write the 2nd, 3rd, etc.

I haven't had this situation before so I'm not sure how (1) to identify if there are multiple records and (2) how to write the 2nd record.  Is the first field in the 2nd record going to be Recordset.Fields(11)?

Thanks for the help..........

Dim Recordset As ADODB.Recordset
Set Recordset = New ADODB.Recordset

vDataBase = "Y:\Groups\Corporate Accounting\AutoMonarch\ Translate\Titles.mdb"
ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= '" & vDataBase & "';Persist Security Info=False"

vSql = ""
vSql = "Select bo_id, buyers_order_date, mileage, contact_name, contact_phone, cust_legal_name, address, city, state, zip, country, location_phone from buyerinfo where unit = '" & vArrUnit(q) & "'"

Call Recordset.Open(vSql, ConnectionString, adOpenForwardOnly, adLockReadOnly, CommandTypeEnum.adCmdText)

If Recordset.BOF And Recordset.EOF Then
'      do something to indicate no records returned
Else

   Cells(x, 4) = Recordset.Fields(1).Value
   Cells(x, 5) = Recordset.Fields(2).Value
   ....
   Cells(x, 12) = Recordset.Fields(10).Value

End If


问:
Faild to claim interface while developing webusb api
I am trying to develop a webusb api using html and javascript and operating system is Ubuntu 16.04. I am able to connect and open the usb device from browser, but I got an error 'Failed to claim interface 0: Device or resource busy (16)'. Please give me a proper solution.

This is the script code,
var device;

```<code>function setup(device) {
    alert(device.productName+" open");

    return device.open()

    .then(() => device.selectConfiguration(1))
    .then(() => device.claimInterface(0))
    .then(() => this.device_.selectAlternateInterface(1, 0))

}

function connect() {
    if (device == null) {
        navigator.usb.requestDevice({ filters: [{ vendorId : 2352 }] })
        .then(selectedDevice => {
            device = selectedDevice;
            console.log(device);
            return setup(device);
            alert("usb connected");
        })

        .catch(error => { console.log(error); })
    }

}
navigator.usb.getDevices()
.then(devices => {
    if (devices.length > 0) {
        device = devices[0];
        return setup(device);
    }
})
.catch(error => { console.log(error); });
</code>```

and this is the rule file I added

SUBSYSTEM=="usb", ATTR{idVendor}=="0930",ATTR{idProduct}=="6544", MODE="0666", GROUP="plugdev"

Whether I can done this by detaching the device from kernal? How it is possible?

答:
This question is a duplicate of "Failed to claim interface 0: Device or resource busy
".</p>

Body:
I am trying to develop a webusb api using html and javascript and operating system is Ubuntu 16.04. I am able to connect and open the usb device from browser, but I got an error 'Failed to claim interface 0: Device or resource busy (16)'. Please give me a proper solution.

This is the script code,
var device;

function setup(device) {
    alert(device.productName+" open");

    return device.open()

    .then(() => device.selectConfiguration(1))
    .then(() => device.claimInterface(0))
    .then(() => this.device_.selectAlternateInterface(1, 0))

}

function connect() {
    if (device == null) {
        navigator.usb.requestDevice({ filters: [{ vendorId : 2352 }] })
        .then(selectedDevice => {
            device = selectedDevice;
            console.log(device);
            return setup(device);
            alert("usb connected");
        })

        .catch(error => { console.log(error); })
    }

}
navigator.usb.getDevices()
.then(devices => {
    if (devices.length > 0) {
        device = devices[0];
        return setup(device);
    }
})
.catch(error => { console.log(error); });

and this is the rule file I added

SUBSYSTEM=="usb", ATTR{idVendor}=="0930",ATTR{idProduct}=="6544", MODE="0666", GROUP="plugdev"

Whether I can done this by detaching the device from kernal? How it is possible?


问:
It telling me that I have make a mistake when I am using  on php
I am trying to make a chart on php which when the number is 2/4/6/8/10 ... etc. The number will be on white color and it's box on green color, and when the number is 1/3/5/7/9 ... etc, the number will be on black color and it's box on red color.

Everything is ok but when I am adding style="color:white(/black);" and style="background-color:red(/green);" on the  and I am saving it, my window is telling me there is a mistake background-color/color ... etc. on this line. Can somebody help me?

Here is my code:

```<code><?php
    echo '<table>'
    for ($i=1; $i<=10; $i++) {
        echo "<tr>  </tr>";
        for ($j=1; $j<=10; $j++) {
            $t= $i * $j;
            if ($j%2==1) {
                echo "<td style="background-color:red;color:black"> $t </td>";
                } else  {
                echo "<td background-color:green;color:white>  $t </td>";
                }
        }
    }
    echo '</table>';
?>
</code>```

I have included the html/head/body etc.

答:
1º - You're putting double quotes inside another double quotes!

2º - You've forgotted to put style attribute in the second td!

Change the code below:

```<code>echo "<td style="background-color:red;color:black"> $t </td>";
} else  {
echo "<td background-color:green;color:white>  $t </td>";
}
</code>```

To:

```<code>echo "<td style='background-color:red;color:black'> $t </td>";
} else  {
echo "<td style='background-color:green;color:white'>  $t </td>";
}
</code>```

PS.: it's not a good idea to put variables inside double quotes "$var". It should be better if you try like above:

```<code>echo "<td style='background-color:red;color:black'>". $t ."</td>";
</code>```

Title: It telling me that I have make a mistake when I am using <td style="color:...;"> on php

Body:
I am trying to make a chart on php which when the number is 2/4/6/8/10 ... etc. The number will be on white color and it's box on green color, and when the number is 1/3/5/7/9 ... etc, the number will be on black color and it's box on red color.

Everything is ok but when I am adding style="color:white(/black);" and style="background-color:red(/green);" on the  and I am saving it, my window is telling me there is a mistake background-color/color ... etc. on this line. Can somebody help me?

Here is my code:

<?php
    echo '
'
    for ($i=1; $i<=10; $i++) {
        echo "

";
        for ($j=1; $j<=10; $j++) {
            $t= $i * $j;
            if ($j%2==1) {
                echo " $t 	";
                } else  {
                echo "  $t 	";
                }
        }
    }
    echo '
';
?>

I have included the html/head/body etc.

Body:
1º - You're putting double quotes inside another double quotes!

2º - You've forgotted to put style attribute in the second td!

Change the code below:

echo "<td style="background-color:red;color:black"> $t </td>";
} else  {
echo "<td background-color:green;color:white>  $t </td>";
}

To:

echo "<td style='background-color:red;color:black'> $t </td>";
} else  {
echo "<td style='background-color:green;color:white'>  $t </td>";
}

PS.: it's not a good idea to put variables inside double quotes "$var". It should be better if you try like above:

echo "<td style='background-color:red;color:black'>". $t ."</td>";


问:
Printf displays numbers/characters incorrectly in C
I am creating a program that simply allows users to do multiple things in one executable program. So for right now I input information into my struct variables and when the user enters "P" into the window, they're suppose to get the information back. The problem is that when it displays the results, instead of displaying '1 or 2' it displays "-0.23455558" and other silly symbols for characters. Here is my code.

C code

```<code>#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<ctype.h>
typedef struct {

    char fname[40];
    char lname[40];
    int age;
    int id;
    double gpa;
    double price;

}student;

void Addsix(student list[]);

char Getinput();

void PrintToScreen(student list[], int count);
int main() {

    student list[100];
    int count = 0;
    char choice;
    Addsix(list);
    count = 6;
    choice = Getinput();
    while (choice != 'Q') {

        if (choice == 'P') {

            PrintToScreen(list, count);
        }
        choice = Getinput();
    }
    return 0;
}

void PrintToScreen(student list[], int count) {

    student temp;

    int i;
    for (i = 0; i < count; i++) {

        printf("First Name: %c\n", temp.fname[i]);
        printf("Last Name: %c\n", temp.lname[i]);
        printf("Age: %d\n", temp.age);
        printf("Id: %d\n", temp.id);
        printf("Gpa: %.2f", temp.gpa);
        printf("Price: %.2f", temp.price);
    }

}
char Getinput() {
    char pick;
    printf("\n***************************************\n");
    printf("Please select from the options below:\n");
    printf("P....Print the inventory list onto the screen\n");
    printf("A....Add a new entry\n");
    printf("C....Clear all records\n");
    printf("S....Create a current report(save it to a file)\n");
    printf("D....Delete an item from the list(inventory)\n");
    printf("U....Update ONE OF THE FIELDS (not THE id)\n");
    printf("Q - QUIT\n");
    printf("What would you like to do: ");
    scanf(" %c", &pick);
    pick = toupper(pick);
    return pick;
}
void Addsix(student list[]) {

    strcpy(list[0].fname, "Jon");
    strcpy(list[0].lname, "pep");
    list[0].age = 19;
    list[0].id = 2713;
    list[0].gpa = 4.0;
    list[0].price = 2.79;

    strcpy(list[1].fname, "Amanda");
    strcpy(list[1].lname, "Stri");
    list[1].age = 25;
    list[1].id = 9654;
    list[1].gpa = 3.5;
    list[1].price = 2.84;

    strcpy(list[2].fname, "Patrick");
    strcpy(list[2].lname, "Collie");
    list[2].age = 42;
    list[2].id = 7748;
    list[2].gpa = 2.4;
    list[2].price = 74.5;

    strcpy(list[3].fname, "Kim");
    strcpy(list[3].lname, "Campbell");
    list[3].age = 21;
    list[3].id = 4508;
    list[3].gpa = 3.27;
    list[3].price = 2.25;

    strcpy(list[4].fname, "Micky");
    strcpy(list[4].lname, "Peoples");
    list[4].age = 37;
    list[4].id = 1478;
    list[4].gpa = 4.0;
    list[4].price = 10.0;

    strcpy(list[5].fname, "ako");
    strcpy(list[5].lname, "Imo");
    list[5].age = 15;
    list[5].id = 8520;
    list[5].gpa = 2.90;
    list[5].price = 96.5;

    strcpy(list[6].fname, "Rick");
    strcpy(list[6].lname, "Rolle");
    list[6].age = 28;
    list[6].id = 1379;
    list[6].gpa = 3.8;
    list[6].price = 55.2;

}
</code>```

答:
```<code>void PrintToScreen(student list[], int count) {
    student temp;

    int i;
    for (i = 0; i < count; i++) {
        printf("First Name: %c\n", temp.fname[i]);
        printf("Last Name: %c\n", temp.lname[i]);
        printf("Age: %d\n", temp.age);
        printf("Id: %d\n", temp.id);
        printf("Gpa: %.2f", temp.gpa);
        printf("Price: %.2f", temp.price);
    }
}
</code>```

Your problem lies here. At no point do you actually access anything in the array created in the main function (and passed in as a parameter to this function). Instead, you access a variable temp created in this function, which will have arbitrary values in the members.

On top of that, since your first two members of the structure are C strings, you probably want to treat them as such rather than trying to output individual characters: i is the index within the structure array, not the character array forming the strings.

You would be better off with something like (cut down for illustration only):

```<code>void PrintToScreen(student list[], int count) {
    int i;
    for (i = 0; i < count; i++) {
        printf("First Name: %s\n", list[i].fname);
        printf("Age: %d\n", list[i].age);
    }
}
</code>```

Body:
I am creating a program that simply allows users to do multiple things in one executable program. So for right now I input information into my struct variables and when the user enters "P" into the window, they're suppose to get the information back. The problem is that when it displays the results, instead of displaying '1 or 2' it displays "-0.23455558" and other silly symbols for characters. Here is my code.

C code

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<ctype.h>
typedef struct {

    char fname[40];
    char lname[40];
    int age;
    int id;
    double gpa;
    double price;

}student;

void Addsix(student list[]);

char Getinput();

void PrintToScreen(student list[], int count);
int main() {

    student list[100];
    int count = 0;
    char choice;
    Addsix(list);
    count = 6;
    choice = Getinput();
    while (choice != 'Q') {

        if (choice == 'P') {

            PrintToScreen(list, count);
        }
        choice = Getinput();
    }
    return 0;
}

void PrintToScreen(student list[], int count) {

    student temp;

    int i;
    for (i = 0; i < count; i++) {

        printf("First Name: %c\n", temp.fname[i]);
        printf("Last Name: %c\n", temp.lname[i]);
        printf("Age: %d\n", temp.age);
        printf("Id: %d\n", temp.id);
        printf("Gpa: %.2f", temp.gpa);
        printf("Price: %.2f", temp.price);
    }

}
char Getinput() {
    char pick;
    printf("\n***************************************\n");
    printf("Please select from the options below:\n");
    printf("P....Print the inventory list onto the screen\n");
    printf("A....Add a new entry\n");
    printf("C....Clear all records\n");
    printf("S....Create a current report(save it to a file)\n");
    printf("D....Delete an item from the list(inventory)\n");
    printf("U....Update ONE OF THE FIELDS (not THE id)\n");
    printf("Q - QUIT\n");
    printf("What would you like to do: ");
    scanf(" %c", &pick);
    pick = toupper(pick);
    return pick;
}
void Addsix(student list[]) {

    strcpy(list[0].fname, "Jon");
    strcpy(list[0].lname, "pep");
    list[0].age = 19;
    list[0].id = 2713;
    list[0].gpa = 4.0;
    list[0].price = 2.79;

    strcpy(list[1].fname, "Amanda");
    strcpy(list[1].lname, "Stri");
    list[1].age = 25;
    list[1].id = 9654;
    list[1].gpa = 3.5;
    list[1].price = 2.84;

    strcpy(list[2].fname, "Patrick");
    strcpy(list[2].lname, "Collie");
    list[2].age = 42;
    list[2].id = 7748;
    list[2].gpa = 2.4;
    list[2].price = 74.5;

    strcpy(list[3].fname, "Kim");
    strcpy(list[3].lname, "Campbell");
    list[3].age = 21;
    list[3].id = 4508;
    list[3].gpa = 3.27;
    list[3].price = 2.25;

    strcpy(list[4].fname, "Micky");
    strcpy(list[4].lname, "Peoples");
    list[4].age = 37;
    list[4].id = 1478;
    list[4].gpa = 4.0;
    list[4].price = 10.0;

    strcpy(list[5].fname, "ako");
    strcpy(list[5].lname, "Imo");
    list[5].age = 15;
    list[5].id = 8520;
    list[5].gpa = 2.90;
    list[5].price = 96.5;

    strcpy(list[6].fname, "Rick");
    strcpy(list[6].lname, "Rolle");
    list[6].age = 28;
    list[6].id = 1379;
    list[6].gpa = 3.8;
    list[6].price = 55.2;

}

Body:
void PrintToScreen(student list[], int count) {
    student temp;

    int i;
    for (i = 0; i < count; i++) {
        printf("First Name: %c\n", temp.fname[i]);
        printf("Last Name: %c\n", temp.lname[i]);
        printf("Age: %d\n", temp.age);
        printf("Id: %d\n", temp.id);
        printf("Gpa: %.2f", temp.gpa);
        printf("Price: %.2f", temp.price);
    }
}

Your problem lies here. At no point do you actually access anything in the array created in the main function (and passed in as a parameter to this function). Instead, you access a variable temp created in this function, which will have arbitrary values in the members.

On top of that, since your first two members of the structure are C strings, you probably want to treat them as such rather than trying to output individual characters: i is the index within the structure array, not the character array forming the strings.

You would be better off with something like (cut down for illustration only):

void PrintToScreen(student list[], int count) {
    int i;
    for (i = 0; i < count; i++) {
        printf("First Name: %s\n", list[i].fname);
        printf("Age: %d\n", list[i].age);
    }
}


问:
How do I simulate flip of biased coin?
In unbiased coin flip H or T occurs 50% of times.

But I want to simulate coin which gives H  with probability 'p' and T with probability '(1-p)'.

something like this:

```<code>def flip(p):
   '''this function return H with probability p'''
   # do something
   return result

>> [flip(0.8) for i in xrange(10)]
[H,H,T,H,H,H,T,H,H,H]
</code>```

答:
Import a random number between 0 - 1 (you can use randrange function)

If the number is above (1-p), return tails.

Else, return heads

OwnerDisplayName: david makcenzie

ContentLicense: CC BY-SA 4.0

Title: How do I simulate flip of biased coin?

Body:
In unbiased coin flip H or T occurs 50% of times.

But I want to simulate coin which gives H  with probability 'p' and T with probability '(1-p)'.

something like this:

def flip(p):
   '''this function return H with probability p'''
   # do something
   return result

>> [flip(0.8) for i in xrange(10)]
[H,H,T,H,H,H,T,H,H,H]

LastEditorDisplayName: Mitch Wheat

OwnerDisplayName: Colin


问:
Starting and stopping IIS Express programmatically
I am trying to build a small application in C# which should start/stop an IIS Express worker process. For this purpose I want to use the official "IIS Express API" which is documented on MSDN: http://msdn.microsoft.com/en-us/library/gg418415.aspx

As far as I understand, the API is based (only) on COM interfaces. To use this COM interfaces I've added a reference to the COM library in VS2010 via Add Reference -> COM -> "IIS Installed Versions Manager Interface":

So far so good, but what's next? There is an IIISExprProcessUtility interface available which includes the the two "methods" to start/stop an IIS process. Do I have to write a class which implements this interface?

```<code>public class test : IISVersionManagerLibrary.IIISExprProcessUtility
{
    public string ConstructCommandLine(string bstrSite, string bstrApplication, string bstrApplicationPool, string bstrConfigPath)
    {
        throw new NotImplementedException();
    }

    public uint GetRunningProcessForSite(string bstrSite, string bstrApplication, string bstrApplicationPool, string bstrConfigPath)
    {
        throw new NotImplementedException();
    }

    public void StopProcess(uint dwPid)
    {
        throw new NotImplementedException();
    }
}
</code>```

As you can see, I'm not a professional developer. Can someone point me in the right direction.
Any help is greatly appreciated.

Update 1:
According to the suggestions I've tried the following code which unfortunately doesn't work:

Ok, it can be instantiated but I cannot see how to use this object...

```<code>IISVersionManagerLibrary.IIISExpressProcessUtility test3 = (IISVersionManagerLibrary.IIISExpressProcessUtility) Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid("5A081F08-E4FA-45CC-A8EA-5C8A7B51727C")));

Exception: Retrieving the COM class factory for component with CLSID {5A081F08-E4FA-45CC-A8EA-5C8A7B51727C} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).
</code>```

答:
I feel you are doing it in a hard way. Take a hint from this question Automatically stop/restart ASP.NET Development Server on Build and see if you can adopt the same process.

Answering your question, I think pinvoke.net might help you. They have lot of examples as well which can help you build your solution.

Body:
I am trying to build a small application in C# which should start/stop an IIS Express worker process. For this purpose I want to use the official "IIS Express API" which is documented on MSDN: http://msdn.microsoft.com/en-us/library/gg418415.aspx

As far as I understand, the API is based (only) on COM interfaces. To use this COM interfaces I've added a reference to the COM library in VS2010 via Add Reference -> COM -> "IIS Installed Versions Manager Interface":

So far so good, but what's next? There is an IIISExprProcessUtility interface available which includes the the two "methods" to start/stop an IIS process. Do I have to write a class which implements this interface?

public class test : IISVersionManagerLibrary.IIISExprProcessUtility
{
    public string ConstructCommandLine(string bstrSite, string bstrApplication, string bstrApplicationPool, string bstrConfigPath)
    {
        throw new NotImplementedException();
    }

    public uint GetRunningProcessForSite(string bstrSite, string bstrApplication, string bstrApplicationPool, string bstrConfigPath)
    {
        throw new NotImplementedException();
    }

    public void StopProcess(uint dwPid)
    {
        throw new NotImplementedException();
    }
}

As you can see, I'm not a professional developer. Can someone point me in the right direction.
Any help is greatly appreciated.

Update 1:
According to the suggestions I've tried the following code which unfortunately doesn't work:

Ok, it can be instantiated but I cannot see how to use this object...

IISVersionManagerLibrary.IIISExpressProcessUtility test3 = (IISVersionManagerLibrary.IIISExpressProcessUtility) Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid("5A081F08-E4FA-45CC-A8EA-5C8A7B51727C")));

Exception: Retrieving the COM class factory for component with CLSID {5A081F08-E4FA-45CC-A8EA-5C8A7B51727C} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).


问:
Typescript: how to sort an array, case insensitively?
I am trying to sort an array in typescript case insensitively. In javascript, that could be accomplished with

```<code>    list.sort(function (a, b) {
      return a.toLowerCase().localeCompare(b.toLowerCase());
    });
</code>```

In typescript the sort looks like

```<code>    list.sort((a, b) => {
      if (a > b) {
        return 1;
      }
      if (a < b) {
        return -1;
      }
      return 0;
    });
</code>```

Starting with [F, E, D, c, b, a] I expect to get [a, b, c, D, E, F]

The javascript sort delivers the expected results, but the typescript sort returns [D, E, F, a, b, c]. How do I make the typescript sort case insensitive?

EDIT: the reason I can't use the javascript method is because in typescript a and b are boolean and don't have ,toLowerCase() method

答:
Try this sort function. It's basically a rewrite of what you have but it may be a bit cleaner. It also works. The compiler wants a type. It doesn't care if it's string or any in this case. I have updated the answer to change the types passed in into strings. It works for this array as easily well as type any.

```<code>function sortStrings(a: string, b: string) {
    a = a.toLowerCase();
    b = b.toLowerCase();
    return a > b ? 1 : (a < b ? -1 : 0);
}

console.log(['F', 'E', 'D', 'c', 'b', 'a'].sort(sortStrings));
</code>```

Output:

```<code>[ 'a', 'b', 'c', 'D', 'E', 'F' ]
</code>```

Body:
I am trying to sort an array in typescript case insensitively. In javascript, that could be accomplished with

    list.sort(function (a, b) {
      return a.toLowerCase().localeCompare(b.toLowerCase());
    });

In typescript the sort looks like

    list.sort((a, b) => {
      if (a > b) {
        return 1;
      }
      if (a < b) {
        return -1;
      }
      return 0;
    });

Starting with [F, E, D, c, b, a] I expect to get [a, b, c, D, E, F]

The javascript sort delivers the expected results, but the typescript sort returns [D, E, F, a, b, c]. How do I make the typescript sort case insensitive?

EDIT: the reason I can't use the javascript method is because in typescript a and b are boolean and don't have ,toLowerCase() method

Body:
Try this sort function. It's basically a rewrite of what you have but it may be a bit cleaner. It also works. The compiler wants a type. It doesn't care if it's string or any in this case. I have updated the answer to change the types passed in into strings. It works for this array as easily well as type any.

function sortStrings(a: string, b: string) {
    a = a.toLowerCase();
    b = b.toLowerCase();
    return a > b ? 1 : (a < b ? -1 : 0);
}

console.log(['F', 'E', 'D', 'c', 'b', 'a'].sort(sortStrings));

Output:

[ 'a', 'b', 'c', 'D', 'E', 'F' ]


问:
Jpanel is not repainting properly
I'm making a pacman game using java swing.
in my code i use 2 jpanels in the component panel
the first is for the map and the second is for the pacman.
now i am trying to move pacman to other cell when a button is clicked.it is moved but the old picture is not deleted.image before clicking, image after clicking
as you can see the new pacman appears but the old didn't disappear. and some trash also appeared.
this is the code of creating the jpanel for the pacman

```<code>JLabel pacman = new JLabel("", new ImageIcon("pacman.png"), JLabel.CENTER);
    player = new JPanel(new BorderLayout());
    player.setBounds(n*1, n*1, n, n);
    //pacman.setOpaque(true);
    pacman.setBackground(new Color(0, 0, 0, 0));
    player.add(pacman);
    //player.setOpaque(true);
    player.setBackground(new Color(0, 0, 0, 0));
    contentPane.setLayout(null);

    JPanel panel = new JPanel();
    panel.setBounds(0, 0, 1000, 1000);
    panel.setLayout(null);
    panel.add(player);
    panel.setBackground(new Color(0, 0, 0,0));
    contentPane.add(panel);
</code>```

the code inside the button actionPreformed method is :

```<code>            panel.remove(player);
            player.setLocation(new Point(n*1, n*2));
            panel.add(player);
            panel.revalidate();
            panel.repaint();
</code>```

how can i make the old pacman disappears ?

答:
```<code>player.setBackground(new Color(0, 0, 0, 0));
</code>```

Don't use transparent colors. Swing does not handle transparency properly.

For full transparency there is a simple solution. Just make the component transparent:

```<code>player.setOpaque( false );
</code>```

If you ever need partial transparency then check out Backgrounds With Transparency for a solution.

Title: Jpanel is not repainting properly

Body:
I'm making a pacman game using java swing.
in my code i use 2 jpanels in the component panel
the first is for the map and the second is for the pacman.
now i am trying to move pacman to other cell when a button is clicked.it is moved but the old picture is not deleted.image before clicking, image after clicking
as you can see the new pacman appears but the old didn't disappear. and some trash also appeared.
this is the code of creating the jpanel for the pacman

JLabel pacman = new JLabel("", new ImageIcon("pacman.png"), JLabel.CENTER);
    player = new JPanel(new BorderLayout());
    player.setBounds(n*1, n*1, n, n);
    //pacman.setOpaque(true);
    pacman.setBackground(new Color(0, 0, 0, 0));
    player.add(pacman);
    //player.setOpaque(true);
    player.setBackground(new Color(0, 0, 0, 0));
    contentPane.setLayout(null);

    JPanel panel = new JPanel();
    panel.setBounds(0, 0, 1000, 1000);
    panel.setLayout(null);
    panel.add(player);
    panel.setBackground(new Color(0, 0, 0,0));
    contentPane.add(panel);

the code inside the button actionPreformed method is :

            panel.remove(player);
            player.setLocation(new Point(n*1, n*2));
            panel.add(player);
            panel.revalidate();
            panel.repaint();

how can i make the old pacman disappears ?

Body:
player.setBackground(new Color(0, 0, 0, 0));

Don't use transparent colors. Swing does not handle transparency properly.

For full transparency there is a simple solution. Just make the component transparent:

player.setOpaque( false );

If you ever need partial transparency then check out Backgrounds With Transparency for a solution.


问:
python object as argument of a function
I know that python pass object by reference, but why the second output of codes below is 3 other than 10?</p>

```<code>class a():
    def __init__(self, value):
        self.value = value

def test(b):
    b = a(10)

b = a(3)
print(b.value)
test(b)
print(b.value)
</code>```

答: Python objects are passed by value, where the value is a reference. The line b = a(3) creates a new object and puts the label b on it. b is not the object, it's just a label which happens to be on the object. When you call test(b), you copy the label b and pass it into the function, making the function's local b (which shadows the global b) also a label on the same object. The two b labels are not tied to each other in any way - they simply happen to both be currently on the same object. So the line b = a(10) inside the function simply creates a new object and places the local b label onto it, leaving the global b exactly as it was.

Title: python object as argument of a function

Body:
I know that python pass object by reference, but why the second output of codes below is 3 other than 10?

class a():
    def __init__(self, value):
        self.value = value

def test(b):
    b = a(10)

b = a(3)
print(b.value)
test(b)
print(b.value)


问:
Angular 2/Javascript AWS S3 SDK - Abort Upload onClick
I am working in Angular 2 and have implemented an S3 upload through the javascript AWS S3 SDK. The question I have is how do I abort the upload via a button click?

So far I have tried below but I get an 'Undefined is not an object (evaluating 'this.bucket.abort.bind')

My Upload Function:

```<code>upload(): void {
AWS.config.update({
    region: AWSREGION,
    credentials: new AWS.CognitoIdentityCredentials(
        {
            IdentityPoolId: AWSIDENTITYPOOLID,
            IdentityId: obj.IdentityId,
            Logins: {
                'cognito-identity.amazonaws.com': obj.Token
            }
        }
    )
});
this.awsToken = obj.Token;
// set bucket
this.bucket = new AWS.S3({params: {Bucket: 'myBucket'}});
// Upload to S3
          this.bucket.putObject(params, (err, data) => {
            if (err) {
                console.log('AWS Error', err);
            } else {
              // Success
              console.log('Success');
            }
           });
}
</code>```

My Cancel Button

```<code> cancel(): void {

    this.bucket.abort.bind(this.bucket);
  }
</code>```

答:
The following end up working:

```<code>upload(): void {
AWS.config.update({
    region: AWSREGION,
    credentials: new AWS.CognitoIdentityCredentials(
        {
            IdentityPoolId: AWSIDENTITYPOOLID,
            IdentityId: obj.IdentityId,
            Logins: {
                'cognito-identity.amazonaws.com': obj.Token
            }
        }
    )
});
this.awsToken = obj.Token;
// set bucket
this.bucket = new AWS.S3({params: {Bucket: 'myBucket'}});
// Set request
this.request = this.bucket.putObject(params);
// Upload to S3
          this.request.send((err, data) => {
            if (err) {
                console.log('AWS Error', err);
            } else {
              // Success
              console.log('Success');
            }
           });
}
</code>```

My Cancel Button

```<code> cancel(): void {

    this.request.abort();
  }
</code>```

Body:
I am working in Angular 2 and have implemented an S3 upload through the javascript AWS S3 SDK. The question I have is how do I abort the upload via a button click?

So far I have tried below but I get an 'Undefined is not an object (evaluating 'this.bucket.abort.bind')

My Upload Function:

upload(): void {
AWS.config.update({
    region: AWSREGION,
    credentials: new AWS.CognitoIdentityCredentials(
        {
            IdentityPoolId: AWSIDENTITYPOOLID,
            IdentityId: obj.IdentityId,
            Logins: {
                'cognito-identity.amazonaws.com': obj.Token
            }
        }
    )
});
this.awsToken = obj.Token;
// set bucket
this.bucket = new AWS.S3({params: {Bucket: 'myBucket'}});
// Upload to S3
          this.bucket.putObject(params, (err, data) => {
            if (err) {
                console.log('AWS Error', err);
            } else {
              // Success
              console.log('Success');
            }
           });
}

My Cancel Button

 cancel(): void {

    this.bucket.abort.bind(this.bucket);
  }

Body:
The following end up working:

upload(): void {
AWS.config.update({
    region: AWSREGION,
    credentials: new AWS.CognitoIdentityCredentials(
        {
            IdentityPoolId: AWSIDENTITYPOOLID,
            IdentityId: obj.IdentityId,
            Logins: {
                'cognito-identity.amazonaws.com': obj.Token
            }
        }
    )
});
this.awsToken = obj.Token;
// set bucket
this.bucket = new AWS.S3({params: {Bucket: 'myBucket'}});
// Set request
this.request = this.bucket.putObject(params);
// Upload to S3
          this.request.send((err, data) => {
            if (err) {
                console.log('AWS Error', err);
            } else {
              // Success
              console.log('Success');
            }
           });
}

My Cancel Button

 cancel(): void {

    this.request.abort();
  }


问:
Making static ReentrantLocks
I've stumbled upon this thread some time ago: Does making a reentrant lock static and make it a mutex? and I have an additional question on my own:

Im interested if creating a private static final ReentrantLock lock is not considered a code smell? I've read that static variables are evil, yet my current use case Im working on looks like ideal place to use one.

Anyone care to help?

Edit with details: I have this class, call it FileProcessor which does a given job in another thread. My use case is spinning up a few of these instances of this class and doing those jobs. But what I want to do is to make sure only one of them will make this job at once and they will take turns in performing the work.

So I figured out Ill give them a static ReentrantLock that will lock() as first thing in run() block and unlock() as last. This way they have a shared lock that will guard the processing synchronization.

Thanks.

答:
Using a static Lock for synchronization at the class level is absolutely normal. You can also use

```<code>synchronized (FileProcessor.class) {
    //your code
}
</code>```

Title: Making static ReentrantLocks

Body:
Using a static Lock for synchronization at the class level is absolutely normal. You can also use

synchronized (FileProcessor.class) {
    //your code
}


问:
Pass additional parameters to post_save signal
I have a user registration form in my Django application which collects additional data while a user is trying to register such as address, city, country, phone number etc.

This data is saved in the Account model class through post_save signal. The user creation process goes something like this :

```<code># Function to Create user Account/Profile
def create_user_account(sender, instance, created, **kwargs):
    if created:
      models.Account.objects.create(user=instance)

# Create User / User Registration
def UserRegistration(request):
    if request.method == 'POST':
        username = request.POST['fn'].capitalize() + ' ' + request.POST['ln'].capitalize()
        # CREATE USER
        newuser = User.objects.create_user(username=username, email=request.POST['email'], password=request.POST['pw'])
        newuser.first_name = request.POST['fn'].capitalize()
        newuser.last_name = request.POST['ln'].capitalize()
        newuser.save()
    return HttpResponse(username)

#Post Save handler to create user Account/Profile
post_save.connect(create_user_account, sender=User)
</code>```

Here the UserRegistration function is called when a user posts a form and under this function, I can get the POST data, what I want is to pass that data to create_user_account method so that it fills in the fields in the Account model.

Right now, I do see Account objects created in the database, but all the fields except the user field are empty. Obviously, because the POST variables are not being passed to the create_user_account method.

答:
Both User.objects.create_user and User.objects.create immediately triggers the post_save handler, because the save is called in the UserManager create_user. So I cannot imagine how Jorge's answer can work (at least if you want the save to be triggered only once - why would you trigger it twice???). What you want to do is to look into what create_user does, dissect it and this way you can really control when the save is called:

```<code># Function to Create user Account/Profile
def create_user_account(sender, instance, created, **kwargs):
    if created:
        attrs_needed = ['_language', '_field', '_otherfield']
        if all(hasattr(instance, attr) for attr in attr_needed):
            models.Account.objects.create(
                user=instance,
                language=instance._language,
                field=instance._field,
                otherfield=instance._otherfield)

# Create User / User Registration
def UserRegistration(request):
  if request.method == 'POST':
    username = request.POST['fn'].capitalize() + ' ' + request.POST['ln'].capitalize()
    # CREATE USER
    newuser = User(
        username=username,
        email=request.POST['email'],
        first_name=request.POST['fn'].capitalize()
        last_name = request.POST['ln'].capitalize()
    )
    newuser.set_password(request.POST['pw'])

    # Set some extra attrs to the instance to be used in the handler.
    newuser._language = request.POST['language']
    newuser._field = request.POST['field']
    newuser._otherfield = request.POST['otherfield']
    newuser.save()  # Now this will be really the first save which is called

  return HttpResponse(username)

#Post Save handler to create user Account/Profile
post_save.connect(create_user_account, sender=User, weak=False)
</code>```

Note that I also use the weak=False when I hook up the handler.

Body:
I have a user registration form in my Django application which collects additional data while a user is trying to register such as address, city, country, phone number etc.

This data is saved in the Account model class through post_save signal. The user creation process goes something like this :

# Function to Create user Account/Profile
def create_user_account(sender, instance, created, **kwargs):
    if created:
      models.Account.objects.create(user=instance)

# Create User / User Registration
def UserRegistration(request):
    if request.method == 'POST':
        username = request.POST['fn'].capitalize() + ' ' + request.POST['ln'].capitalize()
        # CREATE USER
        newuser = User.objects.create_user(username=username, email=request.POST['email'], password=request.POST['pw'])
        newuser.first_name = request.POST['fn'].capitalize()
        newuser.last_name = request.POST['ln'].capitalize()
        newuser.save()
    return HttpResponse(username)

#Post Save handler to create user Account/Profile
post_save.connect(create_user_account, sender=User)

Here the UserRegistration function is called when a user posts a form and under this function, I can get the POST data, what I want is to pass that data to create_user_account method so that it fills in the fields in the Account model.

Right now, I do see Account objects created in the database, but all the fields except the user field are empty. Obviously, because the POST variables are not being passed to the create_user_account method.

Body:
Both User.objects.create_user and User.objects.create immediately triggers the post_save handler, because the save is called in the UserManager create_user. So I cannot imagine how Jorge's answer can work (at least if you want the save to be triggered only once - why would you trigger it twice???). What you want to do is to look into what create_user does, dissect it and this way you can really control when the save is called:

# Function to Create user Account/Profile
def create_user_account(sender, instance, created, **kwargs):
    if created:
        attrs_needed = ['_language', '_field', '_otherfield']
        if all(hasattr(instance, attr) for attr in attr_needed):
            models.Account.objects.create(
                user=instance,
                language=instance._language,
                field=instance._field,
                otherfield=instance._otherfield)

# Create User / User Registration
def UserRegistration(request):
  if request.method == 'POST':
    username = request.POST['fn'].capitalize() + ' ' + request.POST['ln'].capitalize()
    # CREATE USER
    newuser = User(
        username=username,
        email=request.POST['email'],
        first_name=request.POST['fn'].capitalize()
        last_name = request.POST['ln'].capitalize()
    )
    newuser.set_password(request.POST['pw'])

    # Set some extra attrs to the instance to be used in the handler.
    newuser._language = request.POST['language']
    newuser._field = request.POST['field']
    newuser._otherfield = request.POST['otherfield']
    newuser.save()  # Now this will be really the first save which is called

  return HttpResponse(username)

#Post Save handler to create user Account/Profile
post_save.connect(create_user_account, sender=User, weak=False)

Note that I also use the weak=False when I hook up the handler.


问:
Pandas - set datetime / Timestamp value with apply
Lets consider the following dataframe:

```<code>a=pd.DataFrame(data=list(range(10)))
</code>```

Trying to create a new column from it with apply:
The column is supposed to contain Timestamp object

```<code>def test(x):
    x["date"]=pd.Timestamp("2017-01-01")
    return x

a.apply(test,axis=1)
</code>```

However this result in a dataframe containing the .value numerical attribute of the timestamp:

```<code>    0   date
0   0   1483228800000000000
1   1   1483228800000000000
2   2   1483228800000000000
3   3   1483228800000000000
4   4   1483228800000000000
5   5   1483228800000000000
6   6   1483228800000000000
7   7   1483228800000000000
8   8   1483228800000000000
9   9   1483228800000000000
</code>```

How come it is so? How can I get the correct Timestamp in the DataFrame?

Edit: here the full code that is giving me problem:
This is for respondant to understand that i am not trying to set a simply formed list of datetimes to a new column:

```<code>def mae(x):
    entry=x.name[0]
    exit=x.name[1]
    m=d.loc[entry:exit,"close"]
    if x.dir==-1:
        r=(m.sub(m[::-1].cummax()[::-1])).abs().max()
        imax=(m.sub(m[::-1].cummax()[::-1])).idxmin()
    elif x.dir==1:
        r=(m.sub(m[::-1].cummin()[::-1])).abs().max()
        imax=(m.sub(m[::-1].cummin()[::-1])).idxmax()
    else: r=0
    x['mae']=r*gbp['multiplier']
    x['peak']=imax
    return x

k=g.head().apply(mae,axis=1)
</code>```

This takes as input another dataframe and some financial prices data stored in a database - so a bit difficult to invent an example that at the same time is simple enough for people to grab it quickly and complicated enough as to justify the use of .apply.

I think there is something i dont understand / or a bug in the .apply function - this is what i would like to have input and help on. Thanks guys!

答:
I think you just need to inform Pandas that the column should be interpreted as a Datetime:

```<code>a = pd.DataFrame(data=list(range(10)))
def test(x):
    x['date'] = pd.Timestamp('2017-01-01')
    return x

a = a.apply(test, axis=1)
a.date = a.date.astype('datetime64[ns]')
</code>```

This gives:

```<code>    0   date
0   0   2017-01-01
1   1   2017-01-01
2   2   2017-01-01
3   3   2017-01-01
4   4   2017-01-01
5   5   2017-01-01
6   6   2017-01-01
7   7   2017-01-01
8   8   2017-01-01
9   9   2017-01-01
</code>```

Alternatively, I was able to do this by creating the column first and setting its type:

```<code>a = pd.DataFrame(data=list(range(10)))
a['date'] = None
a.date.astype('datetime64[ns]')

def test(x):
    x['date'] = pd.Timestamp('2017-01-01')
    return x

a = a.apply(test, axis=1)
</code>```

Body:
Lets consider the following dataframe:

a=pd.DataFrame(data=list(range(10)))

Trying to create a new column from it with apply:
The column is supposed to contain Timestamp object

def test(x):
    x["date"]=pd.Timestamp("2017-01-01")
    return x

a.apply(test,axis=1)

However this result in a dataframe containing the .value numerical attribute of the timestamp:

    0   date
0   0   1483228800000000000
1   1   1483228800000000000
2   2   1483228800000000000
3   3   1483228800000000000
4   4   1483228800000000000
5   5   1483228800000000000
6   6   1483228800000000000
7   7   1483228800000000000
8   8   1483228800000000000
9   9   1483228800000000000

How come it is so? How can I get the correct Timestamp in the DataFrame?

Edit: here the full code that is giving me problem:
This is for respondant to understand that i am not trying to set a simply formed list of datetimes to a new column:

def mae(x):
    entry=x.name[0]
    exit=x.name[1]
    m=d.loc[entry:exit,"close"]
    if x.dir==-1:
        r=(m.sub(m[::-1].cummax()[::-1])).abs().max()
        imax=(m.sub(m[::-1].cummax()[::-1])).idxmin()
    elif x.dir==1:
        r=(m.sub(m[::-1].cummin()[::-1])).abs().max()
        imax=(m.sub(m[::-1].cummin()[::-1])).idxmax()
    else: r=0
    x['mae']=r*gbp['multiplier']
    x['peak']=imax
    return x

k=g.head().apply(mae,axis=1)

This takes as input another dataframe and some financial prices data stored in a database - so a bit difficult to invent an example that at the same time is simple enough for people to grab it quickly and complicated enough as to justify the use of .apply.

I think there is something i dont understand / or a bug in the .apply function - this is what i would like to have input and help on. Thanks guys!

Body:
I think you just need to inform Pandas that the column should be interpreted as a Datetime:

a = pd.DataFrame(data=list(range(10)))
def test(x):
    x['date'] = pd.Timestamp('2017-01-01')
    return x

a = a.apply(test, axis=1)
a.date = a.date.astype('datetime64[ns]')

This gives:

    0   date
0   0   2017-01-01
1   1   2017-01-01
2   2   2017-01-01
3   3   2017-01-01
4   4   2017-01-01
5   5   2017-01-01
6   6   2017-01-01
7   7   2017-01-01
8   8   2017-01-01
9   9   2017-01-01

Alternatively, I was able to do this by creating the column first and setting its type:

a = pd.DataFrame(data=list(range(10)))
a['date'] = None
a.date.astype('datetime64[ns]')

def test(x):
    x['date'] = pd.Timestamp('2017-01-01')
    return x

a = a.apply(test, axis=1)


问:
Change date format in a Java string
I've a String representing a date.

```<code>String date_s = "2011-01-18 00:00:00.0";
</code>```

I'd like to convert it to a Date and output it in YYYY-MM-DD format.

2011-01-18

How can I achieve this?

Okay, based on the answers I retrieved below, here's something I've tried:

```<code>String date_s = " 2011-01-18 00:00:00.0";
SimpleDateFormat dt = new SimpleDateFormat("yyyyy-mm-dd hh:mm:ss");
Date date = dt.parse(date_s);
SimpleDateFormat dt1 = new SimpleDateFormat("yyyyy-mm-dd");
System.out.println(dt1.format(date));
</code>```

But it outputs 02011-00-1 instead of the desired 2011-01-18. What am I doing wrong?

答:
Use LocalDateTime#parse() (or ZonedDateTime#parse() if the string happens to contain a time zone part) to parse a String in a certain pattern into a LocalDateTime.

```<code>String oldstring = "2011-01-18 00:00:00.0";
LocalDateTime datetime = LocalDateTime.parse(oldstring, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S"));
</code>```

Then use LocalDateTime#format() (or ZonedDateTime#format()) to format a LocalDateTime into a String in a certain pattern.

```<code>String newstring = datetime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
System.out.println(newstring); // 2011-01-18
</code>```

Or, when you're not on Java 8 yet, use SimpleDateFormat#parse() to parse a String in a certain pattern into a Date.

```<code>String oldstring = "2011-01-18 00:00:00.0";
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").parse(oldstring);
</code>```

Then use SimpleDateFormat#format() to format a Date into a String in a certain pattern.

```<code>String newstring = new SimpleDateFormat("yyyy-MM-dd").format(date);
System.out.println(newstring); // 2011-01-18
</code>```

See also:

Java string to date conversion

Update: as per your failed attempt which you added to the question after this answer was posted; the patterns are case sensitive. Carefully read the java.text.SimpleDateFormat javadoc what the individual parts stands for. So stands for example M for months and m for minutes. Also, years exist of four digits yyyy, not five yyyyy. Look closer at the code snippets I posted here above.

Title: Change date format in a Java string

Body:
I've a String representing a date.

String date_s = "2011-01-18 00:00:00.0";

I'd like to convert it to a Date and output it in YYYY-MM-DD format.

2011-01-18

How can I achieve this?

Okay, based on the answers I retrieved below, here's something I've tried:

String date_s = " 2011-01-18 00:00:00.0";
SimpleDateFormat dt = new SimpleDateFormat("yyyyy-mm-dd hh:mm:ss");
Date date = dt.parse(date_s);
SimpleDateFormat dt1 = new SimpleDateFormat("yyyyy-mm-dd");
System.out.println(dt1.format(date));

But it outputs 02011-00-1 instead of the desired 2011-01-18. What am I doing wrong?

Body:
Use LocalDateTime#parse() (or ZonedDateTime#parse() if the string happens to contain a time zone part) to parse a String in a certain pattern into a LocalDateTime.

String oldstring = "2011-01-18 00:00:00.0";
LocalDateTime datetime = LocalDateTime.parse(oldstring, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S"));

Then use LocalDateTime#format() (or ZonedDateTime#format()) to format a LocalDateTime into a String in a certain pattern.

String newstring = datetime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
System.out.println(newstring); // 2011-01-18

Or, when you're not on Java 8 yet, use SimpleDateFormat#parse() to parse a String in a certain pattern into a Date.

String oldstring = "2011-01-18 00:00:00.0";
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").parse(oldstring);

Then use SimpleDateFormat#format() to format a Date into a String in a certain pattern.

String newstring = new SimpleDateFormat("yyyy-MM-dd").format(date);
System.out.println(newstring); // 2011-01-18

See also:

Java string to date conversion

Update: as per your failed attempt which you added to the question after this answer was posted; the patterns are case sensitive. Carefully read the java.text.SimpleDateFormat javadoc what the individual parts stands for. So stands for example M for months and m for minutes. Also, years exist of four digits yyyy, not five yyyyy. Look closer at the code snippets I posted here above.


答:
You did not return a value from the function to put into the class.  This means the 'b' is irrelevant and does nothing.  The only connection is the name 'b'

You need to reassign the value 'b' to be able to call the class.

class a():

```<code>def __init__(self, value):
        self.value = value

def test(b):
    b = a(10)
    return b

b = a(3)
print(b.value)

b = test(3)
print(b.value)
</code>```

Title: python object as argument of a function

Body:
You did not return a value from the function to put into the class.  This means the 'b' is irrelevant and does nothing.  The only connection is the name 'b'

You need to reassign the value 'b' to be able to call the class.

class a():

def __init__(self, value):
        self.value = value

def test(b):
    b = a(10)
    return b

b = a(3)
print(b.value)

b = test(3)
print(b.value)


答: You are using double qoute for entire. Echo statement that's fine but also using double qoute inside the same statement which is wrong.  Change that to single quotes. </p>

Body:
I am trying to make a chart on php which when the number is 2/4/6/8/10 ... etc. The number will be on white color and it's box on green color, and when the number is 1/3/5/7/9 ... etc, the number will be on black color and it's box on red color.

Everything is ok but when I am adding style="color:white(/black);" and style="background-color:red(/green);" on the  and I am saving it, my window is telling me there is a mistake background-color/color ... etc. on this line. Can somebody help me?

Here is my code:

<?php
    echo '
'
    for ($i=1; $i<=10; $i++) {
        echo "

";
        for ($j=1; $j<=10; $j++) {
            $t= $i * $j;
            if ($j%2==1) {
                echo " $t 	";
                } else  {
                echo "  $t 	";
                }
        }
    }
    echo '
';
?>

I have included the html/head/body etc.


问:
How to find out which files / buckets are being publically downloaded the most?
I'm using Google Cloud Storage for a few of my websites by storing static & downloadable content like css, js, images, pdf etc.

How can I find out which of my files and in which bucket is being downloaded a lot ?

My billing just shows :
Cloud Storage Download APAC: 924.637 Gibibytes (Source:Google Storage Project [gs-project-name]) - US$110.84

This is a lot for a month and I want to delete those files.

Is there any stats for this ?

答:
The currently available way to view your usage broken down by bucket or object is to enable access logs for each bucket. Once enabled, GCS will export CSV files that contain information about all requests made to objects in those buckets. This information can be aggregated to find to top objects / buckets that are being downloaded:

See: https://cloud.google.com/storage/docs/access-logs

Create a bucket to store the usage logs:

```<code>gsutil mb gs://my-logs-bucket
gsutil acl ch -g cloud-storage-analytics@google.com:W gs://my-logs-bucket
gsutil defacl set project-private gs://my-logs-bucket
</code>```

Enable usage logging for all your buckets:

```<code>gsutil logging set on -b gs://my-logs-bucket gs://my-bucket1
gsutil logging set on -b gs://my-logs-bucket gs://my-bucket2
..
</code>```

At the end of the month, either download the CSVs in gs://my-logs-bucket and analyse them, or load them into BigQuery for analysis:

```<code>wget http://storage.googleapis.com/pub/cloud_storage_usage_schema_v0.json
bq mk storageanalysis
bq load --skip_leading_rows=1 storageanalysis.usage \
  gs://my-logs-bucket/*_usage_* ./cloud_storage_usage_schema.json

bq shell
> SELECT cs_object, SUM(sc_bytes) AS sc_bytes
  FROM [storageanalysis.usage]
  ORDER BY sc_bytes desc LIMIT 20
..
> SELECT cs_bucket, SUM(sc_bytes) AS sc_bytes
  FROM [storageanalysis.usage]
  ORDER BY sc_bytes desc LIMIT 20
..
> QUIT
</code>```

Body:
The currently available way to view your usage broken down by bucket or object is to enable access logs for each bucket. Once enabled, GCS will export CSV files that contain information about all requests made to objects in those buckets. This information can be aggregated to find to top objects / buckets that are being downloaded:

See: https://cloud.google.com/storage/docs/access-logs

Create a bucket to store the usage logs:

gsutil mb gs://my-logs-bucket
gsutil acl ch -g cloud-storage-analytics@google.com:W gs://my-logs-bucket
gsutil defacl set project-private gs://my-logs-bucket

Enable usage logging for all your buckets:

gsutil logging set on -b gs://my-logs-bucket gs://my-bucket1
gsutil logging set on -b gs://my-logs-bucket gs://my-bucket2
..

At the end of the month, either download the CSVs in gs://my-logs-bucket and analyse them, or load them into BigQuery for analysis:

wget http://storage.googleapis.com/pub/cloud_storage_usage_schema_v0.json
bq mk storageanalysis
bq load --skip_leading_rows=1 storageanalysis.usage \
  gs://my-logs-bucket/*_usage_* ./cloud_storage_usage_schema.json

bq shell
> SELECT cs_object, SUM(sc_bytes) AS sc_bytes
  FROM [storageanalysis.usage]
  ORDER BY sc_bytes desc LIMIT 20
..
> SELECT cs_bucket, SUM(sc_bytes) AS sc_bytes
  FROM [storageanalysis.usage]
  ORDER BY sc_bytes desc LIMIT 20
..
> QUIT


问:
SSL encrypted connection to MySQL container not possible over AWS elastic load balancer
I am trying to establish a SSL-encrypted connection to a my MySQL Docker service running on a AWS VPC (setup up by the Docker for AWS cloud formation template). The elastic load balancer is configured to redirect port 3306. There is no problem to connect to the container (e.g. by using MySQLWorkbench, mysql-client, ..) as long as SSL is not turned on (adding AWS's own certificates (ACM) or my custom certificates to the ELB listener). In case SSL is enabled, the client starts hanging / freezing, without returning a proper error. I added the ca-certs from ACM, generated my own certificates (with and without additonal key / cert for the client) but nothing seems to resolve my problem.

Now I am well aware of the fact, that this setup is not that usual. I guess the standard way of doing this is to configure the MySQL-Server itself. AFAIK, in this case only the connection between client and ELB is encrypted, but I do not understand why this causes a problem?

I am grateful for answers!

答:
In MySQL's client/server protocol, the server talks first.  It advertises its capabilities (including whether it supports SSL).  Then the client requests that the connection switch to SSL mode.  Only then does SSL negotiation take place.

For this reason, it is not possible to offload SSL in front of MySQL.

Your connection hangs because the client is waiting for the initial packet from the server, while the ELB is waiting for the client to start negotiating SSL -- because unlike the MySQL client/server protocol, the client talks first on standard SSL negotiation.

You have to have a certificate on the MySQL Server, and not on the ELB, for this to work.

An AWS Network Load Balancer is a more appropriate solution for exposing MySQL, but you still need the SSL cert on the MySQL Server itself.