问:
Import MySQL JDBC Driver into Dynamic Web Project
I'm having issues connecting to a web based (not local) MySQL database. I keep getting the error: No suitable driver found for jdbc:mysql://host:port/database (I'm using the actual host of course) in the console. The webpage just displays "null".

I am brand new to Java so was using this post
as reference to get started. I created a dynamic web project in Eclipse and have added the JDBC connector JAR file under WebContent > WEB-INF > LIB.  I am totally lost as to why this continues to give me an error.

I'm using Tomcat 7 into Eclipse IDE.

I've been Googling for the past couple hours with no luck... please help! Here is the code I'm using:

Connect.java

```<code>package dbObjects;

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

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;

public class Connect {
    protected Connection getConnection() throws SQLException {
        String url = "jdbc:mysql://host:port/database";
        String username = "username";
        String password = "password";

        Connection conn = (Connection) DriverManager.getConnection(url, username, password);
        return conn;
    }

    protected ResultSet getResultSet(String sql) throws SQLException {
        Connection conn = getConnection();
        Statement st = (Statement) conn.createStatement();
        return st.executeQuery(sql);
    }
}
</code>```

Employees.java

```<code>package dbObjects;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

public class Employees extends Connect {
    private String login;
    private String workgroup;
    private String csm;

    public Employees(String login, String workgroup, String csm) {
        super();
        this.login = login;
        this.workgroup = workgroup;
        this.csm = csm;
    }

    public Employees(String login) throws SQLException {
        super();
        this.login = login;
        setUserById(login);
    }

    private void setUserById(String login) throws SQLException {
        ResultSet resultSet = getResultSet("SELECT * FROM employeeData LIMIT 5");
        while(resultSet.next()) {
            System.out.println(resultSet.getString("login"));
            workgroup = resultSet.getString("workgroup");
            csm = resultSet.getString("csm");
        }
    }

    @Override
    public String toString() {
        return workgroup;
    }

}
</code>```

The servlet I'm trying to run

```<code>package servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dbObjects.Employees;

/**
 * Servlet implementation class HomeServlet
 */
@WebServlet(description = "Home page shown to user", urlPatterns = { "/HomeServlet" })
public class HomeServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public HomeServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        Employees user = null;
        try {
            user = new Employees(null);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        PrintWriter pw = response.getWriter();
        pw.println(user);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

}
</code>```

I've also created a simple connection test class that is working and not returning no suitable driver error.

```<code>import java.sql.DriverManager;
import java.sql.SQLException;

import com.mysql.jdbc.Connection;

public class connTest {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String url = "jdbc:mysql://host:port/database";
    String username = "username";
    String password = "password";

        System.out.println("Connecting database...");

        try (Connection connection = (Connection) DriverManager.getConnection(url, username, password)) {
            System.out.println("Database connected!");
        } catch (SQLException e) {
            throw new IllegalStateException("Cannot connect the database!", e);
        }
    }

}
</code>```

答:
The issue was in the Connect.java class. I added the following line of code DriverManager.registerDriver(new com.mysql.jdbc.Driver ()); right before Connection conn = (Connection) DriverManager.getConnection(url, username, password);

It's now working!

Body:
I'm having issues connecting to a web based (not local) MySQL database. I keep getting the error: No suitable driver found for jdbc:mysql://host:port/database (I'm using the actual host of course) in the console. The webpage just displays "null".

I am brand new to Java so was using this post
as reference to get started. I created a dynamic web project in Eclipse and have added the JDBC connector JAR file under WebContent > WEB-INF > LIB.  I am totally lost as to why this continues to give me an error.

I'm using Tomcat 7 into Eclipse IDE.

I've been Googling for the past couple hours with no luck... please help! Here is the code I'm using:

Connect.java

package dbObjects;

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

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;

public class Connect {
    protected Connection getConnection() throws SQLException {
        String url = "jdbc:mysql://host:port/database";
        String username = "username";
        String password = "password";

        Connection conn = (Connection) DriverManager.getConnection(url, username, password);
        return conn;
    }

    protected ResultSet getResultSet(String sql) throws SQLException {
        Connection conn = getConnection();
        Statement st = (Statement) conn.createStatement();
        return st.executeQuery(sql);
    }
}

Employees.java

package dbObjects;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

public class Employees extends Connect {
    private String login;
    private String workgroup;
    private String csm;

    public Employees(String login, String workgroup, String csm) {
        super();
        this.login = login;
        this.workgroup = workgroup;
        this.csm = csm;
    }

    public Employees(String login) throws SQLException {
        super();
        this.login = login;
        setUserById(login);
    }

    private void setUserById(String login) throws SQLException {
        ResultSet resultSet = getResultSet("SELECT * FROM employeeData LIMIT 5");
        while(resultSet.next()) {
            System.out.println(resultSet.getString("login"));
            workgroup = resultSet.getString("workgroup");
            csm = resultSet.getString("csm");
        }
    }

    @Override
    public String toString() {
        return workgroup;
    }

}

The servlet I'm trying to run

package servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dbObjects.Employees;

/**
 * Servlet implementation class HomeServlet
 */
@WebServlet(description = "Home page shown to user", urlPatterns = { "/HomeServlet" })
public class HomeServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public HomeServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        Employees user = null;
        try {
            user = new Employees(null);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        PrintWriter pw = response.getWriter();
        pw.println(user);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

}

I've also created a simple connection test class that is working and not returning no suitable driver error.

import java.sql.DriverManager;
import java.sql.SQLException;

import com.mysql.jdbc.Connection;

public class connTest {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String url = "jdbc:mysql://host:port/database";
    String username = "username";
    String password = "password";

        System.out.println("Connecting database...");

        try (Connection connection = (Connection) DriverManager.getConnection(url, username, password)) {
            System.out.println("Database connected!");
        } catch (SQLException e) {
            throw new IllegalStateException("Cannot connect the database!", e);
        }
    }

}


来源: stackexchange

问:
When should you make an interface/contract, and when not?
As the title says: What are key points indicating you should use and interface. And what are key points indicating that you should not use an interface?

答:
Interfaces are public "contracts" whenever you want to be able to swap the implementation or give someone the flexibility to use another implementation you should use interfaces.

Example:

You want to store something so you can load it later.
You could use something like

```<code>public function save(MySQL $db, array $data);
</code>```

But this is not very flexible and it ties you code to a MySQL implementation.
If you want to be open for other implementations, because you are building an public library or framework or whatever, you should do something like this.

```<code>public function save(Persistance $storage, array $data)
{
    // dome some random stuff with you data
    ...
    $storage->save($data);
}
</code>```

In this case Persistence is an interface and it could look something like this.

```<code>interface Persistance
{
    public function save(array $data);
}
</code>```

And you local implementation could look like this.

```<code>class MySQL implements Persistance
{
    public function save(array $data)
    {
        $this->insert('my_table', $data);
    }
}
</code>```

But somebody else could use your code with a complete different persistence layer, Redis or Postgres for example, just by implementing your interface and injecting their own Persistence implementation.

This is just a simple example, but Interfaces are mostly to understand as contracts between classes and leave the implementation open.

The opportunity to implement multiple interfaces is nice but has nothing to do with multiple inheritance. Interfaces only make sure a class has some clearly defined in- and outputs, but how things are done in the background is completely open.

If you really want get into 'multiple inheritance' you should have a look at Traits.

Interfaces are used in frameworks and the PHPFig is defining a lot of standard interfaces lately to make framework components more exchangeable.

For example the PSR-16 simple cache interface makes it possible to exchange the cache layer implementation between frameworks.

Or the PSR-7 Request Response interface enables frameworks to exchange standardized middleware implementations for login, CRF security or other stuff.

There is a PSR-11 Interface for dependency injection containers, if frameworks change their implementation from their own DI container to the interface we will be able to use those frameworks with different DI container implementations.

ContentLicense: CC BY-SA 3.0

Body:
Interfaces are public "contracts" whenever you want to be able to swap the implementation or give someone the flexibility to use another implementation you should use interfaces.

Example:

You want to store something so you can load it later.
You could use something like

public function save(MySQL $db, array $data);

But this is not very flexible and it ties you code to a MySQL implementation.
If you want to be open for other implementations, because you are building an public library or framework or whatever, you should do something like this.

public function save(Persistance $storage, array $data)
{
    // dome some random stuff with you data
    ...
    $storage->save($data);
}

In this case Persistence is an interface and it could look something like this.

interface Persistance
{
    public function save(array $data);
}

And you local implementation could look like this.

class MySQL implements Persistance
{
    public function save(array $data)
    {
        $this->insert('my_table', $data);
    }
}

But somebody else could use your code with a complete different persistence layer, Redis or Postgres for example, just by implementing your interface and injecting their own Persistence implementation.

This is just a simple example, but Interfaces are mostly to understand as contracts between classes and leave the implementation open.

The opportunity to implement multiple interfaces is nice but has nothing to do with multiple inheritance. Interfaces only make sure a class has some clearly defined in- and outputs, but how things are done in the background is completely open.

If you really want get into 'multiple inheritance' you should have a look at Traits.

Interfaces are used in frameworks and the PHPFig is defining a lot of standard interfaces lately to make framework components more exchangeable.

For example the PSR-16 simple cache interface makes it possible to exchange the cache layer implementation between frameworks.

Or the PSR-7 Request Response interface enables frameworks to exchange standardized middleware implementations for login, CRF security or other stuff.

There is a PSR-11 Interface for dependency injection containers, if frameworks change their implementation from their own DI container to the interface we will be able to use those frameworks with different DI container implementations.


问:
How does Gearman communicate with workers?
I'm looking to setup Gearman in a distributed server environment. What protocol/method does it use to send jobs to [ip-address-1] and [ip-address-2] below?

```<code>$worker= new GearmanWorker();
$worker->addServers("[ip-address-1],[ip-address-2]");
</code>```

答:
I don't now how PHP do that, but with regard to gearman protocol the worker have to register itself with CAN_DO or CAN_DO_TIMEOUT command by gearman server. For instance Perl binding provides register_function method. After registration the worker have periodically to send GRAB_JOB request to the servers.

The clients send jobs to the server with one of the SUBMIT_JOB commands.

Body:
I'm looking to setup Gearman in a distributed server environment. What protocol/method does it use to send jobs to [ip-address-1] and [ip-address-2] below?

$worker= new GearmanWorker();
$worker->addServers("[ip-address-1],[ip-address-2]");


问:
graph in plotly R
Im new with plotly and i have question for you.

I have a dataset with date and value like this:

```<code>date             value
 01/01/2001     5
 ....
 01/01/2010     25
</code>```

and im plotting it with this code:

```<code>   plotr<- plot_ly(data,x = ~date, y = ~var,name='X',
                      type="scatter",mode='lines',
                      line = list(color = 'rgb(0, 0, 102)', width = 2 )) %>%
  layout(title = "My first graph",
         xaxis = list(title = "date"),
         yaxis = list (title = "number"))
  plotr
</code>```

It works fine but i want to put a note in one date for example in 2013 with his value... I searched in plotly website and i found it but i cant view my note...

https://plot.ly/r/line-charts/

anyone could help?

答:
The documentation for you is https://plot.ly/r/text-and-annotations/

And with your example:

```<code>date <- as.Date(c('2014-02-01','2015-01-11', '2016-03-01', '2017-02-01'))
var<- c(37, 54, 110, 125)
data <- data.frame(date, var)

plot_ly(data,x = ~date, y = ~var, name='X',
    type="scatter",mode='lines',
    line = list(color = 'rgb(0, 0, 102)', width = 2 )) %>%
add_annotations(x="2015-01-11",
                y=data$var[data$date=="2015-01-11"],
                text=data$var[data$date=="2015-01-11"])
</code>```

Title: graph in plotly R

Body:
Im new with plotly and i have question for you.

I have a dataset with date and value like this:

date             value
 01/01/2001     5
 ....
 01/01/2010     25

and im plotting it with this code:

   plotr<- plot_ly(data,x = ~date, y = ~var,name='X',
                      type="scatter",mode='lines',
                      line = list(color = 'rgb(0, 0, 102)', width = 2 )) %>%
  layout(title = "My first graph",
         xaxis = list(title = "date"),
         yaxis = list (title = "number"))
  plotr

It works fine but i want to put a note in one date for example in 2013 with his value... I searched in plotly website and i found it but i cant view my note...

https://plot.ly/r/line-charts/

anyone could help?

Body:
The documentation for you is https://plot.ly/r/text-and-annotations/

And with your example:

date <- as.Date(c('2014-02-01','2015-01-11', '2016-03-01', '2017-02-01'))
var<- c(37, 54, 110, 125)
data <- data.frame(date, var)

plot_ly(data,x = ~date, y = ~var, name='X',
    type="scatter",mode='lines',
    line = list(color = 'rgb(0, 0, 102)', width = 2 )) %>%
add_annotations(x="2015-01-11",
                y=data$var[data$date=="2015-01-11"],
                text=data$var[data$date=="2015-01-11"])


问:
Connecting to an online database in c#
So I'm a developer and we're running a project. I'm using HeidiSQL to connect to our DB, which uses TCP/IP over port 3306 with
my username and password.

I'm developing something in c# for the server and I want to connect to the database which is hosted on the IP(I'm connecting
to the IP via HeidiSQL normally btw, it works fine).

And when I try it in c#,

```<code>string connectionstring = "Data Source=ourIP,3306;Initial Catalog=auth, User ID=myusernameforserv, Password=mypasswordforserv";
            SqlConnection conn = new SqlConnection(connectionstring);
            try
            {
                conn.Open();
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.Message);
            }
</code>```

and I get an error saying that it can't connect to the database. First it was saying that the database doesn't exist or that
I don't have access to it, now it gives me the error "Error state:18".

I'm not using any NuGET's on my code, just the using system.sql.dataclient.

答:
Try using semi-colons after each thing, just as you have after the data source. </p>

```<code>string connectionstring = "Data Source=ourIP,3306;Initial Catalog=auth;User ID=myusernameforserv;Password=mypasswordforserv";
</code>```

Title: Connecting to an online database in c#

Body:
So I'm a developer and we're running a project. I'm using HeidiSQL to connect to our DB, which uses TCP/IP over port 3306 with
my username and password.

I'm developing something in c# for the server and I want to connect to the database which is hosted on the IP(I'm connecting
to the IP via HeidiSQL normally btw, it works fine).

And when I try it in c#,

string connectionstring = "Data Source=ourIP,3306;Initial Catalog=auth, User ID=myusernameforserv, Password=mypasswordforserv";
            SqlConnection conn = new SqlConnection(connectionstring);
            try
            {
                conn.Open();
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.Message);
            }

and I get an error saying that it can't connect to the database. First it was saying that the database doesn't exist or that
I don't have access to it, now it gives me the error "Error state:18".

I'm not using any NuGET's on my code, just the using system.sql.dataclient.

Body:
Try using semi-colons after each thing, just as you have after the data source.

string connectionstring = "Data Source=ourIP,3306;Initial Catalog=auth;User ID=myusernameforserv;Password=mypasswordforserv";


问:
Different popup for textbox change?
I have 10 textboxes in Company page. 5 of them are common in Location page.
My goal is to ask user if he wants to update just company page or even location page. If the user changes 5 textboxes
that are common in Location Page, the popup shows as "Do you want to update Location Page as well" or if the user changes the other 5, then popup shows
"Do you want to save?"

How do we determine what textboxs are changed and which popup should be shown?? Could someone help me out. Thanks all :)

答:
One of the methods is:

install jquery (just for easier access to controls)

assign a className like class='common' to the first set of textboxes

assign another className like class='other' to the second set of textboxes

handle onblur event for 'commons':

```<code>$(":input.common").blur(function() {
  if ($(this).data("changed") && confirm("Do you want to update Location Page as well?")) {
    // TODO: perform update
  }
}).keydown(function(e) {
  $(this).data("changed", true);
}).focus(function(e) {
  $(this).data("changed", false);
});
</code>```

handle onblur event for 'others':

```<code>$(":input.other").blur(function() {
  if ($(this).data("changed") && confirm("Do you want to save?")) {
    // TODO: perform save
  }
}).keydown(function(e) {
  $(this).data("changed", true);
}).focus(function(e) {
  $(this).data("changed", false);
});
</code>```

Got an idea?

ContentLicense: CC BY-SA 2.5

Title: Different popup for textbox change?

Body:
One of the methods is:

install jquery (just for easier access to controls)

assign a className like class='common' to the first set of textboxes

assign another className like class='other' to the second set of textboxes

handle onblur event for 'commons':

$(":input.common").blur(function() {
  if ($(this).data("changed") && confirm("Do you want to update Location Page as well?")) {
    // TODO: perform update
  }
}).keydown(function(e) {
  $(this).data("changed", true);
}).focus(function(e) {
  $(this).data("changed", false);
});

handle onblur event for 'others':

$(":input.other").blur(function() {
  if ($(this).data("changed") && confirm("Do you want to save?")) {
    // TODO: perform save
  }
}).keydown(function(e) {
  $(this).data("changed", true);
}).focus(function(e) {
  $(this).data("changed", false);
});

Got an idea?


问:
How to maintain a counter variable thats value can be used in Page Init
This subject seems to be be beaten to death and yet I still can't find an answer.

I am trying to allow users to click a button to add a usercontrol to a page. Hypothetically, they can do this as many times as they want. I know I need to recreate these controls on Postback, and am trying to do this in Page Init so that viewstate can give them back their values in page load.

My problem is I have no idea how to keep a running counter that I can use in Init to recreate the proper number of controls the user has put on the page. Viewstate is not available in Init so I can't just use a hidden field where I could increment or decrement the value. I also cannot use Session variables. I am not allowed to use them in this particular project.

As an FYI, I'm adding and deleting these usercontrols successfully right now when I do it on Page Load. But, the fields within the usercontrol do not retain their values consistently between postbacks.

答: You can always keep this count in the client, and add it to the URL for instance.</p>


问:
How can I pass a malloc array to another function in order to change its values
I am trying to implement a bubble sort algorithm, but with 3 functions, a gen_array to generate the array given a size and a maximum for the values and a sort to sort the values in a bubble sort way. I can't get the sort part to work.
However, the gen_array funcion is doing what it is supposed to and working when I call it and print its values on main().

Here is the code.

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

int gen_array(int ** list, int size, int max) {

    *list = (int *)malloc(size * sizeof(int));

        if (*list == NULL){
        printf("ERROR: out of memory\n");
        return 1;
    }

    srand( (unsigned)time( NULL ) );
    for (int i = 0; i < size; ++i) {
        (*list)[i] = rand() % max;
    }
    return 0;
}

int sort(int * a, int s) {
    int *temp;

    for (int i = 1; i < s; ++i) {
        for (int j = 0; j < i - 1; ++j) {
            if (*(a + i) > *(a + i + 1)) {
                *(a + i) = temp;
                *(a + i) = *(a + i + 1);
                *(a + i + 1) = temp;
            }
        }

    }
    return 0;
}

int main() {

    int size;
    printf("array Size --> ");
    scanf("%d", &size);
    int * a;

    gen_array(&a ,size, 100);
    for (int i = 0; i < size; ++i) {
        printf("%d ", a[i]);
    }

    printf("\n");
    sort(a, size);
    for (int j = 0; j < size; ++j) {
        printf("%d", a[j]);
    }

    free(a);
    getchar();
    return 0;
}
</code>```

After following @mch's comment I got this output,

Array Size --> 5

1 4 46 4 51

1 4 4 0 0

Process finished with exit code 0

So, the list is generating with 5 elements,
but the sort part isn't working, I believe the sort code is right (the bubble algorithm), but the pointers aren't being used correctly?
Perhaps I should copy the contents of the array with realloc() ?

答:
There are several problematic errors in your code.

First, temp should be int, not int*. Remember, a is a pointer to the start of an array in the heap. *(a + i) is the value of the ith element of that array.

Second, temp should be set to *(a + i), not the other way around.

Also, as Weather Vane pointed out in the comments, the loops are wrong. You need to check array elements j and j + 1, not i. There are some other changes needed as part of that, but you can see those below.

Here's the sort method with these changes (I think the rest is all right except that you need to add spaces the second time you list the items):

```<code>int sort(int *a, int s) {
    int temp;

    for (int i = 0; i < s; ++i) {
        for (int j = 0; j < s - i - 1; ++j) {
            if (*(a + j) > *(a + j + 1)) {
                temp = *(a + j);
                *(a + j) = *(a + j + 1);
                *(a + j + 1) = temp;
            }
        }

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

Body:
I am trying to implement a bubble sort algorithm, but with 3 functions, a gen_array to generate the array given a size and a maximum for the values and a sort to sort the values in a bubble sort way. I can't get the sort part to work.
However, the gen_array funcion is doing what it is supposed to and working when I call it and print its values on main().

Here is the code.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int gen_array(int ** list, int size, int max) {

    *list = (int *)malloc(size * sizeof(int));

        if (*list == NULL){
        printf("ERROR: out of memory\n");
        return 1;
    }

    srand( (unsigned)time( NULL ) );
    for (int i = 0; i < size; ++i) {
        (*list)[i] = rand() % max;
    }
    return 0;
}

int sort(int * a, int s) {
    int *temp;

    for (int i = 1; i < s; ++i) {
        for (int j = 0; j  *(a + i + 1)) {
                *(a + i) = temp;
                *(a + i) = *(a + i + 1);
                *(a + i + 1) = temp;
            }
        }

    }
    return 0;
}

int main() {

    int size;
    printf("array Size --> ");
    scanf("%d", &size);
    int * a;

    gen_array(&a ,size, 100);
    for (int i = 0; i < size; ++i) {
        printf("%d ", a[i]);
    }

    printf("\n");
    sort(a, size);
    for (int j = 0; j < size; ++j) {
        printf("%d", a[j]);
    }

    free(a);
    getchar();
    return 0;
}

After following @mch's comment I got this output,

Array Size --> 5

1 4 46 4 51

1 4 4 0 0

Process finished with exit code 0

So, the list is generating with 5 elements,
but the sort part isn't working, I believe the sort code is right (the bubble algorithm), but the pointers aren't being used correctly?
Perhaps I should copy the contents of the array with realloc() ?

Body:
There are several problematic errors in your code.

First, temp should be int, not int*. Remember, a is a pointer to the start of an array in the heap. *(a + i) is the value of the ith element of that array.

Second, temp should be set to *(a + i), not the other way around.

Also, as Weather Vane pointed out in the comments, the loops are wrong. You need to check array elements j and j + 1, not i. There are some other changes needed as part of that, but you can see those below.

Here's the sort method with these changes (I think the rest is all right except that you need to add spaces the second time you list the items):

int sort(int *a, int s) {
    int temp;

    for (int i = 0; i < s; ++i) {
        for (int j = 0; j < s - i - 1; ++j) {
            if (*(a + j) > *(a + j + 1)) {
                temp = *(a + j);
                *(a + j) = *(a + j + 1);
                *(a + j + 1) = temp;
            }
        }

    }
    return 0;
}


问:
async_connect doesn't call handler in TCP client class
I'm trying to make a client class from boost TCP client example for my projects, and I've noticed that sometimes handle_connect doesn't get called when connecting to nonexistent host.

I've read similar issues here on stack, where people forgot to run io_service or called it before any tasks were posted, but I don't think that's my case, since I launch io_service.run() thread right after calling async_connect, and successfull connect, network unreachable, and some other cases I've tested work just fine.

Here is the full listing:

tcp_client.hpp

```<code>#ifndef TCP_CLIENT_HPP
#define TCP_CLIENT_HPP

#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/chrono.hpp>
#include <boost/thread/thread.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/make_shared.hpp>
#include <mutex>
#include <iostream>
#include <iomanip>

namespace com {

using boost::asio::ip::tcp;
using namespace std;

class client : public boost::enable_shared_from_this<client> {

private:

  std::mutex mx_;
  bool stopped_ = 1;
  boost::asio::streambuf ibuf_;
  boost::shared_ptr<boost::asio::io_service> io_service_;
  boost::shared_ptr<boost::asio::ip::tcp::socket> sock_;
  boost::shared_ptr<tcp::resolver::iterator> ei_;
  std::vector<std::string> inbound_;
  std::string host_, port_;

public:

  client() {}

  void connect( std::string host, std::string port ) {
    if (!stopped_) stop();
    host_ = host; port_ = port;
    io_service_.reset(new boost::asio::io_service);
    sock_.reset(new boost::asio::ip::tcp::socket(*io_service_));
    ei_.reset(new tcp::resolver::iterator);
    tcp::resolver r(*io_service_);
    ei_ = boost::make_shared<tcp::resolver::iterator>( r.resolve(tcp::resolver::query(host_, port_)) );
    stopped_ = 0;
    start_connect();
    boost::thread work( boost::bind(&client::work, shared_from_this()) );
    return;
  }

  bool is_running() {
    return !stopped_;
  }

  void stop() {
    stopped_ = 1;
    sock_->close();
    return;
  }

  void send(std::string str) {
    if (stopped_) return;
    auto msg = boost::asio::buffer(str, str.size());
    boost::asio::async_write( (*sock_), msg, boost::bind(&client::handle_write, shared_from_this(), _1) );
    return;
  }

  std::string pull() {
    std::lock_guard<std::mutex> lock(mx_);
    std::string msg;
    if (inbound_.size()>0) {
      msg = inbound_.at(0);
      inbound_.erase(inbound_.begin());
    }
    return msg;
  }

  int size() {
    std::lock_guard<std::mutex> lock(mx_);
    return inbound_.size();
  }

  void clear() {
    std::lock_guard<std::mutex> lock(mx_);
    inbound_.clear();
    return;
  }

private:

  void work() {
    if (stopped_) return;
    std::cout<<"work in"<<std::endl;
    io_service_->run();
    std::cout<<"work out"<<std::endl;
    return;
  }

  void start_connect() {
    if ((*ei_) != tcp::resolver::iterator()) {
      std::cout<<"Trying "<<(*ei_)->endpoint()<<std::endl;
      sock_->async_connect( (*ei_)->endpoint(), boost::bind(&client::handle_connect, shared_from_this(), boost::asio::placeholders::error) );
    } else {
      stop();
    }
    return;
  }

  void handle_connect(const boost::system::error_code& ec) {
    if (stopped_) return;

    if (!sock_->is_open()) {
      std::cout<<"Socket closed"<<std::endl;
      (*ei_)++;
      start_connect();
    } else if (ec) {
      std::cout<<"Connect error: "<<ec.message()<<std::endl;
      sock_->close();
      (*ei_)++;
      start_connect();
    } else {
      std::cout<<"Connected to "<<(*ei_)->endpoint()<<std::endl;
      start_read();
    }

    return;
  }

  void start_read() {
    if (stopped_) return;
    boost::asio::async_read_until((*sock_), ibuf_, "", boost::bind(&client::handle_read, shared_from_this(), boost::asio::placeholders::error));
    return;
  }

  void handle_read(const boost::system::error_code& ec) {
    std::lock_guard<std::mutex> lock(mx_);
    if (stopped_) return;
    if (ec) {
      std::cout<<"Read error: "<<ec.message()<<std::endl;
      stop();
      return;
    }

    std::string line;
    std::istream is(&ibuf_);
    std::getline(is, line);
    if (!line.empty() && inbound_.size()<1000) inbound_.push_back(line);

    start_read();
    return;
  }

private:

  void handle_write(const boost::system::error_code& ec) {
    if (stopped_) return;
    if (ec) {
      std::cout<<"Write error: "<<ec.message()<<std::endl;
      stop();
      return;
    }
    return;
  }

};

};
</code>```

and tcp_test.cpp

```<code>#include "tcp_client.hpp"

int main(int argc, char* argv[]) {
  auto tcp_client = boost::shared_ptr<com::client>(new com::client);

  try {
    tcp_client->connect("192.168.1.15", "50000");
    boost::this_thread::sleep_for(boost::chrono::milliseconds(1000));
    tcp_client->connect("192.168.1.20", "50000");
  } catch (std::exception& e) {
    std::cerr<<"Exception: "<<e.what()<<std::endl;
  }

  int cnt=0;
  while (cnt<5) {
    std::cout<<cnt<<std::endl;
    cnt++;
    tcp_client->send("<test>");
    boost::this_thread::sleep_for(boost::chrono::milliseconds(500));
  }

  tcp_client->stop();

  while (tcp_client->size()>0) std::cout<<tcp_client->pull()<<std::endl;

  return 0;
}
</code>```

The output I get is when connecting to loopback server:

```<code>Trying 192.168.1.15:50000
work in
work out
Trying 192.168.1.20:50000
0
work in
Connected to 192.168.1.20:50000
1
2
3
4
work out
<test>
<test>
<test>
<test>
<test>
</code>```

The 192.168.1.20 works just as it should, as you see. The 192.168.1.15 doesnt'e exist, but I've expected it to throw some kind of error. Instead io_service.run() returns right away, like async_connect never posted callback task. Maybe it's related to endpoint iterator and not async_connect?

Can anyone please explain why is it happening like this?

Then I've tried to isolate the problem in this code:

```<code>#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/chrono.hpp>
#include <boost/thread/thread.hpp>

boost::asio::io_service io_svc;
boost::asio::ip::tcp::socket sock(io_svc);
boost::asio::ip::tcp::resolver::iterator ei;

void work() {
  std::cout<<"work in"<<std::endl;
  io_svc.run();
  std::cout<<"work out"<<std::endl;
  return;
}

void stop() {
  sock.close();
  return;
}

void start_connect();

void handle_connect(const boost::system::error_code& ec) {
  if (!sock.is_open()) {
    std::cout<<"Socket closed"<<std::endl;
    ei++;
    start_connect();
  } else if (ec) {
    std::cout<<"Connect error: "<<ec.message()<<std::endl;
    sock.close();
    ei++;
    start_connect();
  } else {
    std::cout<<"Connected to "<<ei->endpoint()<<std::endl;
  }
  return;
}

void start_connect() {
  if (ei != boost::asio::ip::tcp::resolver::iterator()) {
    std::cout<<"Trying "<<ei->endpoint()<<std::endl;
    sock.async_connect( ei->endpoint(), boost::bind(handle_connect, boost::asio::placeholders::error) );
  } else {
    stop();
  }
  return;
}

int main(int argc, char* argv[]) {

  std::string host="192.168.1.15", port="50000";

  boost::asio::ip::tcp::resolver r(io_svc);
  ei = r.resolve(boost::asio::ip::tcp::resolver::query(host, port));
  start_connect();
  boost::thread* thr = new boost::thread(work);

  boost::this_thread::sleep_for(boost::chrono::milliseconds(2000));

  return 0;
}
</code>```

But I've got a totally different result. When I try to connect to a nonexistent host, most of the time it's:

```<code>Trying 192.168.1.15:50000
work in
</code>```

Sometimes it's:

```<code>Trying 192.168.1.15:50000
work in
Connect error: Operation canceled
Connect error: Operation canceled
</code>```

And rarely it's:

```<code>Trying 192.168.1.15:50000
work in
Segmentation fault
</code>```

"work out" is never printed, so I'm guessing io_service in this example is doing something, but how is this different from previous code, and why I get "operation canceled" error only sometimes?

答:
A client running in a background thread should look something like this.

Note that I have note included things like connection timeouts. For that you'd want to have a deadline timer running in parallel with the async_connect. Then you'd have to correctly handle crossing cases (hint: cancel the deadline timer on successful connect and throw away the ensuing error from its async_wait).

```<code>#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/chrono.hpp>
#include <thread>
#include <functional>

boost::asio::io_service io_svc;

struct client
    : std::enable_shared_from_this<client>
{
    using protocol = boost::asio::ip::tcp;
    using resolver = protocol::resolver;
    using socket = protocol::socket;

    using error_code = boost::system::error_code;

    client(boost::asio::io_service& ios)
        : ios_(ios) {}

    void start(std::string const& host, std::string const& service)
    {
        auto presolver = std::make_shared<resolver>(get_io_service());

        presolver->async_resolve(protocol::resolver::query(host, service),
                                 strand_.wrap([self = shared_from_this(), presolver](auto&& ec, auto iter)
                                              {
                                                  self->handle_resolve(ec, presolver, iter);
                                              }));

    }

private:
    void
    handle_resolve(boost::system::error_code const& ec, std::shared_ptr<resolver> presolver, resolver::iterator iter)
    {
        if (ec) {
            std::cerr << "error resolving: " << ec.message() << std::endl;
        }
        else {
            boost::asio::async_connect(sock, iter, strand_.wrap([self = shared_from_this(),
                                                                    presolver]
                                                                    (auto&& ec, auto iter)
                                                                {
                                                                    self->handle_connect(ec, iter);
                                                                    // note - we're dropping presolver here - we don't need it any more
                                                                }));
        }
    }

    void handle_connect(error_code const& ec, resolver::iterator iter)
    {
        if (ec) {
            std::cerr << "failed to connect: " << ec.message() << std::endl;
        }
        else {
            auto payload = std::make_shared<std::string>("Hello");

            boost::asio::async_write(sock, boost::asio::buffer(*payload),
                                     strand_.wrap([self = shared_from_this(),
                                                      payload] // note! capture the payload so it continues to exist during async send
                                                      (auto&& ec, auto size)
                                                  {
                                                      self->handle_send(ec, size);
                                                  }));
        }
    }

    void handle_send(error_code const& ec, std::size_t size)
    {
        if (ec) {
            std::cerr << "send failed after " << size << " butes : " << ec.message() << std::endl;
        }
        else {
            // send something else?
        }
    }

    boost::asio::io_service& get_io_service()
    {
        return ios_;
    }

private:

    boost::asio::io_service& ios_;
    boost::asio::strand strand_{get_io_service()};
    socket              sock{get_io_service()};

};

void work()
{
    std::cout << "work in" << std::endl;
    io_svc.run();
    std::cout << "work out" << std::endl;
    return;
}

int main(int argc, char *argv[])
{

    auto        pclient = std::make_shared<client>(io_svc);
    std::string host    = "192.168.1.15", port = "50000";
    pclient->start(host, port);

    auto run_thread = std::thread(work);
    if (run_thread.joinable())
        run_thread.join();

    return 0;
}
</code>```

example output:

```<code>work in
    <time passes>...
failed to connect: Operation timed out
work out
</code>```

Body:
I'm trying to make a client class from boost TCP client example for my projects, and I've noticed that sometimes handle_connect doesn't get called when connecting to nonexistent host.

I've read similar issues here on stack, where people forgot to run io_service or called it before any tasks were posted, but I don't think that's my case, since I launch io_service.run() thread right after calling async_connect, and successfull connect, network unreachable, and some other cases I've tested work just fine.

Here is the full listing:

tcp_client.hpp

#ifndef TCP_CLIENT_HPP
#define TCP_CLIENT_HPP

#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/chrono.hpp>
#include <boost/thread/thread.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/make_shared.hpp>
#include <mutex>
#include <iostream>
#include <iomanip>

namespace com {

using boost::asio::ip::tcp;
using namespace std;

class client : public boost::enable_shared_from_this<client> {

private:

  std::mutex mx_;
  bool stopped_ = 1;
  boost::asio::streambuf ibuf_;
  boost::shared_ptr<boost::asio::io_service> io_service_;
  boost::shared_ptr<boost::asio::ip::tcp::socket> sock_;
  boost::shared_ptr<tcp::resolver::iterator> ei_;
  std::vector<std::string> inbound_;
  std::string host_, port_;

public:

  client() {}

  void connect( std::string host, std::string port ) {
    if (!stopped_) stop();
    host_ = host; port_ = port;
    io_service_.reset(new boost::asio::io_service);
    sock_.reset(new boost::asio::ip::tcp::socket(*io_service_));
    ei_.reset(new tcp::resolver::iterator);
    tcp::resolver r(*io_service_);
    ei_ = boost::make_shared<tcp::resolver::iterator>( r.resolve(tcp::resolver::query(host_, port_)) );
    stopped_ = 0;
    start_connect();
    boost::thread work( boost::bind(&client::work, shared_from_this()) );
    return;
  }

  bool is_running() {
    return !stopped_;
  }

  void stop() {
    stopped_ = 1;
    sock_->close();
    return;
  }

  void send(std::string str) {
    if (stopped_) return;
    auto msg = boost::asio::buffer(str, str.size());
    boost::asio::async_write( (*sock_), msg, boost::bind(&client::handle_write, shared_from_this(), _1) );
    return;
  }

  std::string pull() {
    std::lock_guard<std::mutex> lock(mx_);
    std::string msg;
    if (inbound_.size()>0) {
      msg = inbound_.at(0);
      inbound_.erase(inbound_.begin());
    }
    return msg;
  }

  int size() {
    std::lock_guard<std::mutex> lock(mx_);
    return inbound_.size();
  }

  void clear() {
    std::lock_guard<std::mutex> lock(mx_);
    inbound_.clear();
    return;
  }

private:

  void work() {
    if (stopped_) return;
    std::cout<<"work in"<<std::endl;
    io_service_->run();
    std::cout<<"work out"<<std::endl;
    return;
  }

  void start_connect() {
    if ((*ei_) != tcp::resolver::iterator()) {
      std::cout<<"Trying "<<(*ei_)->endpoint()<<std::endl;
      sock_->async_connect( (*ei_)->endpoint(), boost::bind(&client::handle_connect, shared_from_this(), boost::asio::placeholders::error) );
    } else {
      stop();
    }
    return;
  }

  void handle_connect(const boost::system::error_code& ec) {
    if (stopped_) return;

    if (!sock_->is_open()) {
      std::cout<<"Socket closed"<<std::endl;
      (*ei_)++;
      start_connect();
    } else if (ec) {
      std::cout<<"Connect error: "<<ec.message()<<std::endl;
      sock_->close();
      (*ei_)++;
      start_connect();
    } else {
      std::cout<<"Connected to "<<(*ei_)->endpoint()<<std::endl;
      start_read();
    }

    return;
  }

  void start_read() {
    if (stopped_) return;
    boost::asio::async_read_until((*sock_), ibuf_, "", boost::bind(&client::handle_read, shared_from_this(), boost::asio::placeholders::error));
    return;
  }

  void handle_read(const boost::system::error_code& ec) {
    std::lock_guard<std::mutex> lock(mx_);
    if (stopped_) return;
    if (ec) {
      std::cout<<"Read error: "<<ec.message()<<std::endl;
      stop();
      return;
    }

    std::string line;
    std::istream is(&ibuf_);
    std::getline(is, line);
    if (!line.empty() && inbound_.size()<1000) inbound_.push_back(line);

    start_read();
    return;
  }

private:

  void handle_write(const boost::system::error_code& ec) {
    if (stopped_) return;
    if (ec) {
      std::cout<<"Write error: "<<ec.message()<<std::endl;
      stop();
      return;
    }
    return;
  }

};

};

and tcp_test.cpp

#include "tcp_client.hpp"

int main(int argc, char* argv[]) {
  auto tcp_client = boost::shared_ptr<com::client>(new com::client);

  try {
    tcp_client->connect("192.168.1.15", "50000");
    boost::this_thread::sleep_for(boost::chrono::milliseconds(1000));
    tcp_client->connect("192.168.1.20", "50000");
  } catch (std::exception& e) {
    std::cerr<<"Exception: "<<e.what()<<std::endl;
  }

  int cnt=0;
  while (cnt<5) {
    std::cout<<cnt<<std::endl;
    cnt++;
    tcp_client->send("<test>");
    boost::this_thread::sleep_for(boost::chrono::milliseconds(500));
  }

  tcp_client->stop();

  while (tcp_client->size()>0) std::cout<<tcp_client->pull()<<std::endl;

  return 0;
}

The output I get is when connecting to loopback server:

Trying 192.168.1.15:50000
work in
work out
Trying 192.168.1.20:50000
0
work in
Connected to 192.168.1.20:50000
1
2
3
4
work out
<test>
<test>
<test>
<test>
<test>

The 192.168.1.20 works just as it should, as you see. The 192.168.1.15 doesnt'e exist, but I've expected it to throw some kind of error. Instead io_service.run() returns right away, like async_connect never posted callback task. Maybe it's related to endpoint iterator and not async_connect?

Can anyone please explain why is it happening like this?

Then I've tried to isolate the problem in this code:

#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/chrono.hpp>
#include <boost/thread/thread.hpp>

boost::asio::io_service io_svc;
boost::asio::ip::tcp::socket sock(io_svc);
boost::asio::ip::tcp::resolver::iterator ei;

void work() {
  std::cout<<"work in"<<std::endl;
  io_svc.run();
  std::cout<<"work out"<<std::endl;
  return;
}

void stop() {
  sock.close();
  return;
}

void start_connect();

void handle_connect(const boost::system::error_code& ec) {
  if (!sock.is_open()) {
    std::cout<<"Socket closed"<<std::endl;
    ei++;
    start_connect();
  } else if (ec) {
    std::cout<<"Connect error: "<<ec.message()<<std::endl;
    sock.close();
    ei++;
    start_connect();
  } else {
    std::cout<<"Connected to "<<ei->endpoint()<<std::endl;
  }
  return;
}

void start_connect() {
  if (ei != boost::asio::ip::tcp::resolver::iterator()) {
    std::cout<<"Trying "<<ei->endpoint()<<std::endl;
    sock.async_connect( ei->endpoint(), boost::bind(handle_connect, boost::asio::placeholders::error) );
  } else {
    stop();
  }
  return;
}

int main(int argc, char* argv[]) {

  std::string host="192.168.1.15", port="50000";

  boost::asio::ip::tcp::resolver r(io_svc);
  ei = r.resolve(boost::asio::ip::tcp::resolver::query(host, port));
  start_connect();
  boost::thread* thr = new boost::thread(work);

  boost::this_thread::sleep_for(boost::chrono::milliseconds(2000));

  return 0;
}

But I've got a totally different result. When I try to connect to a nonexistent host, most of the time it's:

Trying 192.168.1.15:50000
work in

Sometimes it's:

Trying 192.168.1.15:50000
work in
Connect error: Operation canceled
Connect error: Operation canceled

And rarely it's:

Trying 192.168.1.15:50000
work in
Segmentation fault

"work out" is never printed, so I'm guessing io_service in this example is doing something, but how is this different from previous code, and why I get "operation canceled" error only sometimes?

Body:
A client running in a background thread should look something like this.

Note that I have note included things like connection timeouts. For that you'd want to have a deadline timer running in parallel with the async_connect. Then you'd have to correctly handle crossing cases (hint: cancel the deadline timer on successful connect and throw away the ensuing error from its async_wait).

#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/chrono.hpp>
#include <thread>
#include <functional>

boost::asio::io_service io_svc;

struct client
    : std::enable_shared_from_this<client>
{
    using protocol = boost::asio::ip::tcp;
    using resolver = protocol::resolver;
    using socket = protocol::socket;

    using error_code = boost::system::error_code;

    client(boost::asio::io_service& ios)
        : ios_(ios) {}

    void start(std::string const& host, std::string const& service)
    {
        auto presolver = std::make_shared<resolver>(get_io_service());

        presolver->async_resolve(protocol::resolver::query(host, service),
                                 strand_.wrap([self = shared_from_this(), presolver](auto&& ec, auto iter)
                                              {
                                                  self->handle_resolve(ec, presolver, iter);
                                              }));

    }

private:
    void
    handle_resolve(boost::system::error_code const& ec, std::shared_ptr<resolver> presolver, resolver::iterator iter)
    {
        if (ec) {
            std::cerr << "error resolving: " << ec.message() << std::endl;
        }
        else {
            boost::asio::async_connect(sock, iter, strand_.wrap([self = shared_from_this(),
                                                                    presolver]
                                                                    (auto&& ec, auto iter)
                                                                {
                                                                    self->handle_connect(ec, iter);
                                                                    // note - we're dropping presolver here - we don't need it any more
                                                                }));
        }
    }

    void handle_connect(error_code const& ec, resolver::iterator iter)
    {
        if (ec) {
            std::cerr << "failed to connect: " << ec.message() << std::endl;
        }
        else {
            auto payload = std::make_shared<std::string>("Hello");

            boost::asio::async_write(sock, boost::asio::buffer(*payload),
                                     strand_.wrap([self = shared_from_this(),
                                                      payload] // note! capture the payload so it continues to exist during async send
                                                      (auto&& ec, auto size)
                                                  {
                                                      self->handle_send(ec, size);
                                                  }));
        }
    }

    void handle_send(error_code const& ec, std::size_t size)
    {
        if (ec) {
            std::cerr << "send failed after " << size << " butes : " << ec.message() << std::endl;
        }
        else {
            // send something else?
        }
    }

    boost::asio::io_service& get_io_service()
    {
        return ios_;
    }

private:

    boost::asio::io_service& ios_;
    boost::asio::strand strand_{get_io_service()};
    socket              sock{get_io_service()};

};

void work()
{
    std::cout << "work in" << std::endl;
    io_svc.run();
    std::cout << "work out" << std::endl;
    return;
}

int main(int argc, char *argv[])
{

    auto        pclient = std::make_shared<client>(io_svc);
    std::string host    = "192.168.1.15", port = "50000";
    pclient->start(host, port);

    auto run_thread = std::thread(work);
    if (run_thread.joinable())
        run_thread.join();

    return 0;
}

example output:

work in
    <time passes>...
failed to connect: Operation timed out
work out


问:
Java Hashmap/Hashtable and numbering
the question is simple - I have to implement JTree TreeModel interface which requires that every object has a number. The tree will represent data that are kept in hashmap/hashtable. Keys in that hashmap are client objects and values are arrays of resources (or ArrayLists) so numbering is only a problem at the top level. What would be the easiest way to number keys in Hashmap/Hashtable?</p>

答:
```<code>public class IndexedMap<V> extends HashMap<Long, V> {
    private AtomicLong index = new AtomicLong();

    public void put(V value) {
        put(index.getAndIncrement(), value);
    }
}
</code>```

```<code>IndexedMap<Object> objects = new IndexedMap<Object>();
objects.put("foo");
objects.put("bar");
// ...
</code>```

But why don't you just use an ArrayList? It holds objects by an index, exactly what you need.

Title: Java Hashmap/Hashtable and numbering

Body:
public class IndexedMap<V> extends HashMap<Long, V> {
    private AtomicLong index = new AtomicLong();

    public void put(V value) {
        put(index.getAndIncrement(), value);
    }
}

IndexedMap<Object> objects = new IndexedMap<Object>();
objects.put("foo");
objects.put("bar");
// ...

But why don't you just use an ArrayList? It holds objects by an index, exactly what you need.


问:
How does mysql do multi-type comparison?
I was working on a project and due to a miscomprehension, we ended up comparing a stored int with a string in a MySql database. I ran a few test and it seems to work but I would like to know how MySql compares different datatypes.

Does it convert one to the other? If it does does it convert both to strings or to ints?

答:
When you use a string in an integer context, for example in an arithmetic expression or in a comparison to an integer, MySQL takes the numeric value of that string as a DOUBLE data type.

See https://dev.mysql.com/doc/refman/5.7/en/type-conversion.html

Demonstration:

```<code>mysql> create table foo as select 1+'1' as x;

mysql> show create table foo\G
CREATE TABLE `foo` (
  `x` double NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=latin1
</code>```

The numeric value of a string is the numeric value of any leading digit characters or other characters that make a floating-point number, like -+.e.

For example, the numeric value of '123abc' is 123.

Scientific notation is supported.

```<code>mysql> select 1 + '5e-2xyz' as n;
+------+
| n    |
+------+
| 1.05 |
+------+
</code>```

If there are no leading characters that form a numeric value, the string's numeric value is 0.

Body:
When you use a string in an integer context, for example in an arithmetic expression or in a comparison to an integer, MySQL takes the numeric value of that string as a DOUBLE data type.

See https://dev.mysql.com/doc/refman/5.7/en/type-conversion.html

Demonstration:

mysql> create table foo as select 1+'1' as x;

mysql> show create table foo\G
CREATE TABLE `foo` (
  `x` double NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=latin1

The numeric value of a string is the numeric value of any leading digit characters or other characters that make a floating-point number, like -+.e.

For example, the numeric value of '123abc' is 123.

Scientific notation is supported.

mysql> select 1 + '5e-2xyz' as n;
+------+
| n    |
+------+
| 1.05 |
+------+

If there are no leading characters that form a numeric value, the string's numeric value is 0.


问:
How can I send request to server for Login
I am beginner in JavaScript, jQuery.

My question is: I have a server called: http://server.address:port/login by using the following parameters

Username

Password

If successful, then server sends back a json object like this:

```<code>{
"username" : "name of the user"
"token": "tokenfromserverobject"
}
</code>```

I put my html class below and I want to write related code inside

```<code><script type="text/javascript" </script>
</code>```

tags.

How can I send login via Post method as I write above and get from server response?

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Login Page</title>
    <meta name="author" content="Anonymous">
    <link href="bootstrap.css" rel="stylesheet">
    <link href="bootstrap-grid.css" rel="stylesheet">
    <link href="bootstrap-reboot.css" rel="stylesheet" >
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5"/css/bootstrap.min.css>
    <link href="bootstrap.min.css" rel="stylesheet">
    <link href="bootstrap-reboot.min.css" rel="stylesheet">
    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet">

    <link rel="stylesheet" type="text/css" href="style.css">
    <link rel="stylesheet" type="text/css" href="bootstrap.css">
    <link rel="stylesheet" type="text/css" href="bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="bootstrap-reboot.min.css">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

        <form class="form-signin">

            <input type="text" id="inputEmail" class="form-control" placeholder="Username" required autofocus>
            <input type="password" id="inputPassword" class="form-control" placeholder="Password" required>

                    <input type="checkbox" value="remember-me"> Remember me

            <button class="btn btn-lg btn-primary btn-block btn-signin" type="submit" id="sendauth">Sign in</button>
        </form>

            Forgot the password?

```

答:
Try with ajax:</p>

```<code>$.ajax({
    type: 'POST',
    url: 'http://server.address:port/login',
    data: {
        'Username': 'yourUserName',
        'Password': 'yourPass'
    },
    success: function(msg){
        alert(msg);
    }
});
</code>```

Body:
I am beginner in JavaScript, jQuery.

My question is: I have a server called: http://server.address:port/login by using the following parameters

Username

Password

If successful, then server sends back a json object like this:

{
"username" : "name of the user"
"token": "tokenfromserverobject"
}

I put my html class below and I want to write related code inside

tags.

How can I send login via Post method as I write above and get from server response?

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Login Page</title>
    <meta name="author" content="Anonymous">
    <link href="bootstrap.css" rel="stylesheet">
    <link href="bootstrap-grid.css" rel="stylesheet">
    <link href="bootstrap-reboot.css" rel="stylesheet" >
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5"/css/bootstrap.min.css>
    <link href="bootstrap.min.css" rel="stylesheet">
    <link href="bootstrap-reboot.min.css" rel="stylesheet">
    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet">

    <link rel="stylesheet" type="text/css" href="style.css">
    <link rel="stylesheet" type="text/css" href="bootstrap.css">
    <link rel="stylesheet" type="text/css" href="bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="bootstrap-reboot.min.css">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

        <form class="form-signin">

            <input type="text" id="inputEmail" class="form-control" placeholder="Username" required autofocus>
            <input type="password" id="inputPassword" class="form-control" placeholder="Password" required>

                    <input type="checkbox" value="remember-me"> Remember me

            <button class="btn btn-lg btn-primary btn-block btn-signin" type="submit" id="sendauth">Sign in</button>
        </form>

            Forgot the password?

Body:
Try with ajax:

$.ajax({
    type: 'POST',
    url: 'http://server.address:port/login',
    data: {
        'Username': 'yourUserName',
        'Password': 'yourPass'
    },
    success: function(msg){
        alert(msg);
    }
});


问:
How to compute the mean survival time
I'm using the survival library. After computing the Kaplan-Meier estimator of a survival function:

```<code>km = survfit(Surv(time, flag) ~ 1)
</code>```

I know how to compute percentiles:

```<code>quantile(km, probs = c(0.05,0.25,0.5,0.75,0.95))
</code>```

But, how do I compute the mean survival time?

答:
Calculate Mean Survival Time

The mean survival time will in general depend on what value is chosen for the maximum survival time. You can get the restricted mean survival time with print(km, print.rmean=TRUE). By default, this assumes that the longest survival time is equal to the longest survival time in the data. You can set this to a different value by adding an rmean argument (e.g., print(km, print.rmean=TRUE, rmean=250)).

Extract Value of Mean Survival Time and Store in an Object

In response to your comment: I initially figured one could extract the mean survival time by looking at the object returned by print(km, print.rmean=TRUE), but it turns out that print.survfit doesn't return a list object but just returns text to the console.

Instead, I looked through the code of print.survfit (you can see the code by typing getAnywhere(print.survfit) in the console) to see where the mean survival time is calculated. It turns out that a function called survmean takes care of this, but it's not an exported function, meaning R won't recognize the function when you try to run it like a "normal" function. So, to access the function, you need to run the code below (where you need to set rmean explicitly):

```<code>survival:::survmean(km, rmean=60)
</code>```

You'll see that the function returns a list where the first element is a matrix with several named values, including the mean and the standard error of the mean. So, to extract, for example, the mean survival time, you would do:

```<code>survival:::survmean(km, rmean=60)[[1]]["*rmean"]
</code>```

Details on How the Mean Survival Time is Calculated

The help for print.survfit provides details on the options and how the restricted mean is calculated:

```<code>?print.survfit
</code>```

The mean and its variance are based on a truncated estimator. That is,
if the last observation(s) is not a death, then the survival curve
estimate does not go to zero and the mean is undefined. There are four
possible approaches to resolve this, which are selected by the rmean
option. The first is to set the upper limit to a constant,
e.g.,rmean=365. In this case the reported mean would be the expected
number of days, out of the first 365, that would be experienced by
each group. This is useful if interest focuses on a fixed period.
Other options are "none" (no estimate), "common" and "individual". The
"common" option uses the maximum time for all curves in the object as
a common upper limit for the auc calculation. For the
"individual"options the mean is computed as the area under each curve,
over the range from 0 to the maximum observed time for that curve.
Since the end point is random, values for different curves are not
comparable and the printed standard errors are an underestimate as
they do not take into account this random variation. This option is
provided mainly for backwards compatability, as this estimate was the
default (only) one in earlier releases of the code. Note that SAS (as
of version 9.3) uses the integral up to the last event time of each
individual curve; we consider this the worst of the choices and do not
provide an option for that calculation.

Title: How to compute the mean survival time

Body:
I'm using the survival library. After computing the Kaplan-Meier estimator of a survival function:

km = survfit(Surv(time, flag) ~ 1)

I know how to compute percentiles:

quantile(km, probs = c(0.05,0.25,0.5,0.75,0.95))

But, how do I compute the mean survival time?

Body:
Calculate Mean Survival Time

The mean survival time will in general depend on what value is chosen for the maximum survival time. You can get the restricted mean survival time with print(km, print.rmean=TRUE). By default, this assumes that the longest survival time is equal to the longest survival time in the data. You can set this to a different value by adding an rmean argument (e.g., print(km, print.rmean=TRUE, rmean=250)).

Extract Value of Mean Survival Time and Store in an Object

In response to your comment: I initially figured one could extract the mean survival time by looking at the object returned by print(km, print.rmean=TRUE), but it turns out that print.survfit doesn't return a list object but just returns text to the console.

Instead, I looked through the code of print.survfit (you can see the code by typing getAnywhere(print.survfit) in the console) to see where the mean survival time is calculated. It turns out that a function called survmean takes care of this, but it's not an exported function, meaning R won't recognize the function when you try to run it like a "normal" function. So, to access the function, you need to run the code below (where you need to set rmean explicitly):

survival:::survmean(km, rmean=60)

You'll see that the function returns a list where the first element is a matrix with several named values, including the mean and the standard error of the mean. So, to extract, for example, the mean survival time, you would do:

survival:::survmean(km, rmean=60)[[1]]["*rmean"]

Details on How the Mean Survival Time is Calculated

The help for print.survfit provides details on the options and how the restricted mean is calculated:

?print.survfit

The mean and its variance are based on a truncated estimator. That is,
if the last observation(s) is not a death, then the survival curve
estimate does not go to zero and the mean is undefined. There are four
possible approaches to resolve this, which are selected by the rmean
option. The first is to set the upper limit to a constant,
e.g.,rmean=365. In this case the reported mean would be the expected
number of days, out of the first 365, that would be experienced by
each group. This is useful if interest focuses on a fixed period.
Other options are "none" (no estimate), "common" and "individual". The
"common" option uses the maximum time for all curves in the object as
a common upper limit for the auc calculation. For the
"individual"options the mean is computed as the area under each curve,
over the range from 0 to the maximum observed time for that curve.
Since the end point is random, values for different curves are not
comparable and the printed standard errors are an underestimate as
they do not take into account this random variation. This option is
provided mainly for backwards compatability, as this estimate was the
default (only) one in earlier releases of the code. Note that SAS (as
of version 9.3) uses the integral up to the last event time of each
individual curve; we consider this the worst of the choices and do not
provide an option for that calculation.

ContentLicense: CC BY-SA 4.0


问:
Can perf display raw sample counts?
I'd like perf to output raw sample counts rather than percentages.  This is useful for determining whether I've sped up a function I'm trying to optimize.

To be clear, I'd like to do something like

```<code>perf record ./a.out
perf report
</code>```

and see how many times perf sampled each function in a.out.

Shark can do this on Mac, as can (I believe) Xperf.  Is this possible on Linux with perf?

答: perf report (version 2.6.35.7) now supports the  -n flag, which does what I want.</p>

Title: Can perf display raw sample counts?

Body:
I'd like perf to output raw sample counts rather than percentages.  This is useful for determining whether I've sped up a function I'm trying to optimize.

To be clear, I'd like to do something like

perf record ./a.out
perf report

and see how many times perf sampled each function in a.out.

Shark can do this on Mac, as can (I believe) Xperf.  Is this possible on Linux with perf?


答:
Mysql manual has a complete section dedicated to this, called Type Conversion in Expression Evaluation.

When an operator is used with operands of different types, type conversion occurs to make the operands compatible. Some conversions occur implicitly. For example, MySQL automatically converts numbers to strings as necessary, and vice versa.

If you compare an int with a string, then both values are converted to floating point number and compared thus.

Title: How does mysql do multi-type comparison?

Body:
I was working on a project and due to a miscomprehension, we ended up comparing a stored int with a string in a MySql database. I ran a few test and it seems to work but I would like to know how MySql compares different datatypes.

Does it convert one to the other? If it does does it convert both to strings or to ints?


问:
Traversing and adding elements to a Data.Tree using Lenses in Haskell
I'm starting to use lenses and until now I've been unable to use them in a concrete part of a codebase I'm writing. My objective is to update a rose tree structure such as the one in Data.Tree by adding a new node inside one of the existing ones. To do so I thought that it would make sense to identify each node with a unique id, so it would look like that:

```<code>type MyTree = Tree Id
type Path = [Id]

addToTree :: MyTree -> MyTree -> Path -> MyTree
addToTree originalTree newNode path = undefined
</code>```

The function addToTree would have to traverse the originalTree by following the path of ids and add the newNode at that level, returning the whole updated tree. I haven't had problems to make a getter for that but I'm not being able to find an appropriate lens to perform the operation with.

That's what I've got until now:

```<code>import           Control.Lens
import           Data.Tree
import           Data.Tree.Lens

addToTree :: MyTree -> Path -> MyTree -> MyTree
addToTree tree path branch = tree & (traversalPath path) . branches %~ (branch:)

traversalPath :: (Foldable t, Applicative f, Contravariant f) => t Id -> (MyTree -> f MyTree) -> MyTree -> f MyTree
traversalPath = foldl (\acc id-> acc . childTraversal id) id

childTraversal :: (Indexable Int p, Applicative f) => Id -> p MyTree (f MyTree) -> MyTree -> f MyTree
childTraversal id = branches . traversed . withId id

withId :: (Choice p, Applicative f) => Id -> Optic' p f MyTree MyTree
withId id = filtered (\x -> rootLabel x == id)
</code>```

But it fails to compile with:

```<code>• No instance for (Contravariant Identity)
    arising from a use of ‘traversalPath’
• In the first argument of ‘(.)’, namely ‘(traversalPath path)’
  In the first argument of ‘(%~)’, namely
    ‘(traversalPath path) . branches’
  In the second argument of ‘(&)’, namely
    ‘(traversalPath path) . branches %~ (branch :)’
</code>```

Thanks!

答:
This is not specially elegant, but should do the trick:

```<code>import Control.Lens
import Data.Monoid (Endo(..)) -- A tidier idiom for 'foldr (.) id'.
import Data.List.NonEmpty (NonEmpty(..)) -- You don't want an empty path.
import qualified Data.List.NonEmpty as N
import Data.Tree
import Data.Tree.Lens -- That's where I got 'branches' from.

addToTree :: Eq a => NonEmpty a -> Tree a -> Tree a -> Tree a
addToTree path newNode oldTree = head $ over pathForests (newNode :) [oldTree]
    where
    pathForests = appEndo $ foldMap (Endo . goDown) path
    goDown x = traverse . filtered ((x ==) . rootLabel) . branches
</code>```

(In particular, I never like using head, even in cases like this one in which it can't possibly fail. Feel free to replace it with your favourite circumlocution.)

Demo:

```<code>GHCi> addToTree (1 :| []) (Node 2 []) (Node 1 [])
Node {rootLabel = 1, subForest = [Node {rootLabel = 2, subForest = []}]}
GHCi> addToTree (4 :| []) (Node 2 []) (Node 1 [])
Node {rootLabel = 1, subForest = []}
GHCi> addToTree (1 :| [5]) (Node 2 []) (Node 1 [Node 5 [], Node 6 []])
Node {rootLabel = 1, subForest = [Node {rootLabel = 5, subForest = [Node {rootLabel = 2, subForest = []}]},Node {rootLabel = 6, subForest = []}]}
GHCi> addToTree (1 :| [7]) (Node 2 []) (Node 1 [Node 5 [], Node 6 []])
Node {rootLabel = 1, subForest = [Node {rootLabel = 5, subForest = []},Node {rootLabel = 6, subForest = []}]}
GHCi> addToTree (1 :| [5,3]) (Node 2 []) (Node 1 [Node 5 [], Node 6 []])
Node {rootLabel = 1, subForest = [Node {rootLabel = 5, subForest = []},Node {rootLabel = 6, subForest = []}]}
</code>```

Do note that we are dealing with traversals, and not with lenses -- there is no guarantee or expectation that the target of the path exists or is unique.

Here is a more stylised variant, without head and using alaf to handle the Endo wrapping.

```<code>addToTree :: Eq a => NonEmpty a -> Tree a -> Tree a -> Tree a
addToTree (desiredRoot :| path) newNode oldTree@(Node x ts)
    | x == desiredRoot = Node x (over pathForests (newNode :) ts)
    | otherwise = oldTree
    where
    pathForests = alaf Endo foldMap goDown path
    goDown x = traverse . filtered ((x ==) . rootLabel) . branches
</code>```

Body:
I'm starting to use lenses and until now I've been unable to use them in a concrete part of a codebase I'm writing. My objective is to update a rose tree structure such as the one in Data.Tree by adding a new node inside one of the existing ones. To do so I thought that it would make sense to identify each node with a unique id, so it would look like that:

type MyTree = Tree Id
type Path = [Id]

addToTree :: MyTree -> MyTree -> Path -> MyTree
addToTree originalTree newNode path = undefined

The function addToTree would have to traverse the originalTree by following the path of ids and add the newNode at that level, returning the whole updated tree. I haven't had problems to make a getter for that but I'm not being able to find an appropriate lens to perform the operation with.

That's what I've got until now:

import           Control.Lens
import           Data.Tree
import           Data.Tree.Lens

addToTree :: MyTree -> Path -> MyTree -> MyTree
addToTree tree path branch = tree & (traversalPath path) . branches %~ (branch:)

traversalPath :: (Foldable t, Applicative f, Contravariant f) => t Id -> (MyTree -> f MyTree) -> MyTree -> f MyTree
traversalPath = foldl (\acc id-> acc . childTraversal id) id

childTraversal :: (Indexable Int p, Applicative f) => Id -> p MyTree (f MyTree) -> MyTree -> f MyTree
childTraversal id = branches . traversed . withId id

withId :: (Choice p, Applicative f) => Id -> Optic' p f MyTree MyTree
withId id = filtered (\x -> rootLabel x == id)

But it fails to compile with:

• No instance for (Contravariant Identity)
    arising from a use of ‘traversalPath’
• In the first argument of ‘(.)’, namely ‘(traversalPath path)’
  In the first argument of ‘(%~)’, namely
    ‘(traversalPath path) . branches’
  In the second argument of ‘(&)’, namely
    ‘(traversalPath path) . branches %~ (branch :)’

Thanks!

Body:
This is not specially elegant, but should do the trick:

import Control.Lens
import Data.Monoid (Endo(..)) -- A tidier idiom for 'foldr (.) id'.
import Data.List.NonEmpty (NonEmpty(..)) -- You don't want an empty path.
import qualified Data.List.NonEmpty as N
import Data.Tree
import Data.Tree.Lens -- That's where I got 'branches' from.

addToTree :: Eq a => NonEmpty a -> Tree a -> Tree a -> Tree a
addToTree path newNode oldTree = head $ over pathForests (newNode :) [oldTree]
    where
    pathForests = appEndo $ foldMap (Endo . goDown) path
    goDown x = traverse . filtered ((x ==) . rootLabel) . branches

(In particular, I never like using head, even in cases like this one in which it can't possibly fail. Feel free to replace it with your favourite circumlocution.)

Demo:

GHCi> addToTree (1 :| []) (Node 2 []) (Node 1 [])
Node {rootLabel = 1, subForest = [Node {rootLabel = 2, subForest = []}]}
GHCi> addToTree (4 :| []) (Node 2 []) (Node 1 [])
Node {rootLabel = 1, subForest = []}
GHCi> addToTree (1 :| [5]) (Node 2 []) (Node 1 [Node 5 [], Node 6 []])
Node {rootLabel = 1, subForest = [Node {rootLabel = 5, subForest = [Node {rootLabel = 2, subForest = []}]},Node {rootLabel = 6, subForest = []}]}
GHCi> addToTree (1 :| [7]) (Node 2 []) (Node 1 [Node 5 [], Node 6 []])
Node {rootLabel = 1, subForest = [Node {rootLabel = 5, subForest = []},Node {rootLabel = 6, subForest = []}]}
GHCi> addToTree (1 :| [5,3]) (Node 2 []) (Node 1 [Node 5 [], Node 6 []])
Node {rootLabel = 1, subForest = [Node {rootLabel = 5, subForest = []},Node {rootLabel = 6, subForest = []}]}

Do note that we are dealing with traversals, and not with lenses -- there is no guarantee or expectation that the target of the path exists or is unique.

Here is a more stylised variant, without head and using alaf to handle the Endo wrapping.

addToTree :: Eq a => NonEmpty a -> Tree a -> Tree a -> Tree a
addToTree (desiredRoot :| path) newNode oldTree@(Node x ts)
    | x == desiredRoot = Node x (over pathForests (newNode :) ts)
    | otherwise = oldTree
    where
    pathForests = alaf Endo foldMap goDown path
    goDown x = traverse . filtered ((x ==) . rootLabel) . branches


问:
Rendered image php slow loading in chrome
I am using the next code to render my images:

```<code>// 1. Check if image exists
$image = glob("public/images/$category/$id/$name.*");

// Image exists
if(count($image) === 1) {
    // 2. Get file extension
    $path_parts = pathinfo($image[0]);

    // 3. Add the content type to the header
    switch(strtolower($path_parts['extension']))
    {
        case "gif":
            header("Content-type: image/gif");
            break;
        case "jpg":
        case "jpeg":
            header("Content-type: image/jpeg");
            break;
        case "png":
            header("Content-type: image/png");
            break;
        case "bmp":
            header("Content-type: image/bmp");
            break;
        case "svg":
            header("Content-type: image/svg+xml");
            break;
        default:
            self::setNotFoundHeaders();
            break;
    }

    // 4. Set the rest of the Header information
    header("Expires: Mon, 1 Jan 2099 05:00:00 GMT");
    header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
    header("Cache-Control: no-store, no-cache, must-revalidate");
    header("Cache-Control: post-check=0, pre-check=0", false);
    header("Pragma: no-cache");
    // 5. Get the size for content length
    $size= filesize($image[0]);
    header("Content-Length: $size bytes");
    // 6. Output the file contents
    readfile($image[0]);
}
</code>```

The image loads perfectly in IE, Chrome and Firefox but while it takes 100 ms to load in IE and Firefox, it takes 5 seconds to load in Chrome. This is what the network tab of Chrome looks like:

Even if it takes 5 seconds to finish loading, the image is ready and visible at normal speed, in about 100 ms.

Also you can see in the image that the file type is "document" and not "image", idk why.

I have tried using different code to render the image but I got the same behavior:

```<code>$fp = fopen($image[0], 'rb');
fpassthru($fp);
</code>```

What am I doing wrong? Am I missing some headers?

Thank you for your time!

答:
There is nothing wrong in the code you posted except that the Content-Length header must specify only the number of bytes (without the word bytes).

```<code>header("Content-Length: $size");
</code>```

Even with that minor mistake however your code should run fine.

I have some code that render images, I tried it with your exact headers ("bytes" mistake included) and inspected the result in Chrome web tools. The images are loaded normally.

Said that I would try one more thing adding this code after readfile()

```<code>// Flush (if any) all the buffers
while( ob_get_level() > 0 ) { ob_end_flush(); }

// Ensure script execution terminates here
exit();
</code>```

If you still experience the problem I would consider the possibility that it's just a glitch in Chrome web tools. Expecially because you've noticed the image is actually loaded without delays.

Body:
I am using the next code to render my images:

// 1. Check if image exists
$image = glob("public/images/$category/$id/$name.*");

// Image exists
if(count($image) === 1) {
    // 2. Get file extension
    $path_parts = pathinfo($image[0]);

    // 3. Add the content type to the header
    switch(strtolower($path_parts['extension']))
    {
        case "gif":
            header("Content-type: image/gif");
            break;
        case "jpg":
        case "jpeg":
            header("Content-type: image/jpeg");
            break;
        case "png":
            header("Content-type: image/png");
            break;
        case "bmp":
            header("Content-type: image/bmp");
            break;
        case "svg":
            header("Content-type: image/svg+xml");
            break;
        default:
            self::setNotFoundHeaders();
            break;
    }

    // 4. Set the rest of the Header information
    header("Expires: Mon, 1 Jan 2099 05:00:00 GMT");
    header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
    header("Cache-Control: no-store, no-cache, must-revalidate");
    header("Cache-Control: post-check=0, pre-check=0", false);
    header("Pragma: no-cache");
    // 5. Get the size for content length
    $size= filesize($image[0]);
    header("Content-Length: $size bytes");
    // 6. Output the file contents
    readfile($image[0]);
}

The image loads perfectly in IE, Chrome and Firefox but while it takes 100 ms to load in IE and Firefox, it takes 5 seconds to load in Chrome. This is what the network tab of Chrome looks like:

Even if it takes 5 seconds to finish loading, the image is ready and visible at normal speed, in about 100 ms.

Also you can see in the image that the file type is "document" and not "image", idk why.

I have tried using different code to render the image but I got the same behavior:

$fp = fopen($image[0], 'rb');
fpassthru($fp);

What am I doing wrong? Am I missing some headers?

Thank you for your time!

Body:
There is nothing wrong in the code you posted except that the Content-Length header must specify only the number of bytes (without the word bytes).

header("Content-Length: $size");

Even with that minor mistake however your code should run fine.

I have some code that render images, I tried it with your exact headers ("bytes" mistake included) and inspected the result in Chrome web tools. The images are loaded normally.

Said that I would try one more thing adding this code after readfile()

// Flush (if any) all the buffers
while( ob_get_level() > 0 ) { ob_end_flush(); }

// Ensure script execution terminates here
exit();

If you still experience the problem I would consider the possibility that it's just a glitch in Chrome web tools. Expecially because you've noticed the image is actually loaded without delays.


问:
Python:How to make the sum of the values of a while loop store into a variable?
I'm just a beginner :P.
I'm doing a tutorial about while loops on Codeacademy "Click here!" ,
but I've gotten stuck on this part: Write a while loop which stores into "theSum" the sum of the first 10 positive integers (including 10).This is what it gives you to work with:

```<code>theSum = 0
num = 1
while num <= 10:
    print num
    num = num + 1
</code>```

It prints out the numbers 1 to 10 on seperate lines in the console. Can anyone explain to me how I can get it to store the sum of the values in the variable "mySum"? Anything I've tried so far hasn't worked for me. :(

EDIT:
Okay so I just tried this:

```<code>theSum = 0
num = 1
while num <= 10:
    num += 1
    mySum = num
    mySum = mySum + num

print mySum
</code>```

This gives me 22, why is that? Am I in anyway close? (Thanks for all the replies but I'll try again tomorrow.)

EDIT: Okay, I got it! Thank you for the help. :)

```<code>mySum = 0
num = 1
while num <= 10:
    mySum += num
    num += 1
print mySum
</code>```

答:
I also greatly struggled with this.

This was my solution but I got help from interactivepython.org (http://interactivepython.org/runestone/static/pip2/IndefiniteIteration/ThewhileStatement.html)

I couldn't figure out how to do this without the 'return' function.  See solution and explanation below:

```<code>def problem1_3(x):
    my_sum=0
    count = 1
    while count<=x:
        my_sum=my_sum+count
        count = count+1
    return my_sum
    print(my_sum)
</code>```

Lets assume you set x = 3
The way I believe python interprets this is as follows:
set my_sum = 0 and count = 1
1.  First iteration with the while loop: 1 <= 3 : True
so my_sum = 0+1
plus count increases by 1 and now count = 2
The 'Return my_sum' is key because it allows my_sum to circle back to the top of the loop as 1 now instead of 0.

Second iteration of the while loop: 2 <= 3 : True
so my_sum = 1+2 ; count again increases by 1 so now count = 3
Return my_sum again returns the new value of 3 for my_sum to the top of the loop

Third iteration of the while loop: 3 <= 3 : True
so my_sum = 3+3 ; count increases by 1 so now count = 4
Return my_sum again returns the new value of 6 for my_sum to the top of the loop

Fourth iteration of while loop never happens since 4 <=3 : False
Now the program prints my_sum which now is equal to 6.

However, I'd think there would be an easier way to do this. Is there a way for python to generate a list and then sum the values in the list?  For example, could I write a program called sumlist(n) where python listed the integers from 0 to n and then added them up?

Body:
I'm just a beginner :P.
I'm doing a tutorial about while loops on Codeacademy "Click here!" ,
but I've gotten stuck on this part: Write a while loop which stores into "theSum" the sum of the first 10 positive integers (including 10).This is what it gives you to work with:

theSum = 0
num = 1
while num <= 10:
    print num
    num = num + 1

It prints out the numbers 1 to 10 on seperate lines in the console. Can anyone explain to me how I can get it to store the sum of the values in the variable "mySum"? Anything I've tried so far hasn't worked for me. :(

EDIT:
Okay so I just tried this:

theSum = 0
num = 1
while num <= 10:
    num += 1
    mySum = num
    mySum = mySum + num

print mySum

This gives me 22, why is that? Am I in anyway close? (Thanks for all the replies but I'll try again tomorrow.)

EDIT: Okay, I got it! Thank you for the help. :)

mySum = 0
num = 1
while num <= 10:
    mySum += num
    num += 1
print mySum

Body:
I also greatly struggled with this.

This was my solution but I got help from interactivepython.org (http://interactivepython.org/runestone/static/pip2/IndefiniteIteration/ThewhileStatement.html)

I couldn't figure out how to do this without the 'return' function.  See solution and explanation below:

def problem1_3(x):
    my_sum=0
    count = 1
    while count<=x:
        my_sum=my_sum+count
        count = count+1
    return my_sum
    print(my_sum)

Lets assume you set x = 3
The way I believe python interprets this is as follows:
set my_sum = 0 and count = 1
1.  First iteration with the while loop: 1 <= 3 : True
so my_sum = 0+1
plus count increases by 1 and now count = 2
The 'Return my_sum' is key because it allows my_sum to circle back to the top of the loop as 1 now instead of 0.

Second iteration of the while loop: 2 <= 3 : True
so my_sum = 1+2 ; count again increases by 1 so now count = 3
Return my_sum again returns the new value of 3 for my_sum to the top of the loop

Third iteration of the while loop: 3 <= 3 : True
so my_sum = 3+3 ; count increases by 1 so now count = 4
Return my_sum again returns the new value of 6 for my_sum to the top of the loop

Fourth iteration of while loop never happens since 4 <=3 : False
Now the program prints my_sum which now is equal to 6.

However, I'd think there would be an easier way to do this. Is there a way for python to generate a list and then sum the values in the list?  For example, could I write a program called sumlist(n) where python listed the integers from 0 to n and then added them up?


问:
Node.js API to spawn off a call to another API
I created a Node.js API.
When this API gets called I return to the caller fairly quickly.  Which is good.

But now I also want API to call or launch an different API or function or something that will go off and run on it's own. Kind of like calling a child process with child.unref().  In fact, I would use child.spawn() but I don't see how to have spawn() call another API.  Maybe that alone would be my answer?

Of this other process, I don't care if it crashes or finishes without error.
 So it doesn't need to be attached to anything.  But if it does remain attached to the Node.js console then icing on the cake.

I'm still thinking about how to identify & what to do if the spawn somehow gets caught up in running a really long time.  But ready to cross that part of this yet.

Your thoughts on what I might be able to do?

答:
This is from a test API I built some time ago. Note I'm even passing a value into the script as a parameter.

```<code>router.put('/test', function (req, res, next) {
    var u = req.body.u;
    var cp = require('child_process');
    var c = cp.spawn('node', ['yourtest.js',  '"' + u + '"'], { detach: true });
    c.unref();
    res.sendStatus(200);

});
</code>```

The yourtest.js script can be just about anything you want it to be.  But I thought I would have enjoy learning more if I thought to first treat the script as a node.js console desktop app.  FIRST get your yourtest.js script to run without error by manually running/testing it from your console's command line node yourstest.js yourparamtervalue  THEN integrate it in to the child.spawn()

```<code>var u = process.argv[2];
console.log('f2u', u);

function f1() {
    console.log('f1-hello');
}

function f2() {
    console.log('f2-hello');
}
setTimeout(f2, 3000); // wait 3 second before execution f2().  I do this just for troubleshooting.  You can watch node.exe open and then close in TaskManager if node.exe is running long enough.

f1();
</code>```

Body:
This is from a test API I built some time ago. Note I'm even passing a value into the script as a parameter.

router.put('/test', function (req, res, next) {
    var u = req.body.u;
    var cp = require('child_process');
    var c = cp.spawn('node', ['yourtest.js',  '"' + u + '"'], { detach: true });
    c.unref();
    res.sendStatus(200);

});

The yourtest.js script can be just about anything you want it to be.  But I thought I would have enjoy learning more if I thought to first treat the script as a node.js console desktop app.  FIRST get your yourtest.js script to run without error by manually running/testing it from your console's command line node yourstest.js yourparamtervalue  THEN integrate it in to the child.spawn()

var u = process.argv[2];
console.log('f2u', u);

function f1() {
    console.log('f1-hello');
}

function f2() {
    console.log('f2-hello');
}
setTimeout(f2, 3000); // wait 3 second before execution f2().  I do this just for troubleshooting.  You can watch node.exe open and then close in TaskManager if node.exe is running long enough.

f1();


问:
bs4 max result length
I am currently writing a python script to scrape a news site with bs4 and I want to have the results on my 16x2 lcd screen. Is it possible to have something like a maximum length of soup.find_all results?

```<code>from bs4 import BeautifulSoup
from urllib.request import Request, urlopen
import re

r=urlopen("https://derstandard.at")
url = "https://derstandard.at"

soup = BeautifulSoup(r, "html.parser")

for a in soup.find_all("h2", limit=5):
    print(a.text)
</code>```

This is the current script

答:
I'm not sure what you're asking for but let me know if the following doesn't answer your question.

You're looking for a way to display the output (console) on your BIG screen/s.
Now while I'm not sure how to deal with this problem, you can probably use a specific IDE or change the mode of the console to be displayed on your big screen.

```<code>import os

os.system('mode con: cols=100 lines=40')
</code>```

You can, of course, change the units to display bigger or wider results.

It would be helpful if you could edit your question to be a little bit more detailed or place a comment that I'm on the right track so I can help you, Thank you.

Title: bs4 max result length

Body:
I am currently writing a python script to scrape a news site with bs4 and I want to have the results on my 16x2 lcd screen. Is it possible to have something like a maximum length of soup.find_all results?

from bs4 import BeautifulSoup
from urllib.request import Request, urlopen
import re

r=urlopen("https://derstandard.at")
url = "https://derstandard.at"

soup = BeautifulSoup(r, "html.parser")

for a in soup.find_all("h2", limit=5):
    print(a.text)

This is the current script

Body:
I'm not sure what you're asking for but let me know if the following doesn't answer your question.

You're looking for a way to display the output (console) on your BIG screen/s.
Now while I'm not sure how to deal with this problem, you can probably use a specific IDE or change the mode of the console to be displayed on your big screen.

import os

os.system('mode con: cols=100 lines=40')

You can, of course, change the units to display bigger or wider results.

It would be helpful if you could edit your question to be a little bit more detailed or place a comment that I'm on the right track so I can help you, Thank you.


问:
List with position of certain values of a matrix
I have a matrix with 1 and 0 in it. For example:

```<code>M1 = matrix(c(1, 0, 1, 0, 1, 0), nrow=2, ncol=3, byrow = TRUE)
row.names(M1) <- c(100, 101)
colnames(M1) <- c("A", "B", "C")
M1

    A B C
100 1 0 1
101 0 1 0
</code>```

Now I want to create a list of all the values=1 in the matrix with the following syntax:

```<code>"row name"."column name", value
</code>```

In this example the solution I'm looking for would be:

```<code>100.A, 1
100.C, 1
101.B, 1
</code>```

Body:
I have a matrix with 1 and 0 in it. For example:

M1 = matrix(c(1, 0, 1, 0, 1, 0), nrow=2, ncol=3, byrow = TRUE)
row.names(M1) <- c(100, 101)
colnames(M1) <- c("A", "B", "C")
M1

    A B C
100 1 0 1
101 0 1 0

Now I want to create a list of all the values=1 in the matrix with the following syntax:

"row name"."column name", value

In this example the solution I'm looking for would be:

100.A, 1
100.C, 1
101.B, 1

Body:
Try this:

x <- which(M1==1, arr.ind = TRUE)
data.frame(COL=paste0(rownames(M1)[x[,1]], ".", colnames(M1)[x[,2]], ", ", 1))

#       COL
#1 100.A, 1
#2 101.B, 1
#3 100.C, 1