问:
Can't access Tomcat launched in Docker container
I'm launching Tomcat as a Docker container:

```<code>$ docker run -dP tomcat
</code>```

And the process starts correctly:

```<code>$ docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED              STATUS              PORTS                     NAMES
48b87e545c18        tomcat              "catalina.sh run"   About a minute ago   Up About a minute   0.0.0.0:32769->8080/tcp   hopeful_ardinghelli

$ docker logs 48b87e545c18
16-Sep-2015 17:16:38.027 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server version:        Apache Tomcat/8.0.26
16-Sep-2015 17:16:38.037 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server built:          Aug 18 2015 11:38:37 UTC
16-Sep-2015 17:16:38.037 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server number:         8.0.26.0
16-Sep-2015 17:16:38.038 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log OS Name:               Linux
16-Sep-2015 17:16:38.038 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log OS Version:            4.0.9-boot2docker
16-Sep-2015 17:16:38.038 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Architecture:          amd64
16-Sep-2015 17:16:38.039 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Java Home:             /usr/lib/jvm/java-7-openjdk-amd64/jre
16-Sep-2015 17:16:38.039 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log JVM Version:           1.7.0_79-b14
16-Sep-2015 17:16:38.040 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log JVM Vendor:            Oracle Corporation
16-Sep-2015 17:16:38.040 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log CATALINA_BASE:         /usr/local/tomcat
16-Sep-2015 17:16:38.041 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log CATALINA_HOME:         /usr/local/tomcat
16-Sep-2015 17:16:38.041 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.util.logging.config.file=/usr/local/tomcat/conf/logging.properties
16-Sep-2015 17:16:38.042 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager
16-Sep-2015 17:16:38.042 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.endorsed.dirs=/usr/local/tomcat/endorsed
16-Sep-2015 17:16:38.043 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcatalina.base=/usr/local/tomcat
16-Sep-2015 17:16:38.043 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcatalina.home=/usr/local/tomcat
16-Sep-2015 17:16:38.044 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.io.tmpdir=/usr/local/tomcat/temp
16-Sep-2015 17:16:38.044 INFO [main] org.apache.catalina.core.AprLifecycleListener.lifecycleEvent The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: /usr/java/packages/lib/amd64:/usr/lib/x86_64-linux-gnu/jni:/lib/x86_64-linux-gnu:/usr/lib/x86_64-linux-gnu:/usr/lib/jni:/lib:/usr/lib
16-Sep-2015 17:16:38.226 INFO [main] org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler ["http-nio-8080"]
16-Sep-2015 17:16:38.267 INFO [main] org.apache.tomcat.util.net.NioSelectorPool.getSharedSelector Using a shared selector for servlet write/read
16-Sep-2015 17:16:38.272 INFO [main] org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler ["ajp-nio-8009"]
16-Sep-2015 17:16:38.274 INFO [main] org.apache.tomcat.util.net.NioSelectorPool.getSharedSelector Using a shared selector for servlet write/read
16-Sep-2015 17:16:38.282 INFO [main] org.apache.catalina.startup.Catalina.load Initialization processed in 1251 ms
16-Sep-2015 17:16:38.325 INFO [main] org.apache.catalina.core.StandardService.startInternal Starting service Catalina
16-Sep-2015 17:16:38.341 INFO [main] org.apache.catalina.core.StandardEngine.startInternal Starting Servlet Engine: Apache Tomcat/8.0.26
16-Sep-2015 17:16:38.374 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory /usr/local/tomcat/webapps/host-manager
16-Sep-2015 17:17:16.231 INFO [localhost-startStop-1] org.apache.catalina.util.SessionIdGeneratorBase.createSecureRandom Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [36,979] milliseconds.
16-Sep-2015 17:17:16.276 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /usr/local/tomcat/webapps/host-manager has finished in 37,901 ms
16-Sep-2015 17:17:16.276 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory /usr/local/tomcat/webapps/docs
16-Sep-2015 17:17:16.361 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /usr/local/tomcat/webapps/docs has finished in 85 ms
16-Sep-2015 17:17:16.362 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory /usr/local/tomcat/webapps/examples
16-Sep-2015 17:17:17.221 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /usr/local/tomcat/webapps/examples has finished in 859 ms
16-Sep-2015 17:17:17.242 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory /usr/local/tomcat/webapps/ROOT
16-Sep-2015 17:17:17.343 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /usr/local/tomcat/webapps/ROOT has finished in 101 ms
16-Sep-2015 17:17:17.354 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory /usr/local/tomcat/webapps/manager
16-Sep-2015 17:17:17.452 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /usr/local/tomcat/webapps/manager has finished in 98 ms
16-Sep-2015 17:17:17.460 INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["http-nio-8080"]
16-Sep-2015 17:17:17.484 INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["ajp-nio-8009"]
16-Sep-2015 17:17:17.487 INFO [main] org.apache.catalina.startup.Catalina.start Server startup in 39204 ms
</code>```

But when I hit the server in the browser at the URL http://localhost:32769, I get a connection refused error. I also tried to publish ports explicitly:

```<code>$ docker run -d -p 8888:8080 tomcat
</code>```

Or launch the container in interactive shell mode:

```<code>$ docker run -it -p 8888:8080 tomcat
</code>```

But neither helped: http://localhost:8888 refuses the connection. How would I go about troubleshooting this?

答:
This is because you can't use the localhost to access your docker address.
You have to use the IP that is relates with your virtual network.
You have to check what subnet your docker is running.

Example: The ip address of my notebook is 192.168.1.13 but the IP address of my VirtualMachine where is running 192.168.99.100.

Regards

Body:
I'm launching Tomcat as a Docker container:

$ docker run -dP tomcat

And the process starts correctly:

$ docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED              STATUS              PORTS                     NAMES
48b87e545c18        tomcat              "catalina.sh run"   About a minute ago   Up About a minute   0.0.0.0:32769->8080/tcp   hopeful_ardinghelli

$ docker logs 48b87e545c18
16-Sep-2015 17:16:38.027 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server version:        Apache Tomcat/8.0.26
16-Sep-2015 17:16:38.037 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server built:          Aug 18 2015 11:38:37 UTC
16-Sep-2015 17:16:38.037 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server number:         8.0.26.0
16-Sep-2015 17:16:38.038 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log OS Name:               Linux
16-Sep-2015 17:16:38.038 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log OS Version:            4.0.9-boot2docker
16-Sep-2015 17:16:38.038 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Architecture:          amd64
16-Sep-2015 17:16:38.039 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Java Home:             /usr/lib/jvm/java-7-openjdk-amd64/jre
16-Sep-2015 17:16:38.039 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log JVM Version:           1.7.0_79-b14
16-Sep-2015 17:16:38.040 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log JVM Vendor:            Oracle Corporation
16-Sep-2015 17:16:38.040 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log CATALINA_BASE:         /usr/local/tomcat
16-Sep-2015 17:16:38.041 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log CATALINA_HOME:         /usr/local/tomcat
16-Sep-2015 17:16:38.041 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.util.logging.config.file=/usr/local/tomcat/conf/logging.properties
16-Sep-2015 17:16:38.042 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager
16-Sep-2015 17:16:38.042 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.endorsed.dirs=/usr/local/tomcat/endorsed
16-Sep-2015 17:16:38.043 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcatalina.base=/usr/local/tomcat
16-Sep-2015 17:16:38.043 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcatalina.home=/usr/local/tomcat
16-Sep-2015 17:16:38.044 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.io.tmpdir=/usr/local/tomcat/temp
16-Sep-2015 17:16:38.044 INFO [main] org.apache.catalina.core.AprLifecycleListener.lifecycleEvent The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: /usr/java/packages/lib/amd64:/usr/lib/x86_64-linux-gnu/jni:/lib/x86_64-linux-gnu:/usr/lib/x86_64-linux-gnu:/usr/lib/jni:/lib:/usr/lib
16-Sep-2015 17:16:38.226 INFO [main] org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler ["http-nio-8080"]
16-Sep-2015 17:16:38.267 INFO [main] org.apache.tomcat.util.net.NioSelectorPool.getSharedSelector Using a shared selector for servlet write/read
16-Sep-2015 17:16:38.272 INFO [main] org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler ["ajp-nio-8009"]
16-Sep-2015 17:16:38.274 INFO [main] org.apache.tomcat.util.net.NioSelectorPool.getSharedSelector Using a shared selector for servlet write/read
16-Sep-2015 17:16:38.282 INFO [main] org.apache.catalina.startup.Catalina.load Initialization processed in 1251 ms
16-Sep-2015 17:16:38.325 INFO [main] org.apache.catalina.core.StandardService.startInternal Starting service Catalina
16-Sep-2015 17:16:38.341 INFO [main] org.apache.catalina.core.StandardEngine.startInternal Starting Servlet Engine: Apache Tomcat/8.0.26
16-Sep-2015 17:16:38.374 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory /usr/local/tomcat/webapps/host-manager
16-Sep-2015 17:17:16.231 INFO [localhost-startStop-1] org.apache.catalina.util.SessionIdGeneratorBase.createSecureRandom Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [36,979] milliseconds.
16-Sep-2015 17:17:16.276 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /usr/local/tomcat/webapps/host-manager has finished in 37,901 ms
16-Sep-2015 17:17:16.276 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory /usr/local/tomcat/webapps/docs
16-Sep-2015 17:17:16.361 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /usr/local/tomcat/webapps/docs has finished in 85 ms
16-Sep-2015 17:17:16.362 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory /usr/local/tomcat/webapps/examples
16-Sep-2015 17:17:17.221 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /usr/local/tomcat/webapps/examples has finished in 859 ms
16-Sep-2015 17:17:17.242 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory /usr/local/tomcat/webapps/ROOT
16-Sep-2015 17:17:17.343 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /usr/local/tomcat/webapps/ROOT has finished in 101 ms
16-Sep-2015 17:17:17.354 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory /usr/local/tomcat/webapps/manager
16-Sep-2015 17:17:17.452 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /usr/local/tomcat/webapps/manager has finished in 98 ms
16-Sep-2015 17:17:17.460 INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["http-nio-8080"]
16-Sep-2015 17:17:17.484 INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["ajp-nio-8009"]
16-Sep-2015 17:17:17.487 INFO [main] org.apache.catalina.startup.Catalina.start Server startup in 39204 ms

But when I hit the server in the browser at the URL http://localhost:32769, I get a connection refused error. I also tried to publish ports explicitly:

$ docker run -d -p 8888:8080 tomcat

Or launch the container in interactive shell mode:

$ docker run -it -p 8888:8080 tomcat

But neither helped: http://localhost:8888 refuses the connection. How would I go about troubleshooting this?


来源: stackexchange

问:
Calling a function with arguments within dplyr::do using multidplyr
I'm trying to use multidplyr to speed up getting residuals from a regression fit. I've created a function that fits the regression model to get the residuals, which in addition to the data, gets two more arguments.

Here's the function:

```<code>func <- function(df,reg.mdl,mdl.fmla)
{
  if(reg.mdl == "linear"){
    df$resid <- lm(formula = mdl.fmla, data = df)$residuals
  } else if(reg.mdl == "poisson"){
    df$resid <- residuals(object = glm(formula = mdl.fmla,data = df,family = "poisson"),type='pearson')
  }
  return(df)
}
</code>```

Here's an example data on which I'll try my multidplyr approach:

```<code>set.seed(1)
ds <- data.frame(group=c(rep("a",100), rep("b",100),rep("c",100)),sex=rep(sample(c("F","M"),100,replace=T),3),y=rpois(300,10))
model.formula <- as.formula("y ~ sex")
regression.model <- "poisson"
</code>```

And here's the multidplyr approach:

```<code>ds %>% partition(group) %>% cluster_library("tidyverse") %>%
  cluster_assign_value("func", func) %>%
  do(results = func(df=.,reg.mdl=regression.model,mdl.fmla=model.formula)) %>% collect() %>% .$results %>% bind_rows()
</code>```

This throws this error though:

```<code>Error in checkForRemoteErrors(lapply(cl, recvResult)) :
  3 nodes produced errors; first error: object 'regression.model' not found
In addition: Warning message:
group_indices_.grouped_df ignores extra arguments
</code>```

So I guess the way I'm passing the arguments to func from do is wrong.

Any idea what's the correct way?

答:
Error caused by the fact that clusters don't have such objects in their enviroment. As such it is required to assign variables to cluster process:

```<code>ds %>%
  partition(group) %>%
  cluster_library("tidyverse") %>%
  cluster_assign_value("func", func) %>%
  cluster_copy(regression.model) %>%
  cluster_copy(model.formula) %>%
  do(results = func(
    df = .,
    reg.mdl = regression.model,
    mdl.fmla = model.formula
  )) %>%
  collect() %>%
  .$results %>%
  bind_rows()
</code>```

Or another way (I prefer to set up clusters before chain):

```<code>CL <- makePSOCKcluster(3)
clusterEvalQ(cl = CL, library("tidyverse"))
clusterExport(cl = CL, list("func", "regression.model", "model.formula"))

ds %>%
  partition(group, cluster = CL) %>%
  do(results = func(
    df = .,
    reg.mdl = regression.model,
    mdl.fmla = model.formula
  )) %>%
  collect() %>%
  .$results %>%
  bind_rows()

stopCluster(CL)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to use multidplyr to speed up getting residuals from a regression fit. I've created a function that fits the regression model to get the residuals, which in addition to the data, gets two more arguments.

Here's the function:

func <- function(df,reg.mdl,mdl.fmla)
{
  if(reg.mdl == "linear"){
    df$resid <- lm(formula = mdl.fmla, data = df)$residuals
  } else if(reg.mdl == "poisson"){
    df$resid <- residuals(object = glm(formula = mdl.fmla,data = df,family = "poisson"),type='pearson')
  }
  return(df)
}

Here's an example data on which I'll try my multidplyr approach:

set.seed(1)
ds <- data.frame(group=c(rep("a",100), rep("b",100),rep("c",100)),sex=rep(sample(c("F","M"),100,replace=T),3),y=rpois(300,10))
model.formula <- as.formula("y ~ sex")
regression.model <- "poisson"

And here's the multidplyr approach:

ds %>% partition(group) %>% cluster_library("tidyverse") %>%
  cluster_assign_value("func", func) %>%
  do(results = func(df=.,reg.mdl=regression.model,mdl.fmla=model.formula)) %>% collect() %>% .$results %>% bind_rows()

This throws this error though:

Error in checkForRemoteErrors(lapply(cl, recvResult)) :
  3 nodes produced errors; first error: object 'regression.model' not found
In addition: Warning message:
group_indices_.grouped_df ignores extra arguments

So I guess the way I'm passing the arguments to func from do is wrong.

Any idea what's the correct way?

Body:
Error caused by the fact that clusters don't have such objects in their enviroment. As such it is required to assign variables to cluster process:

ds %>%
  partition(group) %>%
  cluster_library("tidyverse") %>%
  cluster_assign_value("func", func) %>%
  cluster_copy(regression.model) %>%
  cluster_copy(model.formula) %>%
  do(results = func(
    df = .,
    reg.mdl = regression.model,
    mdl.fmla = model.formula
  )) %>%
  collect() %>%
  .$results %>%
  bind_rows()

Or another way (I prefer to set up clusters before chain):

CL <- makePSOCKcluster(3)
clusterEvalQ(cl = CL, library("tidyverse"))
clusterExport(cl = CL, list("func", "regression.model", "model.formula"))

ds %>%
  partition(group, cluster = CL) %>%
  do(results = func(
    df = .,
    reg.mdl = regression.model,
    mdl.fmla = model.formula
  )) %>%
  collect() %>%
  .$results %>%
  bind_rows()

stopCluster(CL)


问:
serialize only one property of a class
I have a class which have about 20 members. I need to serialize my the object of this  class in a XML. But condition is I need only one member in the XML.

How can I do this.

EDIT : But at some time, I would like to serialize all the members. So I can't use [XMLIgnore] attribute.

答:
There is two ways to make properties non-serializable in.NET using attributes.

You may set attributes [NonSerialized] or [XmlIgnore]

If you serializing in binary or SOAP you should use [NonSerialized], if you want to serialize just in XML you should use [XmlIgnore].

So in your case the answer is [XmlIgnore]

EDIT:
There is no way to apply attributes to properties dynamically.
Here some info about that here: Can attributes be added dynamically in C#? and here Remove C# attribute of a property dynamically

Also as a workout you may have different copies of your class with different attributes.

OR

Have a copy of your class set all props as serializable but populate only properties you need, this way every thing else will be null/empty and after serialization of that class you should get the XML you need.

ContentLicense: CC BY-SA 2.5

Title: serialize only one property of a class


问:
Fetch data from database and update is not working
i have this code for the user-edit.php
what i need with this code is to fetch user data from database and show it to the textbox and also the user able to edit the textbox value and updating the database

```<code><?php
    include("config/session.php");
    include("config/connection.php");
    $user_id =  $_SESSION['LOGGED_USER_ID'];
?>

<?php
    $sql_query = "SELECT * FROM table_users WHERE `SNo` = '$user_id'";
    $query = mysql_query($sql_query);
    //$i = 1;
    $fetch = mysql_fetch_assoc($query);

    //$user_id = $_GET['id'];

?>
<form name="form1" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" >
    <fieldset>

        <p>
            <label for="simple-input" >User Name</label>
            <input type="text" id="UserName" class="round default-width-input" autofocus name="UserName" value="<?php echo $fetch['UserName'];?>" readonly="readonly" />
        </p>
        <p>
            <label for="simple-input" >Password</label>
            <input type="text" id="pass_word" class="round default-width-input" autofocus name="pass_word" value="<?php echo $fetch['pass_word'];?>" />
        </p>
        <p>
            <label for="simple-input" >Email ID</label>
            <input type="text" id="Email" class="round default-width-input" autofocus name="Email" value="<?php echo $fetch['Email'];?>" />

        </p>
        <p>
            <label for="simple-input" >Website</label>
            <input type="text" id="website" class="round default-width-input" autofocus name="website" value="<?php echo $fetch['website'];?>" />
        </p>

    </fieldset>

    <input type="submit" class="btn btn-primary btn-large" name="form_submit" value="Update Data"/>

</form>

<?php

if(isset($_POST['form_submit']))
{
    "UPDATE `table_users` SET `pass_word` =  '".$_POST['pass_word']."',`Email` =  '".$_POST['Email']."',`website` =  '".$_POST['website']."', WHERE `SNo` = '$user_id'";

    // sql query for update data into database
    if(mysql_query($sql_query))
     {

      echo '<script type="text/javascript">';
      echo 'alert("Data Are Updated Successfully");';
      echo '</script>';

     }
     else
     {

      echo '<script type="text/javascript">';
      echo 'alert("error occured while updating data");';
      echo '</script>';
    }
    }
?>

        </div>
    </div>
</div>
</code>```

been working with this for hours and still the data are not updated to the mysql database, been trying several way but still the textbox value cant update the database, please help

答:
remove , before where in query

```<code>$sql_query="UPDATE `table_users` SET `pass_word` =  '".$_POST['pass_word']."',`Email` =  '".$_POST['Email']."',`website` =  '".$_POST['website']."' WHERE `SNo` = '$user_id'";
</code>```

store query in $sql_query because you not store update string into variable
 without store in $sql_query you run sql query

if(mysql_query($sql_query)) so store update query in $sql_query

Body:
i have this code for the user-edit.php
what i need with this code is to fetch user data from database and show it to the textbox and also the user able to edit the textbox value and updating the database

<?php
    include("config/session.php");
    include("config/connection.php");
    $user_id =  $_SESSION['LOGGED_USER_ID'];
?>

<?php
    $sql_query = "SELECT * FROM table_users WHERE `SNo` = '$user_id'";
    $query = mysql_query($sql_query);
    //$i = 1;
    $fetch = mysql_fetch_assoc($query);

    //$user_id = $_GET['id'];

?>
<form name="form1" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" >
    <fieldset>

            User Name
            <input type="text" id="UserName" class="round default-width-input" autofocus name="UserName" value="<?php echo $fetch['UserName'];?>" readonly="readonly" />

            Password
            <input type="text" id="pass_word" class="round default-width-input" autofocus name="pass_word" value="<?php echo $fetch['pass_word'];?>" />

            Email ID
            <input type="text" id="Email" class="round default-width-input" autofocus name="Email" value="<?php echo $fetch['Email'];?>" />

            Website
            <input type="text" id="website" class="round default-width-input" autofocus name="website" value="<?php echo $fetch['website'];?>" />

    </fieldset>

    <input type="submit" class="btn btn-primary btn-large" name="form_submit" value="Update Data"/>

</form>

<?php

if(isset($_POST['form_submit']))
{
    "UPDATE `table_users` SET `pass_word` =  '".$_POST['pass_word']."',`Email` =  '".$_POST['Email']."',`website` =  '".$_POST['website']."', WHERE `SNo` = '$user_id'";

    // sql query for update data into database
    if(mysql_query($sql_query))
     {

      echo '';

     }
     else
     {

      echo '';
    }
    }
?>

been working with this for hours and still the data are not updated to the mysql database, been trying several way but still the textbox value cant update the database, please help

Body:
remove , before where in query

$sql_query="UPDATE `table_users` SET `pass_word` =  '".$_POST['pass_word']."',`Email` =  '".$_POST['Email']."',`website` =  '".$_POST['website']."' WHERE `SNo` = '$user_id'";

store query in $sql_query because you not store update string into variable
 without store in $sql_query you run sql query

if(mysql_query($sql_query)) so store update query in $sql_query


问:
Search bar + select tag rails
I have a search bar + a dropdown list to search for restaurants or meals and be able to filter by category (French food, Indian, foot, etc.)

index.html.erb

```<code><%= form_tag meals_path, method: 'get', id: 'products_search' do %>
  <p>
    <%= text_field_tag :search, params[:search] %>
    <%= select_tag :search_category, options_for_select(@categories, @categories[0]) %>
    <%= submit_tag "Rechercher", name: nil %>
  </p>
<% end %>
</code>```

meals_controller.rb

```<code>@meals_search = @meals.search(params[:search], params[:search_category])
</code>```

model/meal.rb

```<code>def self.search(search, search_category)
  if search
    if search && search_category == "All"
    where('name LIKE ?', "%#{search}%")
    elsif search == "" && search_category != "All"
      where('category = ?',  "%#{search_category}%")
    else
      where('name LIKE ? AND category = ?', "%#{search}%", "%#{search_category}%")
    end
  else
    all
  end
end
</code>```

the search bar works perfectly but the category filter (search_category) does not. I actually get an empty list although you can only filter with category that has at least one restaurant or meal (so the list can't be empty).

Any idea ?

答:
OK so, following @vishnuprakash 's suggestion, I used the ransack gem to solve my issue:

I added gem 'ransack' to my Gemfile and ran bundle.

Then I created this form in my index.html.erb:

```<code><%= search_form_for @q do |f| %>

  <%= f.search_field :name_cont %>

  <%= f.select :category_eq, options_for_select(@categories), include_blank: true %>

  <%= f.submit %>
<% end %>
</code>```

and meals_controller.rb:

```<code> @q = @meals.ransack(params[:q])
      @meals_search = @q.result(distinct: true)
</code>```

I also got rid of the function previously created in model/meals.rb.

It now works perfectly ! Do not hesitate to have a look at the ransack dock if you have similar issue. You can also DM me, I'll be happy to help.

Title: Search bar + select tag rails

Body:
I have a search bar + a dropdown list to search for restaurants or meals and be able to filter by category (French food, Indian, foot, etc.)

index.html.erb

<%= form_tag meals_path, method: 'get', id: 'products_search' do %>

    <%= text_field_tag :search, params[:search] %>
    <%= select_tag :search_category, options_for_select(@categories, @categories[0]) %>
    <%= submit_tag "Rechercher", name: nil %>

<% end %>

meals_controller.rb

@meals_search = @meals.search(params[:search], params[:search_category])

model/meal.rb

def self.search(search, search_category)
  if search
    if search && search_category == "All"
    where('name LIKE ?', "%#{search}%")
    elsif search == "" && search_category != "All"
      where('category = ?',  "%#{search_category}%")
    else
      where('name LIKE ? AND category = ?', "%#{search}%", "%#{search_category}%")
    end
  else
    all
  end
end

the search bar works perfectly but the category filter (search_category) does not. I actually get an empty list although you can only filter with category that has at least one restaurant or meal (so the list can't be empty).

Any idea ?

Body:
OK so, following @vishnuprakash 's suggestion, I used the ransack gem to solve my issue:

I added gem 'ransack' to my Gemfile and ran bundle.

Then I created this form in my index.html.erb:

<%= search_form_for @q do |f| %>

  <%= f.search_field :name_cont %>

  <%= f.select :category_eq, options_for_select(@categories), include_blank: true %>

  <%= f.submit %>
<% end %>

and meals_controller.rb:

 @q = @meals.ransack(params[:q])
      @meals_search = @q.result(distinct: true)

I also got rid of the function previously created in model/meals.rb.

It now works perfectly ! Do not hesitate to have a look at the ransack dock if you have similar issue. You can also DM me, I'll be happy to help.


问:
elasticsearch_dsl: Generate multiple buckets in aggregation
I want to generate this:

```<code>GET /packets-2017-09-25/_search
{
  "size": 0,
  "query": {
        "match": {
            "transport_protocol": "tcp"
        }
  },
  "aggs": {
    "clients": {
      "terms": {
        "field": "layers.ip.src.keyword",
        "size": 1000,
        "order":{ "num_servers.value":"desc" }
      },
      "aggs": {
        "num_servers": {
          "cardinality": {
            "field": "layers.ip.dst.keyword",
            "precision_threshold" : 40000
          }
        },
        "server_list": {
          "terms": {
            "field": "layers.ip.dst.keyword"
          }
        }
      }
    }
  }
}
</code>```

i.e I want two buckets (num_servers) and (server_list) under clients.

I am trying the below piece of code, which errors out:

```<code>def get_streams_per_client(proto='tcp', max=40000):
    s = Search(using=client, index="packets-2017-09-25") \
               .query("match", transport_protocol=proto)
    s.aggs.bucket('clients', 'terms', field='layers.ip.src.keyword', size=max, order={"num_servers.value":"desc"})\
    .bucket('num_servers', 'cardinality', field='layers.ip.dst.keyword', precision_threshold=40000)\
    .bucket('server_list', 'terms', field='layers.ip.dst.keyword')
    s = s.execute()
    <snip>
</code>```

I think I am missing on the right syntax. Appreciate some guidance.

答:
Got the answer from Honza on elasticsearch_dsl project page:</p>

```<code>  s = Search(using=client, index="packets-2017-09-25").query('match', transport_protocol=proto)
  s.aggs.bucket('clients', 'terms', field='layers.ip.src.keyword', size=max, order={"num_servers.value":"desc"})
  s.aggs['clients'].bucket('num_servers', 'cardinality', field='layers.ip.dst.keyword', precision_threshold=40000)
  s.aggs['clients'].bucket('server_list', 'terms', field='layers.ip.dst.keyword')
  print json.dumps(s.to_dict(), indent=4)
  s = s.execute()
</code>```

Body:
I want to generate this:

GET /packets-2017-09-25/_search
{
  "size": 0,
  "query": {
        "match": {
            "transport_protocol": "tcp"
        }
  },
  "aggs": {
    "clients": {
      "terms": {
        "field": "layers.ip.src.keyword",
        "size": 1000,
        "order":{ "num_servers.value":"desc" }
      },
      "aggs": {
        "num_servers": {
          "cardinality": {
            "field": "layers.ip.dst.keyword",
            "precision_threshold" : 40000
          }
        },
        "server_list": {
          "terms": {
            "field": "layers.ip.dst.keyword"
          }
        }
      }
    }
  }
}

i.e I want two buckets (num_servers) and (server_list) under clients.

I am trying the below piece of code, which errors out:

def get_streams_per_client(proto='tcp', max=40000):
    s = Search(using=client, index="packets-2017-09-25") \
               .query("match", transport_protocol=proto)
    s.aggs.bucket('clients', 'terms', field='layers.ip.src.keyword', size=max, order={"num_servers.value":"desc"})\
    .bucket('num_servers', 'cardinality', field='layers.ip.dst.keyword', precision_threshold=40000)\
    .bucket('server_list', 'terms', field='layers.ip.dst.keyword')
    s = s.execute()
    <snip>

I think I am missing on the right syntax. Appreciate some guidance.

Body:
Got the answer from Honza on elasticsearch_dsl project page:

  s = Search(using=client, index="packets-2017-09-25").query('match', transport_protocol=proto)
  s.aggs.bucket('clients', 'terms', field='layers.ip.src.keyword', size=max, order={"num_servers.value":"desc"})
  s.aggs['clients'].bucket('num_servers', 'cardinality', field='layers.ip.dst.keyword', precision_threshold=40000)
  s.aggs['clients'].bucket('server_list', 'terms', field='layers.ip.dst.keyword')
  print json.dumps(s.to_dict(), indent=4)
  s = s.execute()


问:
Why is the result of "SELECT ISNULL(LEFT(NULL, 8), '1234567890')" returned as '1' instead of '1234567890'?
I have this query

```<code>SELECT ISNULL(LEFT(NULL, 8), '1234567890')
</code>```

The result I got is '1' instead of '1234567890'. What am I missing?

I'm using SQL Server 2014.

答:
one difference between ISNULL and COALESCE is that ISNULL limits the length of parameters to that of first whereas COALESCE won't. try the following to know the difference</p>

```<code>DECLARE @i AS VARCHAR(4) = NULL,
        @j AS VARCHAR(6) = 'abcdefg'

SELECT ISNULL(@i, @j)
SELECT COALESCE (@i, @j)
</code>```

Body:
I have this query

SELECT ISNULL(LEFT(NULL, 8), '1234567890')

The result I got is '1' instead of '1234567890'. What am I missing?

I'm using SQL Server 2014.

Body:
one difference between ISNULL and COALESCE is that ISNULL limits the length of parameters to that of first whereas COALESCE won't. try the following to know the difference

DECLARE @i AS VARCHAR(4) = NULL,
        @j AS VARCHAR(6) = 'abcdefg'

SELECT ISNULL(@i, @j)
SELECT COALESCE (@i, @j)


问:
React Native, MobX and lifecycle
I'm using MobX in React Native and so far I really lite it.
Is there some lifecycle or method to call a function when the state in Mobx Store is changed?</p>

答:
componentWillReceiveProps can be used in the component level. For instance, observer container will notify the actual component through props (imaginary use case in TypeScript):

```<code>@inject('notificationStore')
@observer
class SomeContainer extends Component<Props> {
  ...

  public render(): JSX.Element {
    <Notification
      message={this.props.notificationStore.message}
      ...
    />
  }
}
</code>```

And in Notification:

```<code>class Notification extends PureComponent<Props> {
  ...
  public componentWillReceiveProps(nextProps: any): void {
    Alert.alert('message', nextProps.message);
  }
}
</code>```

Now, when you mutate notificationStore.message eg. 'Hello world', it will displayed by Notification component.

If you want more direct approach, then you just inject the component with store and observe the changes. Basically your TypeScript interface should look like this:

```<code>interface Props {
  notificationStore?: any;
  ...
}
</code>```

As you can see, store is always considered as a prop and this means the mutation will trigger componentWillReceiveProps lifecycle event.

Hope I explained this clear enough.

Title: React Native, MobX and lifecycle

Body:
componentWillReceiveProps can be used in the component level. For instance, observer container will notify the actual component through props (imaginary use case in TypeScript):

@inject('notificationStore')
@observer
class SomeContainer extends Component<Props> {
  ...

  public render(): JSX.Element {
    <Notification
      message={this.props.notificationStore.message}
      ...
    />
  }
}

And in Notification:

class Notification extends PureComponent<Props> {
  ...
  public componentWillReceiveProps(nextProps: any): void {
    Alert.alert('message', nextProps.message);
  }
}

Now, when you mutate notificationStore.message eg. 'Hello world', it will displayed by Notification component.

If you want more direct approach, then you just inject the component with store and observe the changes. Basically your TypeScript interface should look like this:

interface Props {
  notificationStore?: any;
  ...
}

As you can see, store is always considered as a prop and this means the mutation will trigger componentWillReceiveProps lifecycle event.

Hope I explained this clear enough.


问:
MySQL: Can't create table (errno: 150)
I am trying to import a .sql file and its failing on creating tables.

Here's the query that fails:

```<code>CREATE TABLE `data` (
`id` int(10) unsigned NOT NULL,
`name` varchar(100) NOT NULL,
`value` varchar(15) NOT NULL,
UNIQUE KEY `id` (`id`,`name`),
CONSTRAINT `data_ibfk_1` FOREIGN KEY (`id`) REFERENCES `keywords` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
</code>```

I exported the .sql from the same database, I dropped all the tables and now im trying to import it, why is it failing?

MySQL: Can't create table './dbname/data.frm' (errno: 150)

答: Create the table without foreign key, then set the foreign key separately.</p>

ContentLicense: CC BY-SA 4.0

Title: MySQL: Can't create table (errno: 150)

Body:
I am trying to import a .sql file and its failing on creating tables.

Here's the query that fails:

CREATE TABLE `data` (
`id` int(10) unsigned NOT NULL,
`name` varchar(100) NOT NULL,
`value` varchar(15) NOT NULL,
UNIQUE KEY `id` (`id`,`name`),
CONSTRAINT `data_ibfk_1` FOREIGN KEY (`id`) REFERENCES `keywords` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

I exported the .sql from the same database, I dropped all the tables and now im trying to import it, why is it failing?

MySQL: Can't create table './dbname/data.frm' (errno: 150)


问:
How can I click on a popup window in selenium Java
I am new to selenium and try to automate (using selenium Webdriver in Java for Window and using Chrome Driver) an App (ABC Project) which contains a Registration Form.

After completing the form and click on Registration Button I get a popup info message (modal) with close (X) & OK Button & Headline in the message: Under ABC Project the following is displayed & Text which informs the user that the registration was successful.

I have tried several ways to click on OK button in this popup window but no success:

```<code>1.

    Alert alert = driver.switchTo().alert();
                   alert.accept();

 2.

    driver.findElement(By.xpath("//input[@value = 'alert']")).click();
               Alert javascriptAlert = myTestDriver.switchTo().alert();
               System.out.println(javascriptAlert.getText()); // Get text on alert box
               javascriptAlert.accept();
               ----> in this case I get only the text of the opened tab (from registration window: driver.getTitle();:ABC Project) but not the text of teh Info message(to see in logger.info)

 3.

    String winHandleBefore =
        driver.getWindowHandle();
               driver.findElement(By.xpath("//div[@class='col-md-4']/button[1]")).click();
        // Xpath of register Button
               Set handles = driver.getWindowHandles();    ..... --->>, In this case, I don't get any Window Handler of new window the window handler from old and new are the same
</code>```

Additional Hint:

I am also not able to click anywhere else in Window to skip the popup window

In Google Developer tool I don't see also any source code and no Elements from the popup window (when the popups appear.

I heard from developer that this window is a javascript but I don't
see anything in source code too (it did not also work with solution b
above)

I appreciate for any tips and supports
Thanks

答:
This picture posted looks like a javascript alert.

So the below code should have worked.

```<code>Alert alert = driver.switchTo().alert();
alert.accept();
</code>```

Maybe it is a wait issue. Try WebDriverWait

```<code>Alert alert = new WebDriverWait(driver, 20).until(ExpectedConditions.alertIsPresent());
alert.accept();
</code>```

Body:
I am new to selenium and try to automate (using selenium Webdriver in Java for Window and using Chrome Driver) an App (ABC Project) which contains a Registration Form.

After completing the form and click on Registration Button I get a popup info message (modal) with close (X) & OK Button & Headline in the message: Under ABC Project the following is displayed & Text which informs the user that the registration was successful.

I have tried several ways to click on OK button in this popup window but no success:

1.

    Alert alert = driver.switchTo().alert();
                   alert.accept();

 2.

    driver.findElement(By.xpath("//input[@value = 'alert']")).click();
               Alert javascriptAlert = myTestDriver.switchTo().alert();
               System.out.println(javascriptAlert.getText()); // Get text on alert box
               javascriptAlert.accept();
               ----> in this case I get only the text of the opened tab (from registration window: driver.getTitle();:ABC Project) but not the text of teh Info message(to see in logger.info)

 3.

    String winHandleBefore =
        driver.getWindowHandle();
               driver.findElement(By.xpath("//div[@class='col-md-4']/button[1]")).click();
        // Xpath of register Button
               Set handles = driver.getWindowHandles();    ..... --->>, In this case, I don't get any Window Handler of new window the window handler from old and new are the same

Additional Hint:

I am also not able to click anywhere else in Window to skip the popup window

In Google Developer tool I don't see also any source code and no Elements from the popup window (when the popups appear.

I heard from developer that this window is a javascript but I don't
see anything in source code too (it did not also work with solution b
above)

I appreciate for any tips and supports
Thanks

Body:
This picture posted looks like a javascript alert.

So the below code should have worked.

Alert alert = driver.switchTo().alert();
alert.accept();

Maybe it is a wait issue. Try WebDriverWait

Alert alert = new WebDriverWait(driver, 20).until(ExpectedConditions.alertIsPresent());
alert.accept();


问:
Display a message using NSTimer
```<code>NSTimer scheduledTimerWithTimeInterval:2.0
                                target:self
                              selector:@selector(targetMethod:)
                              userInfo:nil
                               repeats:NO];
</code>```

How can I use for display the message "your time is over" after 5 min?

答:
In below code, Instead 5.0 you can put your time in second</p>

```<code>[NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(targetMethod) userInfo:nil repeats:NO];

-(void)targetMethod {
     //enter code here to execute...
}
</code>```

Title: Display a message using NSTimer

Body:
NSTimer scheduledTimerWithTimeInterval:2.0
                                target:self
                              selector:@selector(targetMethod:)
                              userInfo:nil
                               repeats:NO];

How can I use for display the message "your time is over" after 5 min?

Body:
In below code, Instead 5.0 you can put your time in second

[NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(targetMethod) userInfo:nil repeats:NO];

-(void)targetMethod {
     //enter code here to execute...
}


问:
Find time difference between highest and lowest value in data frame and sort by factor
I have a data frame and it looks like this:

```<code>submition_id       time_answered
           2 2017-11-06 14:19:30
           2 2017-11-06 14:22:45
           2 2017-11-06 14:24:55
           2 2017-11-06 14:34:10
           4 2017-11-06 14:31:23
           4 2017-11-06 14:33:21
           5 2017-11-06 14:54:48
           5 2017-11-06 14:59:38
           5 2017-11-06 15:05:39
         ...                 ...
</code>```

So basically my submition_id column is a factor column and time_answered column is POSIXct column. I want to find the time difference for each factor which is basically max(x) - min(x). How can I do this effective with inbuilt functions? Such that I get

```<code>submition_id       difference
           2            14.67
           4             1.96
           5             9.77
         ...              ...
</code>```

I would like it in minutes as well.

答: The lubridate package is very useful, interval fromlubridate will create a time span between specific times, you can then then calculate the duration of this time span, using group_by from dplyr and arrange ... can you supply some data example / dput as others have suggested to work with an extract of your data

Body:
I have a data frame and it looks like this:

submition_id       time_answered
           2 2017-11-06 14:19:30
           2 2017-11-06 14:22:45
           2 2017-11-06 14:24:55
           2 2017-11-06 14:34:10
           4 2017-11-06 14:31:23
           4 2017-11-06 14:33:21
           5 2017-11-06 14:54:48
           5 2017-11-06 14:59:38
           5 2017-11-06 15:05:39
         ...                 ...

So basically my submition_id column is a factor column and time_answered column is POSIXct column. I want to find the time difference for each factor which is basically max(x) - min(x). How can I do this effective with inbuilt functions? Such that I get

submition_id       difference
           2            14.67
           4             1.96
           5             9.77
         ...              ...

I would like it in minutes as well.


问:
Given a number, find the next higher number which has the exact same set of digits as the original number
I just bombed an interview and made pretty much zero progress on my interview question.

Given a number, find the next higher number which has the exact same
set of digits as the original number. For example: given 38276 return
38627

I wanted to begin by finding the index of the first digit (from the right) that was less than the ones digit. Then I would rotate the last digits in the subset such that it was the next biggest number comprised of the same digits, but got stuck.

The interviewer also suggested trying to swap digits one at a time, but I couldn't figure out the algorithm and just stared at a screen for like 20-30 minutes. Needless to say, I think I'm going to have to continue the job hunt.

答:
I know this is very old question but still I didn't find easy code in c#. This might help guys who are attending interviews.</p>

```<code>class Program
{
    static void Main(string[] args)
    {

        int inputNumber = 629;
        int i, currentIndexOfNewArray = 0;

        int[] arrayOfInput = GetIntArray(inputNumber);
        var numList = arrayOfInput.ToList();

        int[] newArray = new int[arrayOfInput.Length];

        do
        {
            int temp = 0;
            int digitFoundAt = 0;
            for (i = numList.Count; i > 0; i--)
            {
                if (numList[i - 1] > temp)
                {
                    temp = numList[i - 1];
                    digitFoundAt = i - 1;
                }
            }

            newArray[currentIndexOfNewArray] = temp;
            currentIndexOfNewArray++;
            numList.RemoveAt(digitFoundAt);
        } while (arrayOfInput.Length > currentIndexOfNewArray);

        Console.WriteLine(GetWholeNumber(newArray));

        Console.ReadKey();

    }

    public static int[] GetIntArray(int num)
    {
        IList<int> listOfInts = new List<int>();
        while (num > 0)
        {
            listOfInts.Add(num % 10);
            num = num / 10;
        }
        listOfInts.Reverse();
        return listOfInts.ToArray();
    }

    public static double GetWholeNumber(int[] arrayNumber)
    {
        double result = 0;
        double multiplier = 0;
        var length = arrayNumber.Count() - 1;
        for(int i = 0; i < arrayNumber.Count(); i++)
        {
            multiplier = Math.Pow(10.0, Convert.ToDouble(length));
            result += (arrayNumber[i] * multiplier);
            length = length - 1;
        }

        return result;
    }
}
</code>```

Body:
I know this is very old question but still I didn't find easy code in c#. This might help guys who are attending interviews.

class Program
{
    static void Main(string[] args)
    {

        int inputNumber = 629;
        int i, currentIndexOfNewArray = 0;

        int[] arrayOfInput = GetIntArray(inputNumber);
        var numList = arrayOfInput.ToList();

        int[] newArray = new int[arrayOfInput.Length];

        do
        {
            int temp = 0;
            int digitFoundAt = 0;
            for (i = numList.Count; i > 0; i--)
            {
                if (numList[i - 1] > temp)
                {
                    temp = numList[i - 1];
                    digitFoundAt = i - 1;
                }
            }

            newArray[currentIndexOfNewArray] = temp;
            currentIndexOfNewArray++;
            numList.RemoveAt(digitFoundAt);
        } while (arrayOfInput.Length > currentIndexOfNewArray);

        Console.WriteLine(GetWholeNumber(newArray));

        Console.ReadKey();

    }

    public static int[] GetIntArray(int num)
    {
        IList<int> listOfInts = new List<int>();
        while (num > 0)
        {
            listOfInts.Add(num % 10);
            num = num / 10;
        }
        listOfInts.Reverse();
        return listOfInts.ToArray();
    }

    public static double GetWholeNumber(int[] arrayNumber)
    {
        double result = 0;
        double multiplier = 0;
        var length = arrayNumber.Count() - 1;
        for(int i = 0; i < arrayNumber.Count(); i++)
        {
            multiplier = Math.Pow(10.0, Convert.ToDouble(length));
            result += (arrayNumber[i] * multiplier);
            length = length - 1;
        }

        return result;
    }
}


问:
Work-around for enclosing instance ineligible for garbage collection
The enclosing instance here isn't eligible for garbage collection as long as the enclosed instance is alive, right?

```<code>interface Foo<T> {
    T compute();

    default Foo<T> memoize() {
        return new Foo<>() {
            T result = null;

            boolean cached = false;

            @Override
            public T compute() {
                if (!cached) {
                    result = Foo.this.compute();
                    cached = true;
                }
                return result;
            }
        };
    }
}
</code>```

Does this solve that problem?

```<code>interface Foo<T> {
    T compute();

    default Foo<T> memoize() {
        return Foo.memoize(this);
    }

    private static <T> Foo<T> memoize(Foo<T> original) {
        class Bar implements Foo<T> {
            T result = null;

            Foo<T> foo;

            Bar(Foo<T> original) {
                foo = original;
            }

            @Override
            public T compute() {
                if (foo != null) {
                    result = foo.compute();
                    foo = null;
                }
                return result;
            }
        }
        return new Bar(original);
    }
}
</code>```

答:
Note that there’s the alternative to use lambda expressions, as lambda expressions only capture values as required, e.g.

```<code>interface Foo<T> {
    T compute();

    default Foo<T> memoize() {
        AtomicReference<Foo<T>> holder = new AtomicReference<>();
        holder.set(() -> {
               T result = compute();
               holder.set(() -> result);
               return result;
            }
        );
        return () -> holder.get().compute();
    }
}
</code>```

The holder initially contains a lambda implemented Foo<T> that has a reference to the original Foo<T> instance as at will invoke compute on the first evaluation, but then, it will replace itself with a new lambda implemented Foo<T> that will invariably return the computed value. The new lambda doesn’t even need to evaluate a conditional, as the fact that the value has been computed already is implied.

Note that the holder object doesn’t have to be an AtomicReference here, but there is no canonical simple-to-use alternative. Generic arrays can’t be created, so the only alternative that comes into my mind would be a (mutable) list of size 1, e.g. created via Arrays.asList(null).

Body:
The enclosing instance here isn't eligible for garbage collection as long as the enclosed instance is alive, right?

interface Foo<T> {
    T compute();

    default Foo<T> memoize() {
        return new Foo<>() {
            T result = null;

            boolean cached = false;

            @Override
            public T compute() {
                if (!cached) {
                    result = Foo.this.compute();
                    cached = true;
                }
                return result;
            }
        };
    }
}

Does this solve that problem?

interface Foo<T> {
    T compute();

    default Foo<T> memoize() {
        return Foo.memoize(this);
    }

    private static <T> Foo<T> memoize(Foo<T> original) {
        class Bar implements Foo<T> {
            T result = null;

            Foo<T> foo;

            Bar(Foo<T> original) {
                foo = original;
            }

            @Override
            public T compute() {
                if (foo != null) {
                    result = foo.compute();
                    foo = null;
                }
                return result;
            }
        }
        return new Bar(original);
    }
}

Body:
Note that there’s the alternative to use lambda expressions, as lambda expressions only capture values as required, e.g.

interface Foo<T> {
    T compute();

    default Foo<T> memoize() {
        AtomicReference<Foo<T>> holder = new AtomicReference<>();
        holder.set(() -> {
               T result = compute();
               holder.set(() -> result);
               return result;
            }
        );
        return () -> holder.get().compute();
    }
}

The holder initially contains a lambda implemented Foo<T> that has a reference to the original Foo<T> instance as at will invoke compute on the first evaluation, but then, it will replace itself with a new lambda implemented Foo<T> that will invariably return the computed value. The new lambda doesn’t even need to evaluate a conditional, as the fact that the value has been computed already is implied.

Note that the holder object doesn’t have to be an AtomicReference here, but there is no canonical simple-to-use alternative. Generic arrays can’t be created, so the only alternative that comes into my mind would be a (mutable) list of size 1, e.g. created via Arrays.asList(null).


问:
Declaration and use of function in c
I can't find errors in this code. I'm trying to write a program that returns the number of days (ex: 60) in the year based on day, month and year [ex: 1/3/2000 (3 Mar 2000)].

The compiler give me these errors:

too few arguments to function 'day_of_year'

conflicting types for 'day_of_year'

```<code>#include <stdio.h>

int day_of_year(int day, int month, int year);

int main(){
    int day, month, year, i, count=0;
    int a[]={31,28,31,30,31,30,31,31,30,31,30,31};
    printf ("Enter the day: ");
    scanf ("%d", &day);
    printf ("Enter the month: ");
    scanf ("%d", &month);
    printf ("Enter the year: ");
    scanf ("%d", &year);
    count=day_of_year();
    printf ("Count: %d", count);
    return 0;
}

int day_of_year (int day, int month, int year, int i, int count){
    int a[]={31,28,31,30,31,30,31,31,30,31,30,31};
    if (year%4==0) a[2]++;
    count = day;
    for (i=0;i<month;i++)
        count+=a[i];
    return count;
}
</code>```

答:
Thanks to all. I corrected the errors.
This is the new code.</p>

```<code>#include <stdio.h>

int day_of_year(int day, int month, int year);

int main(){
    int day, month, year, i, count=0;
    int a[]={31,28,31,30,31,30,31,31,30,31,30,31};
    printf ("Enter the day: ");
    scanf ("%d", &day);
    printf ("Enter the month: ");
    scanf ("%d", &month);
    printf ("Enter the year: ");
    scanf ("%d", &year);
    count=day_of_year(day, month, year);
    printf ("Count: %d", count);
    return 0;
}

int day_of_year (int day, int month, int year){
    int i, count;
    int a[]={31,28,31,30,31,30,31,31,30,31,30,31};
    if (year%4==0) a[2]++;
    count = day;
    for (i=0;i<month;i++)
        count+=a[i];
    return count;
}
</code>```

Title: Declaration and use of function in c

Body:
I can't find errors in this code. I'm trying to write a program that returns the number of days (ex: 60) in the year based on day, month and year [ex: 1/3/2000 (3 Mar 2000)].

The compiler give me these errors:

too few arguments to function 'day_of_year'

conflicting types for 'day_of_year'

#include <stdio.h>

int day_of_year(int day, int month, int year);

int main(){
    int day, month, year, i, count=0;
    int a[]={31,28,31,30,31,30,31,31,30,31,30,31};
    printf ("Enter the day: ");
    scanf ("%d", &day);
    printf ("Enter the month: ");
    scanf ("%d", &month);
    printf ("Enter the year: ");
    scanf ("%d", &year);
    count=day_of_year();
    printf ("Count: %d", count);
    return 0;
}

int day_of_year (int day, int month, int year, int i, int count){
    int a[]={31,28,31,30,31,30,31,31,30,31,30,31};
    if (year%4==0) a[2]++;
    count = day;
    for (i=0;i<month;i++)
        count+=a[i];
    return count;
}

Body:
Thanks to all. I corrected the errors.
This is the new code.

#include <stdio.h>

int day_of_year(int day, int month, int year);

int main(){
    int day, month, year, i, count=0;
    int a[]={31,28,31,30,31,30,31,31,30,31,30,31};
    printf ("Enter the day: ");
    scanf ("%d", &day);
    printf ("Enter the month: ");
    scanf ("%d", &month);
    printf ("Enter the year: ");
    scanf ("%d", &year);
    count=day_of_year(day, month, year);
    printf ("Count: %d", count);
    return 0;
}

int day_of_year (int day, int month, int year){
    int i, count;
    int a[]={31,28,31,30,31,30,31,31,30,31,30,31};
    if (year%4==0) a[2]++;
    count = day;
    for (i=0;i<month;i++)
        count+=a[i];
    return count;
}


问:
How to get root node attributes on java
I have an xml file like down below. I want to get pharmacies nodes' latitude and longitude attributes.I can get chilnodes attributes but couldnt get root node attributes. I am new on java and xml. I could not find a solution how to do.

```<code><pharmacies Acc="4" latitude="36.8673380" longitude="30.6346640" address="Ayujkila">
        <pharmacy name="sadde" owner="" address="dedes" distance="327.000555668" phone="342343" lat="36.8644" long="30.6345" accuracy="8"/>
        <pharmacy name="Sun " owner="" address="degerse" distance="364.450016586" phone="45623" lat="36.8641" long="30.6353" accuracy="8"/>
        <pharmacy name="lara" owner="" address="freacde" distance="927.262190129" phone="564667" lat="36.8731" long="30.6422" accuracy="8"
    <end/>
    </pharmacies>
</code>```

This is my part of code. I get xml file from a url address.

```<code>                    DocumentBuilderFactory dbf =DocumentBuilderFactory.newInstance();
                 DocumentBuilder db = dbf.newDocumentBuilder();
                 Document doc = db.parse(new InputSource(url.openStream()));
                 doc.getDocumentElement().normalize();
                    NodeList nodeList =doc.getElementsByTagName("pharmacy");
                 for (int i = 0; i < nodeList.getLength(); i++){
                      Node node =nodeList.item(i);
                      Element fstElmnt = (Element) node;
                      NodeList pharmacyList = fstElmnt.getElementsByTagName("pharmacy");
                      Element pharmacyElement = (Element) pharmacyList.item(0);
              Element pharmacyElement = (Element) pharmacyList.item(0);

              HashMap<String,String>map=new HashMap<String,String>();
              map.put("name", pharmacyElement.getAttribute("name"));
              map.put("distance", pharmacyElement.getAttribute("phone"));
              list.add(map);

              latt.add(pharmacyElement.getAttribute("lat"));

                    ....
</code>```

答:
try the following:</p>

```<code>    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(new ByteArrayInputStream(xml.getBytes("UTF-8")));
    doc.getDocumentElement().normalize();
    System.out.println(doc.getChildNodes().getLength());
    Node item = doc.getChildNodes().item(0);
    System.out.println(item.getNodeName());
    Node lat = item.getAttributes().getNamedItem("latitude");
    String s = lat.getNodeValue();
    System.out.println(s.equals("36.8673380")); // Value of /pharmacies[@latitude]/value()
</code>```

Title: How to get root node attributes on java

Body:
I have an xml file like down below. I want to get pharmacies nodes' latitude and longitude attributes.I can get chilnodes attributes but couldnt get root node attributes. I am new on java and xml. I could not find a solution how to do.

<pharmacies Acc="4" latitude="36.8673380" longitude="30.6346640" address="Ayujkila">
        <pharmacy name="sadde" owner="" address="dedes" distance="327.000555668" phone="342343" lat="36.8644" long="30.6345" accuracy="8"/>
        <pharmacy name="Sun " owner="" address="degerse" distance="364.450016586" phone="45623" lat="36.8641" long="30.6353" accuracy="8"/>
        <pharmacy name="lara" owner="" address="freacde" distance="927.262190129" phone="564667" lat="36.8731" long="30.6422" accuracy="8"
    <end/>
    </pharmacies>

This is my part of code. I get xml file from a url address.

                    DocumentBuilderFactory dbf =DocumentBuilderFactory.newInstance();
                 DocumentBuilder db = dbf.newDocumentBuilder();
                 Document doc = db.parse(new InputSource(url.openStream()));
                 doc.getDocumentElement().normalize();
                    NodeList nodeList =doc.getElementsByTagName("pharmacy");
                 for (int i = 0; i < nodeList.getLength(); i++){
                      Node node =nodeList.item(i);
                      Element fstElmnt = (Element) node;
                      NodeList pharmacyList = fstElmnt.getElementsByTagName("pharmacy");
                      Element pharmacyElement = (Element) pharmacyList.item(0);
              Element pharmacyElement = (Element) pharmacyList.item(0);

              HashMap<String,String>map=new HashMap<String,String>();
              map.put("name", pharmacyElement.getAttribute("name"));
              map.put("distance", pharmacyElement.getAttribute("phone"));
              list.add(map);

              latt.add(pharmacyElement.getAttribute("lat"));

                    ....

Body:
try the following:

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(new ByteArrayInputStream(xml.getBytes("UTF-8")));
    doc.getDocumentElement().normalize();
    System.out.println(doc.getChildNodes().getLength());
    Node item = doc.getChildNodes().item(0);
    System.out.println(item.getNodeName());
    Node lat = item.getAttributes().getNamedItem("latitude");
    String s = lat.getNodeValue();
    System.out.println(s.equals("36.8673380")); // Value of /pharmacies[@latitude]/value()


问:
Non-scalar enumeration in Matlab
Is it possible to have enumeration member that are non-scalar?

For example, how can I enumerate colors such that each color is a 1x3 double (as needed for plots), without using methods?

With the following class definition

```<code>classdef color
    properties
        R, G, B
    end
    methods
        function c = color(r, g, b)
            c.R = r;
            c.G = g;
            c.B = b;
        end
        function g = get(c)
            g = [c.R, c.G, c.B];
        end
    end
    enumeration
        red (1, 0, 0)
        green (0, 1, 0)
    end
end
</code>```

I can write color.green.get() to get [0 1 0], but I would like the same result with color.green to make the code cleaner.

A different solution may be setting color as a global struct, but it's not practical because global variables can cause confusion and I have to write global color; in each script/function.

答:
I'm not sure exactly what you're asking here, but I think the main answer is that you're currently doing basically the right thing (although I'd suggest a few small changes).

You can certainly have non-scalar arrays of enumeration values - using your class, for example, you could create mycolors = [color.red, color.green]. You can also have an enumeration with non-scalar properties, such as the following:

```<code>classdef color2
    properties
        RGB
    end
    methods
        function c = color2(r, g, b)
            c.RGB = [r,g,b];
        end
    end
    enumeration
        red (1, 0, 0)
        green (0, 1, 0)
    end
end
</code>```

and then you could just say color2.red.RGB and you'd get [1,0,0].

But I'm guessing that neither of those are really what you want. The thing that I imagine you're aiming for, and unfortunately what you explicitly can't do, is something like:

```<code>classdef color3 < double
    enumeration
        red ([1,0,0])
        green ([0,1,0])
    end
end
</code>```

where you would then just type color3.red and you'd get [1,0,0]. You can't do that, because when an enumeration inherits from a built-in, it has to be a scalar.

Personally, I would do basically what you're doing, but instead of calling your method get I would call it toRGB, so you'd say color.red.toRGB, which feels quite natural (especially if you also give it some other methods like toHSV or toHex as well). I'd also modify it slightly, so that it could accept arrays of colors:

```<code>function rgb = toRGB(c)
        rgb = [[c.R]', [c.G]', [c.B]'];
end
</code>```

That way you can pass in an array of n colors, and it will output an n-by-3 array of RGB values. For example, you could say mycolors = [color.red, color.green]; mycolors.toRGB and you'd get [1,0,0;0,1,0].

Hope that helps!

Title: Non-scalar enumeration in Matlab

Body:
Is it possible to have enumeration member that are non-scalar?

For example, how can I enumerate colors such that each color is a 1x3 double (as needed for plots), without using methods?

With the following class definition

classdef color
    properties
        R, G, B
    end
    methods
        function c = color(r, g, b)
            c.R = r;
            c.G = g;
            c.B = b;
        end
        function g = get(c)
            g = [c.R, c.G, c.B];
        end
    end
    enumeration
        red (1, 0, 0)
        green (0, 1, 0)
    end
end

I can write color.green.get() to get [0 1 0], but I would like the same result with color.green to make the code cleaner.

A different solution may be setting color as a global struct, but it's not practical because global variables can cause confusion and I have to write global color; in each script/function.

Body:
I'm not sure exactly what you're asking here, but I think the main answer is that you're currently doing basically the right thing (although I'd suggest a few small changes).

You can certainly have non-scalar arrays of enumeration values - using your class, for example, you could create mycolors = [color.red, color.green]. You can also have an enumeration with non-scalar properties, such as the following:

classdef color2
    properties
        RGB
    end
    methods
        function c = color2(r, g, b)
            c.RGB = [r,g,b];
        end
    end
    enumeration
        red (1, 0, 0)
        green (0, 1, 0)
    end
end

and then you could just say color2.red.RGB and you'd get [1,0,0].

But I'm guessing that neither of those are really what you want. The thing that I imagine you're aiming for, and unfortunately what you explicitly can't do, is something like:

classdef color3 < double
    enumeration
        red ([1,0,0])
        green ([0,1,0])
    end
end

where you would then just type color3.red and you'd get [1,0,0]. You can't do that, because when an enumeration inherits from a built-in, it has to be a scalar.

Personally, I would do basically what you're doing, but instead of calling your method get I would call it toRGB, so you'd say color.red.toRGB, which feels quite natural (especially if you also give it some other methods like toHSV or toHex as well). I'd also modify it slightly, so that it could accept arrays of colors:

function rgb = toRGB(c)
        rgb = [[c.R]', [c.G]', [c.B]'];
end

That way you can pass in an array of n colors, and it will output an n-by-3 array of RGB values. For example, you could say mycolors = [color.red, color.green]; mycolors.toRGB and you'd get [1,0,0;0,1,0].

Hope that helps!


问:
JDBC connection url issue
i am getting error on below url connection as "Syntax error on tokens, delete these tokens"

My url

```<code> import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JdbcSQLServerConnection {

    public static void main(String[] args) throws ClassNotFoundException, SQLException {

    String url="jdbc:sqlserver://"TKSQA";databaseName="RDK";integratedSecurity=true";

    String query="use RDK
    go
    /* * the current date must be less than 45 days after the policy effective date and the transaction must have
           * a status of IssuedRenewal */
    select top 5 left(prsnAddr.PostalZip, 5) as ZipCode, policy.policynum,terms.termeffective
    from PolicyRecord pr left join Policy policy on pr.PolicySK = policy.PolicySK
    join PolicyTerms terms on pr.PolicyTermSK = terms.PolicyTermSK and getDate() < (terms.termeffective + 45)
    join PolicyTxn txn on pr.PolicyTxnSK = txn.PolicyTxnSK and TxnBusStatus = 'ISSUEDRENEWAL'  and txn.TxnSequence = (
           select max(ptx2.TxnSequence)
           from PolicyTxn ptx2
           inner join PolicyTermTxn pttx2 on pttx2.PolicyTxnsk = ptx2.PolicyTxnSK
           where pttx2.PolicyTermSK = terms.PolicyTermSK and ptx2.TxnStatus <> 'INACTIVE')
    join Insured ins on ins.PolicyRecordSK= pr.PolicyRecordSK
    join Person pers on pers.PersonSK = ins.PersonSK
    join PersonAddress prsnAddr on prsnAddr.PersonSK = pers.PersonSK
           where policy.insuranceproductid like '%CollectorVehicle%' and RecordType='ONSET'
           order by terms.TermEffective
    ";

    Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
    Connection con = DriverManager.getConnection(url);
    Statement st = con.createStatement();
    ResultSet rs = st.executeQuery(query);

    rs.next();
    String zip= rs.getString("ZipCode");
    System.out.print(zip);
    st.close();
    con.close();

        }

    }
</code>```

Due to the above error i am unable to connect sql sever using java.Is this the correct way to write string url

答:
The general form of the connection URL is (for MS SQL Server)

```<code>jdbc:sqlserver://[serverName[\instanceName][:portNumber]][;property=value[;property=value]]
</code>```

example,

```<code>jdbc:sqlserver://localhost;user=MyUserName;password=*****;
</code>```

The general form of the connection URL is (for MySQL Server)

```<code>jdbc:mysql://hostname/ databaseName
</code>```

Here, hostname should contain portnumber (its mandatory)

example,

```<code>  //STEP 1. Import required packages
import java.sql.*;

public class JDBCExample {
   // JDBC driver name and database URL
   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
   static final String DB_URL = "jdbc:mysql://localhost:3306/STUDENTS";

   //  Database credentials
   static final String USER = "username";
   static final String PASS = "password";

   public static void main(String[] args) {
   Connection conn = null;
   Statement stmt = null;
   try{
      //STEP 2: Register JDBC driver
      Class.forName("com.mysql.jdbc.Driver");

      //STEP 3: Open a connection
      System.out.println("Connecting to a selected database...");
      conn = DriverManager.getConnection(DB_URL, USER, PASS);
      System.out.println("Connected database successfully...");

      //STEP 4: Execute a query

   }catch(SQLException se){
      //Handle errors for JDBC
      se.printStackTrace();
   }finally{
    conn.close();
   }//end finally
   System.out.println("Goodbye!");
}
}
</code>```

References,

https://learn.microsoft.com/en-us/sql/connect/jdbc/building-the-connection-url

https://www.tutorialspoint.com/jdbc/index.htm

Title: JDBC connection url issue

Body:
i am getting error on below url connection as "Syntax error on tokens, delete these tokens"

My url

 import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JdbcSQLServerConnection {

    public static void main(String[] args) throws ClassNotFoundException, SQLException {

    String url="jdbc:sqlserver://"TKSQA";databaseName="RDK";integratedSecurity=true";

    String query="use RDK
    go
    /* * the current date must be less than 45 days after the policy effective date and the transaction must have
           * a status of IssuedRenewal */
    select top 5 left(prsnAddr.PostalZip, 5) as ZipCode, policy.policynum,terms.termeffective
    from PolicyRecord pr left join Policy policy on pr.PolicySK = policy.PolicySK
    join PolicyTerms terms on pr.PolicyTermSK = terms.PolicyTermSK and getDate() < (terms.termeffective + 45)
    join PolicyTxn txn on pr.PolicyTxnSK = txn.PolicyTxnSK and TxnBusStatus = 'ISSUEDRENEWAL'  and txn.TxnSequence = (
           select max(ptx2.TxnSequence)
           from PolicyTxn ptx2
           inner join PolicyTermTxn pttx2 on pttx2.PolicyTxnsk = ptx2.PolicyTxnSK
           where pttx2.PolicyTermSK = terms.PolicyTermSK and ptx2.TxnStatus <> 'INACTIVE')
    join Insured ins on ins.PolicyRecordSK= pr.PolicyRecordSK
    join Person pers on pers.PersonSK = ins.PersonSK
    join PersonAddress prsnAddr on prsnAddr.PersonSK = pers.PersonSK
           where policy.insuranceproductid like '%CollectorVehicle%' and RecordType='ONSET'
           order by terms.TermEffective
    ";

    Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
    Connection con = DriverManager.getConnection(url);
    Statement st = con.createStatement();
    ResultSet rs = st.executeQuery(query);

    rs.next();
    String zip= rs.getString("ZipCode");
    System.out.print(zip);
    st.close();
    con.close();

        }

    }

Due to the above error i am unable to connect sql sever using java.Is this the correct way to write string url

Body:
The general form of the connection URL is (for MS SQL Server)

jdbc:sqlserver://[serverName[\instanceName][:portNumber]][;property=value[;property=value]]

example,

jdbc:sqlserver://localhost;user=MyUserName;password=*****;

The general form of the connection URL is (for MySQL Server)

jdbc:mysql://hostname/ databaseName

Here, hostname should contain portnumber (its mandatory)

example,

  //STEP 1. Import required packages
import java.sql.*;

public class JDBCExample {
   // JDBC driver name and database URL
   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
   static final String DB_URL = "jdbc:mysql://localhost:3306/STUDENTS";

   //  Database credentials
   static final String USER = "username";
   static final String PASS = "password";

   public static void main(String[] args) {
   Connection conn = null;
   Statement stmt = null;
   try{
      //STEP 2: Register JDBC driver
      Class.forName("com.mysql.jdbc.Driver");

      //STEP 3: Open a connection
      System.out.println("Connecting to a selected database...");
      conn = DriverManager.getConnection(DB_URL, USER, PASS);
      System.out.println("Connected database successfully...");

      //STEP 4: Execute a query

   }catch(SQLException se){
      //Handle errors for JDBC
      se.printStackTrace();
   }finally{
    conn.close();
   }//end finally
   System.out.println("Goodbye!");
}
}

References,

https://learn.microsoft.com/en-us/sql/connect/jdbc/building-the-connection-url

https://www.tutorialspoint.com/jdbc/index.htm


问:
How to check whether cells in a particular column of a html table is empty using Jquery?
I have a html page in my web application where there are several forms and tables.
In following column 'Advert Id' is mandatory to be filled.

 File Name
 Duration
 Category
 Comment
 Advert Name
 Advert Id

```
</div>
</div>
</p>

<p>The content of the above table is to be added.</p>

<p>I want to check whether all the cells under the Advert Id column is filled. If not I want to get the Advert name of the relevant entry. </p>

<p>Currently I am able to check whether there is content in the table and if not a warning is displayed.</p>

```function saveAdminStatusAndTR(){
     var rowCount = $('#mf-table tr').length;
     if(rowCount == 1){ //case where there is no content in the table
        toastr.error('No media file has been uploaded', 'Approval Status');
     }else if(...){ //one of the cell under advert id is empty
          // Need to show a warning message indicating the advert names
          where there is no advert id
     }else{
       //my code here
     }
 }
```

Can any one help me with this?

答:
Use jquery selector :eq

```<code>$("table td:eq(POSITION)").each(function(idx) {...});
</code>```

This link will be helpfull https://api.jquery.com/eq-selector/

Hope this helps

Body:
I have a html page in my web application where there are several forms and tables.
In following column 'Advert Id' is mandatory to be filled.

 File Name
 Duration
 Category
 Comment
 Advert Name
 Advert Id

The content of the above table is to be added.

I want to check whether all the cells under the Advert Id column is filled. If not I want to get the Advert name of the relevant entry.

Currently I am able to check whether there is content in the table and if not a warning is displayed.

function saveAdminStatusAndTR(){
     var rowCount = $('#mf-table tr').length;
     if(rowCount == 1){ //case where there is no content in the table
        toastr.error('No media file has been uploaded', 'Approval Status');
     }else if(...){ //one of the cell under advert id is empty
          // Need to show a warning message indicating the advert names
          where there is no advert id
     }else{
       //my code here
     }
 }

Can any one help me with this?

Body:
Use jquery selector :eq

$("table td:eq(POSITION)").each(function(idx) {...});

This link will be helpfull https://api.jquery.com/eq-selector/

Hope this helps


问:
CSS Computed width different from specified
As shown in this bin the width specified for the preview button is 120 px while the rendered width is always 132 px (on different screens).

.btn-grey{
    cursor: pointer;
    background: #f1f3f6;
    border: 1px solid #d7d9e1;
    box-shadow: 1px 1px 1px #fff inset;
    border-radius: 3px;
    color: #838AAB;
    display: inline-block;
    height: 30px;
    padding: 0 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
            <div style="display: flex; width: 60%; justify-content: center;">
                <input name="preview" class="btn-grey" value="Preview" style="flex-basis: 120px; width: 120px; height: 35px;max-width: 120px; max-height: 35px; margin : 5px 5px 5px 5px " title="preview"/>
                <input name="load" class="btn-grey" type="submit" value="Load " style="width: 120px; height: 35px;max-width: 120px; max-height: 35px;margin : 5px 5px 5px 5px "/>
            </div>

</body>
</html></code>```

答:
hi try this:

```<code>.btn-grey{
box-sizing:border-box;
}
</code>```

Body:
As shown in this bin the width specified for the preview button is 120 px while the rendered width is always 132 px (on different screens).

.btn-grey{
    cursor: pointer;
    background: #f1f3f6;
    border: 1px solid #d7d9e1;
    box-shadow: 1px 1px 1px #fff inset;
    border-radius: 3px;
    color: #838AAB;
    display: inline-block;
    height: 30px;
    padding: 0 5px;
}

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

                <input name="preview" class="btn-grey" value="Preview" style="flex-basis: 120px; width: 120px; height: 35px;max-width: 120px; max-height: 35px; margin : 5px 5px 5px 5px " title="preview"/>
                <input name="load" class="btn-grey" type="submit" value="Load " style="width: 120px; height: 35px;max-width: 120px; max-height: 35px;margin : 5px 5px 5px 5px "/>

Body:
hi try this:

.btn-grey{
box-sizing:border-box;
}


问:
Record gets inserted successfully but doesn't show up in select query
I'm trying to insert a record in table containing 105 columns. The record gets inserted successfully but when I try to select the same record it doesn't show up.
I'm in the same session and also I tried to apply commit and select it again but could see no luck. Could anyone please suggest how to resolve this?</p>

答:
Create trigger like this and see what happens when you inserts:</p>

```<code>create or replace trigger xyz_log after insert or update or delete on xyz for each row
begin
  if Inserting then
    dbms_output.put_line('Row inserted: ' || :new.rowid);
  elsif Updating then
    dbms_output.put_line('Row updated: ' || :new.rowid);
  elsif Deleting then
    dbms_output.put_line('Row deleted: ' || :old.rowid);
  end if;
end;
</code>```

Body:
Create trigger like this and see what happens when you inserts:

create or replace trigger xyz_log after insert or update or delete on xyz for each row
begin
  if Inserting then
    dbms_output.put_line('Row inserted: ' || :new.rowid);
  elsif Updating then
    dbms_output.put_line('Row updated: ' || :new.rowid);
  elsif Deleting then
    dbms_output.put_line('Row deleted: ' || :old.rowid);
  end if;
end;


问:
Selenium vba no such window: window was already closed
I have Main Window and Sub Window, when i click on OK button in Sub window, I got the below Error. How to handle this?

Selenium VBA :

```<code>Dim driver As SeleniumWrapper.WebDriver
Set driver = New SeleniumWrapper.WebDriver
</code>```

答:
Here is the answer

driver.selectWindow ("AIF - Generic Request with Type (rap-alpha-ndc-pr.csc.com)")            'Main Window
aa = driver.WindowHandle   'Main Window
driver.Click "id=WIN_0_603220144"    'Sub Window open here
driver.selectWindow ("Cost Object Search (rap-alpha-ndc-pr.csc.com)") ' Selecting Sub Window to work on this page.
driver.Click "id=WIN_0_603220135" 'Clicking on Sub window and it close automatically.

driver.switchToWindow (aa)  ' it helps to switch to Main Window

Body:
I have Main Window and Sub Window, when i click on OK button in Sub window, I got the below Error. How to handle this?

Selenium VBA :

Dim driver As SeleniumWrapper.WebDriver
Set driver = New SeleniumWrapper.WebDriver


问:
I want to show a chapter page number from 15 to 25 - barteksc/AndroidPdfViewer
I'm using barteksc/AndroidPdfViewer, and suffering from an issue that is I want to show a chapter page number from 15 to 25, how it will be? I can start a chapter page number using .defaultPage(15) but how can I finish on page 25? Is it possible? Here is sample code:

```<code>private void displayFromAsset(String assetFileName) {
pdfFileName = assetFileName;
pdfView.fromAsset(SAMPLE_FILE)
        .defaultPage(15)
        .onPageChange(this)
        .enableAnnotationRendering(true)
        .onLoad(this)
        .scrollHandle(new DefaultScrollHandle(this))
        .load();
}
</code>```

Please help me in this regard. Thanks in advance

答:
If you want to show some pages, mention them on pages function as followed, it will show pages from 15 to 25.

```<code>.pages(15,16,17,18,19,20,21,22,23,24,25)
</code>```

Below is complete function.

```<code>private void displayFromAsset(String assetFileName) {
pdfFileName = assetFileName;
pdfView.fromAsset(SAMPLE_FILE)
        .defaultPage(15)
        .onPageChange(this)
        .enableAnnotationRendering(true)
        .onLoad(this)
        .scrollHandle(new DefaultScrollHandle(this))
        .pages(15,16,17,18,19,20,21,22,23,24,25)
        .load();
}
</code>```

Body:
I'm using barteksc/AndroidPdfViewer, and suffering from an issue that is I want to show a chapter page number from 15 to 25, how it will be? I can start a chapter page number using .defaultPage(15) but how can I finish on page 25? Is it possible? Here is sample code:

private void displayFromAsset(String assetFileName) {
pdfFileName = assetFileName;
pdfView.fromAsset(SAMPLE_FILE)
        .defaultPage(15)
        .onPageChange(this)
        .enableAnnotationRendering(true)
        .onLoad(this)
        .scrollHandle(new DefaultScrollHandle(this))
        .load();
}

Please help me in this regard. Thanks in advance

Body:
If you want to show some pages, mention them on pages function as followed, it will show pages from 15 to 25.

.pages(15,16,17,18,19,20,21,22,23,24,25)

Below is complete function.

private void displayFromAsset(String assetFileName) {
pdfFileName = assetFileName;
pdfView.fromAsset(SAMPLE_FILE)
        .defaultPage(15)
        .onPageChange(this)
        .enableAnnotationRendering(true)
        .onLoad(this)
        .scrollHandle(new DefaultScrollHandle(this))
        .pages(15,16,17,18,19,20,21,22,23,24,25)
        .load();
}


问:
What's a cool way to StopPlay(); a <object id="myflashvideo"> with JavaScript?
I heard that I can control Flash via Javascript.. but I really need some advice about the possibilitys of it. I have a  Flash Video Movie .flv, I dont know if this makes a difference, which contains a navigation .swf.

HTML

```<code><div class="video">
            <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" style="position:absolute;z-index:0;"width="809" height="459" id="FLVPlayer">
              <param name="movie" value="FLVPlayer_Progressive.swf" />
              <param name="quality" value="high" />
              <param name="wmode" value="transparent" />
              <param name="scale" value="noscale" />
              <param name="salign" value="lt" />
              <param name="FlashVars" value="&MM_ComponentVersion=1&skinName=flash/player&streamName=videos/Bens_neu&autoPlay=true&autoRewind=false;wmode=transparent" />
              <param name="swfversion" value="8,0,0,0" />
              <!-- Dieses param-Tag fordert Benutzer von Flash Player 6.0 r65 und höher auf, die aktuelle Version von Flash Player herunterzuladen. Wenn Sie nicht wünschen, dass die Benutzer diese Aufforderung sehen, löschen Sie dieses Tag. -->
              <param name="expressinstall" value="scripts/expressInstall.swf" />
              <!-- Das nächste Objekt-Tag ist für Nicht-IE-Browser vorgesehen. Blenden Sie es daher mit IECC in IE aus. -->
              <!--[if !IE]>-->
              <object id="FLVPLayer" type="application/x-shockwave-flash" data="FLVPlayer_Progressive.swf" width="809" height="459">
                <!--<![endif]-->
                <param name="quality" value="high" />
                <param name="wmode" value="transparent" />
                <param name="scale" value="noscale" />
                <param name="salign" value="lt" />
                <param name="FlashVars" value="&MM_ComponentVersion=1&skinName=flash/player&streamName=videos/Bens_neu&autoPlay=true&autoRewind=false;wmode=transparent" />
                <param name="swfversion" value="8,0,0,0" />
                <param name="expressinstall" value="scripts/expressInstall.swf" />
                <!-- Im Browser wird für Benutzer von Flash Player 6.0 und älteren Versionen der folgende alternative Inhalt angezeigt. -->
                <div>
                  <h4>Für den Inhalt dieser Seite ist eine neuere Version von Adobe Flash Player erforderlich.</h4>
                  <p><a href="http://www.adobe.com/go/getflashplayer"><img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Adobe Flash Player herunterladen" /></a></p>
                </div>
                <!--[if !IE]>-->
              </object>
              <!--<![endif]-->
            </object>
          </div>
</code>```

Pseudo Javascript (btw I use JQuery on the website.. maybe we can short code with that, but not required)

```<code>GetDocumentObjectID("FLVPlayer").StopPlay();
</code>```

Is there a cool, easy way to get this done? I prioritize IE 8,7.. but it is okay if it worked in all other browsers too.

答:
This jQuery plugin (based on the original SWFObject) should be very useful for your purpose

You can easily do stuff like these:

```<code>function play() {
    flashMovie.flash(
        function() {
            this.Play();
        }
    );
}

function pause() {
    flashMovie.flash(
        function() {
            this.StopPlay();
        }
    );
}
</code>```

examples taken from http://jquery.thewikies.com/swfobject/examples

Body:
I heard that I can control Flash via Javascript.. but I really need some advice about the possibilitys of it. I have a  Flash Video Movie .flv, I dont know if this makes a difference, which contains a navigation .swf.

HTML

            <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" style="position:absolute;z-index:0;"width="809" height="459" id="FLVPlayer">
              <param name="movie" value="FLVPlayer_Progressive.swf" />
              <param name="quality" value="high" />
              <param name="wmode" value="transparent" />
              <param name="scale" value="noscale" />
              <param name="salign" value="lt" />
              <param name="FlashVars" value="&MM_ComponentVersion=1&skinName=flash/player&streamName=videos/Bens_neu&autoPlay=true&autoRewind=false;wmode=transparent" />
              <param name="swfversion" value="8,0,0,0" />

              <param name="expressinstall" value="scripts/expressInstall.swf" />

              <object id="FLVPLayer" type="application/x-shockwave-flash" data="FLVPlayer_Progressive.swf" width="809" height="459">

                <param name="quality" value="high" />
                <param name="wmode" value="transparent" />
                <param name="scale" value="noscale" />
                <param name="salign" value="lt" />
                <param name="FlashVars" value="&MM_ComponentVersion=1&skinName=flash/player&streamName=videos/Bens_neu&autoPlay=true&autoRewind=false;wmode=transparent" />
                <param name="swfversion" value="8,0,0,0" />
                <param name="expressinstall" value="scripts/expressInstall.swf" />

Für den Inhalt dieser Seite ist eine neuere Version von Adobe Flash Player erforderlich.

              </object>

            </object>

Pseudo Javascript (btw I use JQuery on the website.. maybe we can short code with that, but not required)

GetDocumentObjectID("FLVPlayer").StopPlay();

Is there a cool, easy way to get this done? I prioritize IE 8,7.. but it is okay if it worked in all other browsers too.

Body:
This jQuery plugin (based on the original SWFObject) should be very useful for your purpose

You can easily do stuff like these:

function play() {
    flashMovie.flash(
        function() {
            this.Play();
        }
    );
}

function pause() {
    flashMovie.flash(
        function() {
            this.StopPlay();
        }
    );
}

examples taken from http://jquery.thewikies.com/swfobject/examples