问:
How to show the attributes of an object when clicking a button in Windows forms?
I want to show the attributes of an object when I click on a button in Windows Forms using c# and I don't know how to do it. Part of my code looks like this until now. I'm a beginner in c#.

```<code>class Pizza: ICloneable
    {
        private string nume;
        private int nrIngrediente;
        private string[] ingrediente;

        public Pizza()
        {
            nume = "Margherita";
            nrIngrediente = 2;
            ingrediente = new string[nrIngrediente];
            for (int i = 0; i < nrIngrediente; i++)
            {
                ingrediente[0] = "Sos rosii";
                ingrediente[1] = "Mozzarella";
            }
        }

        public Pizza(string den, int nri, string[] ing)
        {
            nume = den;
            nrIngrediente = nri;
            ingrediente = new string[nrIngrediente];
            for (int i = 0; i < nrIngrediente; i++)
                ingrediente[i] = ing[i];
        }

        public Pizza(Pizza p)
        {
            nume = p.nume;
            nrIngrediente = p.nrIngrediente;
            ingrediente = new string[nrIngrediente];
            for (int i = 0; i < nrIngrediente; i++)
                ingrediente[i] = p.ingrediente[i];
        }

        public string PizzaName
        {
            get { return nume; }
            set { nume = value; }
        }

 public int PizzaNrIng
        {
            get { return nrIngrediente; }
            set { nrIngrediente = value; }

//also, i don't know how to write the getter and setter for this one
      public string PizzaIngredients
        //{
        //    get
        //    {
        //        for(int i=0;i<nrIngrediente;i++)
        //            return ingrediente[i];
        //    }
        //    set { ingrediente = value; }
        //}
</code>```

And now, the form code is the following(note that i designed it already):

```<code> public partial class ListaPizza : Form
    {

        public ListaPizza()
        {
            InitializeComponent();
        }

        private void Margherita_Click(object sender, EventArgs e)
        {

            string[] ingrMargh = new string[2] { "Sos rosii", "Mozzarella" };
            Pizza Margherita = new Pizza("Margherita", 2, ingrMargh);

            //Show(Margherita);
//here i want the object created above to be shown in a messagebox when i click the button in the form but i don't know how

        }
    }
</code>```

Thank you!

答:
As for the getter - you should return an array of strings, not just a string:

```<code>public string[] PizzaIngredients
{
    get
    {
        ingrediente;
    }
    set
    {
        ingrediente = value;
    }
}
</code>```

As for the showing - just use MessageBox.Show():

```<code>MessageBox.Show(string.Format("{0} {1}", Margherita.Name, Margherita.nrIngrediente));
</code>```

Body:
I want to show the attributes of an object when I click on a button in Windows Forms using c# and I don't know how to do it. Part of my code looks like this until now. I'm a beginner in c#.

class Pizza: ICloneable
    {
        private string nume;
        private int nrIngrediente;
        private string[] ingrediente;

        public Pizza()
        {
            nume = "Margherita";
            nrIngrediente = 2;
            ingrediente = new string[nrIngrediente];
            for (int i = 0; i < nrIngrediente; i++)
            {
                ingrediente[0] = "Sos rosii";
                ingrediente[1] = "Mozzarella";
            }
        }

        public Pizza(string den, int nri, string[] ing)
        {
            nume = den;
            nrIngrediente = nri;
            ingrediente = new string[nrIngrediente];
            for (int i = 0; i < nrIngrediente; i++)
                ingrediente[i] = ing[i];
        }

        public Pizza(Pizza p)
        {
            nume = p.nume;
            nrIngrediente = p.nrIngrediente;
            ingrediente = new string[nrIngrediente];
            for (int i = 0; i < nrIngrediente; i++)
                ingrediente[i] = p.ingrediente[i];
        }

        public string PizzaName
        {
            get { return nume; }
            set { nume = value; }
        }

 public int PizzaNrIng
        {
            get { return nrIngrediente; }
            set { nrIngrediente = value; }

//also, i don't know how to write the getter and setter for this one
      public string PizzaIngredients
        //{
        //    get
        //    {
        //        for(int i=0;i<nrIngrediente;i++)
        //            return ingrediente[i];
        //    }
        //    set { ingrediente = value; }
        //}

And now, the form code is the following(note that i designed it already):

 public partial class ListaPizza : Form
    {

        public ListaPizza()
        {
            InitializeComponent();
        }

        private void Margherita_Click(object sender, EventArgs e)
        {

            string[] ingrMargh = new string[2] { "Sos rosii", "Mozzarella" };
            Pizza Margherita = new Pizza("Margherita", 2, ingrMargh);

            //Show(Margherita);
//here i want the object created above to be shown in a messagebox when i click the button in the form but i don't know how

        }
    }

Thank you!

Body:
As for the getter - you should return an array of strings, not just a string:

public string[] PizzaIngredients
{
    get
    {
        ingrediente;
    }
    set
    {
        ingrediente = value;
    }
}

As for the showing - just use MessageBox.Show():

MessageBox.Show(string.Format("{0} {1}", Margherita.Name, Margherita.nrIngrediente));


来源: stackexchange

问:
How to add a button in the heading next to php echo string
i am trying to add a button to the heading, but i cant figure that out.
It now looks this way:

The button should be at the light grey part at the right side of the "name". The code i am having now is:

```<code><div class="panel panel-default bg-white nopadding">
          <div class="panel-heading">
            <div class="col-md-4">
                <h3 class="text-uppercase text-faded">
                <?php echo $info['c_name'];?>
                </h3>
            </div>
            <div class="col-md-4">
                <div class="input-group">
                    <div id="addcinfo" class="btn btn-success" name="search1">Redigera</div>
                </div>
            </div>
          </div>
        </div>
</code>```

What do i am doing wrong?

The webpage is: http://109.74.0.128/~sarath/admin
username: Jonathan@inkhousemedia.se
pw: John@123

Go on "Kund" and search for saurav and you will see the error

答:
Add button class to your heading tag</p>

```<code><h1 class="btn btn-primary">Heading</h1>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i am trying to add a button to the heading, but i cant figure that out.
It now looks this way:

The button should be at the light grey part at the right side of the "name". The code i am having now is:

                <?php echo $info['c_name'];?>

Redigera

What do i am doing wrong?

The webpage is: http://109.74.0.128/~sarath/admin
username: Jonathan@inkhousemedia.se
pw: John@123

Go on "Kund" and search for saurav and you will see the error

Body:
Add button class to your heading tag

<h1 class="btn btn-primary">Heading</h1>


问:
How come I need to remove the current item in my listview before adding another one?
So im trying something new..
I added a global ListViewItem at the top of the code so I can easily add new subitems to the list whenever I see it fits.

So to try this new method out I made a simple list view and a button to add the current time.
When I click it once it works great but if i try clicking add again it throws me this error.

System.ArgumentException: 'Cannot add or insert the item '11:24' in
  more than one place. You must first remove it from its current
  location or clone it.'

is there a way I can get past this without removing or cloning it?

```<code>using System;
using System.Windows.Forms;

namespace Listviews
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        ListViewItem lvi = new ListViewItem();

        private void btnAdd_Click(object sender, EventArgs e)
        {
            string time = DateTime.Now.ToString("HH:mm");
            lvi.Text = time;
            listView1.Items.Add(lvi);
        }
    }
}
</code>```

答:
You are adding the same item again and again (a different text don't means it is another item). The Add method of ListView has an overload that accepts a string. This way a new listviewitem will be automatically created.

```<code>namespace Listviews
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        // Not needed
        //ListViewItem lvi = new ListViewItem();

        private void btnAdd_Click(object sender, EventArgs e)
        {
            string time = DateTime.Now.ToString("HH:mm");
            // Just add the time directly as a string
            listView1.Items.Add(time);
        }
    }
}
</code>```

Alternatively check the first comment under your question. But as long as you don't want to modify the items or store them externally, you wouldn't need to create a listViewItem.

Body:
So im trying something new..
I added a global ListViewItem at the top of the code so I can easily add new subitems to the list whenever I see it fits.

So to try this new method out I made a simple list view and a button to add the current time.
When I click it once it works great but if i try clicking add again it throws me this error.

System.ArgumentException: 'Cannot add or insert the item '11:24' in
  more than one place. You must first remove it from its current
  location or clone it.'

is there a way I can get past this without removing or cloning it?

using System;
using System.Windows.Forms;

namespace Listviews
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        ListViewItem lvi = new ListViewItem();

        private void btnAdd_Click(object sender, EventArgs e)
        {
            string time = DateTime.Now.ToString("HH:mm");
            lvi.Text = time;
            listView1.Items.Add(lvi);
        }
    }
}

Body:
You are adding the same item again and again (a different text don't means it is another item). The Add method of ListView has an overload that accepts a string. This way a new listviewitem will be automatically created.

namespace Listviews
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        // Not needed
        //ListViewItem lvi = new ListViewItem();

        private void btnAdd_Click(object sender, EventArgs e)
        {
            string time = DateTime.Now.ToString("HH:mm");
            // Just add the time directly as a string
            listView1.Items.Add(time);
        }
    }
}

Alternatively check the first comment under your question. But as long as you don't want to modify the items or store them externally, you wouldn't need to create a listViewItem.


问:
Why do I get a Keras LSTM RNN input_shape error?
I keep getting an input_shape error from the following code.

```<code>from keras.models import Sequential
from keras.layers.core import Dense, Activation, Dropout
from keras.layers.recurrent import LSTM

def _load_data(data):
    """
    data should be pd.DataFrame()
    """
    n_prev = 10
    docX, docY = [], []
    for i in range(len(data)-n_prev):
        docX.append(data.iloc[i:i+n_prev].as_matrix())
        docY.append(data.iloc[i+n_prev].as_matrix())
    if not docX:
        pass
    else:
        alsX = np.array(docX)
        alsY = np.array(docY)
        return alsX, alsY

X, y = _load_data(dframe)
poi = int(len(X) * .8)
X_train = X[:poi]
X_test = X[poi:]
y_train = y[:poi]
y_test = y[poi:]

input_dim = 3
</code>```

All of the above runs smoothly. This is where it goes wrong.

```<code>in_out_neurons = 2
hidden_neurons = 300
model = Sequential()
#model.add(Masking(mask_value=0, input_shape=(input_dim,)))
model.add(LSTM(in_out_neurons, hidden_neurons, return_sequences=False, input_shape=(len(full_data),)))
model.add(Dense(hidden_neurons, in_out_neurons))
model.add(Activation("linear"))
model.compile(loss="mean_squared_error", optimizer="rmsprop")
model.fit(X_train, y_train, nb_epoch=10, validation_split=0.05)
</code>```

It returns this error.

```<code>Exception: Invalid input shape - Layer expects input ndim=3, was provided with input shape (None, 10320)
</code>```

When I check the website it says to specify a tuple "(e.g. (100,) for 100-dimensional inputs)."

That being said, my data set consists of one column with a length of 10320. I assume that that means that I should be putting (10320,) in as the input_shape, but I get the error anyways. Does anyone have a solution?

答:
Some more information: when using RNN (like LSTM) with sequences of variable length you have to take of the format of your data.

When you group sequences in order to pass it to the fit method, keras will try to build a matrix of samples, which implies that all input sequences must have the same size, otherwise you won't have a matrix of the correct dimension.

There several possible solutions:

train your network using samples one by one (using fit_generator for example)

pad all your sequences so they have the same size

group sequences by size (eventually padding them) and train your network group by group (again using generator based fit)

The third solution corresponds to the most common strategy with variable size. And if you pad sequences (second or third solution) you may want to add a masking layer as input.

If you're not sure, try to print the shape of your data (using the shape attribute of the numpy array.)

You may need to look at: https://keras.io/preprocessing/sequence/ (pad_sequences) and https://keras.io/layers/core/#masking

Body:
I keep getting an input_shape error from the following code.

from keras.models import Sequential
from keras.layers.core import Dense, Activation, Dropout
from keras.layers.recurrent import LSTM

def _load_data(data):
    """
    data should be pd.DataFrame()
    """
    n_prev = 10
    docX, docY = [], []
    for i in range(len(data)-n_prev):
        docX.append(data.iloc[i:i+n_prev].as_matrix())
        docY.append(data.iloc[i+n_prev].as_matrix())
    if not docX:
        pass
    else:
        alsX = np.array(docX)
        alsY = np.array(docY)
        return alsX, alsY

X, y = _load_data(dframe)
poi = int(len(X) * .8)
X_train = X[:poi]
X_test = X[poi:]
y_train = y[:poi]
y_test = y[poi:]

input_dim = 3

All of the above runs smoothly. This is where it goes wrong.

in_out_neurons = 2
hidden_neurons = 300
model = Sequential()
#model.add(Masking(mask_value=0, input_shape=(input_dim,)))
model.add(LSTM(in_out_neurons, hidden_neurons, return_sequences=False, input_shape=(len(full_data),)))
model.add(Dense(hidden_neurons, in_out_neurons))
model.add(Activation("linear"))
model.compile(loss="mean_squared_error", optimizer="rmsprop")
model.fit(X_train, y_train, nb_epoch=10, validation_split=0.05)

It returns this error.

Exception: Invalid input shape - Layer expects input ndim=3, was provided with input shape (None, 10320)

When I check the website it says to specify a tuple "(e.g. (100,) for 100-dimensional inputs)."

That being said, my data set consists of one column with a length of 10320. I assume that that means that I should be putting (10320,) in as the input_shape, but I get the error anyways. Does anyone have a solution?


问:
How to log container in docker swarm mode
Is there a way to log the containers which are created with the docker service create in docker swarm mode?

答:
Finally that feature has been implemented in docker 17.03. You can get the logs of a service running on different/multiple nodes with this command:

```<code>docker service logs -f {NAME_OF_THE_SERVICE}
</code>```

You can get the name of the service with:

```<code>docker service ls
</code>```

Note that this is an experimental feature (not production ready) and in order to use it you must enable the experimental mode:

Update: docker logs service is now a standard feature of docker >= 17.06.
https://docs.docker.com/engine/reference/commandline/service_logs/

Body:
Finally that feature has been implemented in docker 17.03. You can get the logs of a service running on different/multiple nodes with this command:

docker service logs -f {NAME_OF_THE_SERVICE}

You can get the name of the service with:

docker service ls

Note that this is an experimental feature (not production ready) and in order to use it you must enable the experimental mode:

Update: docker logs service is now a standard feature of docker >= 17.06.
https://docs.docker.com/engine/reference/commandline/service_logs/

ContentLicense: CC BY-SA 4.0


问:
How do I use Zigbee to communicate to a laptop?
What I have in mind is having a number of sensors (temperature, accelerometer, sound level meter) that are controlled by a micro controller. What I want to do is take this information and transmit it wireless to a laptop that will take this information and put it on to a web server using Zigbee. I don't know where to start.</p>

答:
We also provide wireless modules that can be used for serial data transmission. They can be found at www.starmanelectric.com Our modules are very similar to the xbee, but more plug and play. They can be a great for going wireless for the first time. Our devices are designed to function like a "wireless cable" so if you're used to using wires then you'll be up and running in no time at all. We also have circuit examples for transmitting to a laptop serial port or USB. Any micro-controller will be fine for this application, as long as it has a serial port and a few ADCs to sample your data. Our modules also provide simple analog in/out which can run in parallel to the serial. If you want to compare to other systems, I would google "wireless serial modules"

Regards,

Michael

Starman Electric

ContentLicense: CC BY-SA 2.5


问:
Using Android Renderscript v8 Support Library causes link errors with other shared libraries
I'm trying to use the v8 Renderscript support library, from SDK Build Tools 22.0.0.

I'm using gradle to build, and I've included the lines

```<code>defaultConfig {
    renderscriptTargetApi 21
    renderscriptSupportModeEnabled true
}
</code>```

Importing and using the library seems fine, but when I run my app, it chokes trying to load another shared library, giving an UnsatisfiedLinkError.  If I make no other changes except removing the renderscript stuff, there's no linkage problem.

Is there anyway around this?  I'm using the SDK tools 22.0.0, gradle 2.2.1, Android Gradle plugin 1.1.0 and Android Studio 1.1.0.

答:
What happened to me was that when I was running on a 64bit device the PathClassLoader found the renderscript library in a 64bit version and thus tried to load 64bit versions of all other libraries included in the project. You can't run mixed 64 and 32bit. But since some of the libraries didn't exist in 64bit versions the PathClassLoader couldn't find them, hence the UnsatisfiedLinkError. The solution that worked for me was to exclude the 64bit versions of the renderscript library.

See this great article to see how its done.
Mixing 32- and 64-bit Dependencies in Android

This Stackoverflow post suggests a somewhat simpler solution

Body:
I'm trying to use the v8 Renderscript support library, from SDK Build Tools 22.0.0.

I'm using gradle to build, and I've included the lines

defaultConfig {
    renderscriptTargetApi 21
    renderscriptSupportModeEnabled true
}

Importing and using the library seems fine, but when I run my app, it chokes trying to load another shared library, giving an UnsatisfiedLinkError.  If I make no other changes except removing the renderscript stuff, there's no linkage problem.

Is there anyway around this?  I'm using the SDK tools 22.0.0, gradle 2.2.1, Android Gradle plugin 1.1.0 and Android Studio 1.1.0.


问:
DNS Records Redirect www to non-www
I'm using Namecheap Domains and Vultr Hosting.

I'm trying to redirect DNS www to non-www.

www.example.com to example.com

I contacted Vultr and asked how to do this with their DNS Manager, they said they would not help as it is self-managed. So I contacted Namecheap, they said they would not help becuase they don't have access to Vultr's DNS Manager, would not tell me if the records I showed them are correct, and I would need to contact Vultr. So I am in an endless support loop.

Vultr DNS Manager

I followed this answer on how to set up a CNAME to redirect to non-www.

```<code>Type   | Name | Data         | Seconds
--------------------------------------
A      |      | ipv4 address | 300
AAAA   |      | ipv6 address | 300
CNAME  | .    | example.com  | 300
CNAME  | www  | example.com  | 300
</code>```

After waiting all night for it to propgate, the www can still be visited and does not redirect.

It does not allow me to make another A record, only CNAME. It says:

```<code>Unable to add record: A CNAME record is not allowed to coexist with any other data.
</code>```

NGINX

I followed this guide and tried redirecting it with sites-available config. Http and Https work, but www does not redirect to non-www.

```<code>server {
    # Redirect http to https
    listen 80;
    return 301 https://$host$request_uri;
}

server {
    # Redirect www to non-www
    server_name www.example.com;
    return 301 $scheme://example.com$request_uri;
}

server {
    listen 443 ssl default_server;

    ssl on;
    ssl_certificate /etc/nginx/ssl/cert_chain.crt;
    ssl_certificate_key /etc/nginx/ssl/example_com.key;
    ssl_protocols  TLSv1.1 TLSv1.2;

    server_name example.com;
    ...
</code>```

答:
DNS cannot redirect your www site to non-www. The only purpose of DNS is to point both www and non-www to your server's IP address using A, AAAA or CNAME records (it makes little difference). The nginx configuration is responsible for performing the redirect from www to non-www.

Your second server block is intended to redirect from www to non-www, but currently only handles http connections (on port 80).

You can move the default server and use that to redirect everything to the intended domain name. For example:

```<code>ssl_certificate /etc/nginx/ssl/cert_chain.crt;
ssl_certificate_key /etc/nginx/ssl/example_com.key;

server {
    listen 80 default_server;
    listen 443 ssl default_server;
    return 301 https://example.com$request_uri;
}

server {
    listen 443 ssl;
    server_name example.com;
    ...
}
</code>```

Assuming that you have a common certificate for both the www and non-www domain names, you can move the ssl_ directives into the outer block and allow them to be inherited into both server blocks (as shown above).

See this document for more.

Title: DNS Records Redirect www to non-www

Body:
I'm using Namecheap Domains and Vultr Hosting.

I'm trying to redirect DNS www to non-www.

www.example.com to example.com

I contacted Vultr and asked how to do this with their DNS Manager, they said they would not help as it is self-managed. So I contacted Namecheap, they said they would not help becuase they don't have access to Vultr's DNS Manager, would not tell me if the records I showed them are correct, and I would need to contact Vultr. So I am in an endless support loop.

Vultr DNS Manager

I followed this answer on how to set up a CNAME to redirect to non-www.

Type   | Name | Data         | Seconds
--------------------------------------
A      |      | ipv4 address | 300
AAAA   |      | ipv6 address | 300
CNAME  | .    | example.com  | 300
CNAME  | www  | example.com  | 300

After waiting all night for it to propgate, the www can still be visited and does not redirect.

It does not allow me to make another A record, only CNAME. It says:

Unable to add record: A CNAME record is not allowed to coexist with any other data.

NGINX

I followed this guide and tried redirecting it with sites-available config. Http and Https work, but www does not redirect to non-www.

server {
    # Redirect http to https
    listen 80;
    return 301 https://$host$request_uri;
}

server {
    # Redirect www to non-www
    server_name www.example.com;
    return 301 $scheme://example.com$request_uri;
}

server {
    listen 443 ssl default_server;

    ssl on;
    ssl_certificate /etc/nginx/ssl/cert_chain.crt;
    ssl_certificate_key /etc/nginx/ssl/example_com.key;
    ssl_protocols  TLSv1.1 TLSv1.2;

    server_name example.com;
    ...

Body:
DNS cannot redirect your www site to non-www. The only purpose of DNS is to point both www and non-www to your server's IP address using A, AAAA or CNAME records (it makes little difference). The nginx configuration is responsible for performing the redirect from www to non-www.

Your second server block is intended to redirect from www to non-www, but currently only handles http connections (on port 80).

You can move the default server and use that to redirect everything to the intended domain name. For example:

ssl_certificate /etc/nginx/ssl/cert_chain.crt;
ssl_certificate_key /etc/nginx/ssl/example_com.key;

server {
    listen 80 default_server;
    listen 443 ssl default_server;
    return 301 https://example.com$request_uri;
}

server {
    listen 443 ssl;
    server_name example.com;
    ...
}

Assuming that you have a common certificate for both the www and non-www domain names, you can move the ssl_ directives into the outer block and allow them to be inherited into both server blocks (as shown above).

See this document for more.


答:
Several points to make:

geom_bar(stat = 'identity') is now replaced by geom_col()

You should not change the y aesthetic

Use the position argument with position_stack(vjust = 0.5)

Code:

```<code>library(ggplot2)
ggplot(df, aes(x = variable, y = percentage, fill = score)) +
    geom_col(position = 'stack')+
    geom_text(aes(label = percentage2),
              position = position_stack(vjust = .5),
              color='grey25',
              size=2) +
    facet_wrap(~ group,ncol=2) +
    coord_flip()
</code>```

Title: How to reverse order of stacked bars in ggplot2?

Body:
I have this data frame:

df <- structure(list(variable = c("var1", "var1", "var1", "var1", "var2",
                            "var2", "var2", "var2", "var3", "var3", "var3", "var3", "var1",
                            "var1", "var1", "var1", "var2", "var2", "var2", "var2", "var3",
                            "var3", "var3"), percentage = c(12.565445026178, 18.848167539267,
                                                            42.4083769633508, 26.1780104712042, 3.57142857142857, 11.2244897959184,
                                                            45.9183673469388, 39.2857142857143, 4.59183673469388, 10.2040816326531,
                                                            57.1428571428571, 28.0612244897959, 3.03030303030303, 12.1212121212121,
                                                            39.3939393939394, 45.4545454545455, 2.94117647058824, 5.88235294117647,
                                                            38.2352941176471, 52.9411764705882, 17.6470588235294, 29.4117647058824,
                                                            52.9411764705882), score = structure(c(1L, 2L, 3L, 4L, 1L, 2L,
                                                                                3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 2L, 3L,
                                                                                4L), .Label = c("1", "2", "3", "4"), class = "factor"), group = c("group1",
                                                                                "group1", "group1", "group1", "group1", "group1", "group1", "group1",
                                                                                "group1", "group1", "group1", "group1", "group2", "group2", "group2",
                                                                                "group2", "group2", "group2", "group2", "group2", "group2", "group2",
                                                                                "group2"), label = c(6.282722513089, 21.9895287958115, 52.6178010471204,
                                                                                86.9109947643979, 1.78571428571429, 9.18367346938776, 37.7551020408163,
                                                                                80.3571428571429, 2.29591836734694, 9.69387755102041, 43.3673469387755,
                                                                                85.969387755102, 1.51515151515152, 9.09090909090909, 34.8484848484848,
                                                                                77.2727272727273, 1.47058823529412, 5.88235294117647, 27.9411764705882,
                                                                                73.5294117647059, 8.82352941176471, 32.3529411764706, 73.5294117647059
                                                                                ), percentage2 = c("13%", "19%", "42%", "26%", "4%", "11%", "46%",
                                                                                "39%", "5%", "10%", "57%", "28%", "3%", "12%", "39%", "45%",
                                                                                "3%", "6%", "38%", "53%", "18%", "29%", "53%")), .Names = c("variable",
                                                                                "percentage", "score", "group", "label", "percentage2"), row.names = c(NA,
                                                                                -23L), class = "data.frame")

Now I try to make a faceted stacked bar chart with this code:

ggplot(df, aes(x = variable, y = percentage, fill = score)) +
  geom_bar(stat = 'identity')+
  geom_text(aes(y=label,label=percentage2), color='grey25', size=2) +
  facet_wrap(~ group,ncol=2)+
  coord_flip()

As you can see, the labels are not on the right spots in the bars. I need a reverse order of the bars. I know it sounds a bit like a duplicate question, like the one here, but when I try that solution I get this error:

Warning: Ignoring unknown aesthetics: order

Does anyone know how to solve this problem?

Body:
Several points to make:

geom_bar(stat = 'identity') is now replaced by geom_col()

You should not change the y aesthetic

Use the position argument with position_stack(vjust = 0.5)

Code:

library(ggplot2)
ggplot(df, aes(x = variable, y = percentage, fill = score)) +
    geom_col(position = 'stack')+
    geom_text(aes(label = percentage2),
              position = position_stack(vjust = .5),
              color='grey25',
              size=2) +
    facet_wrap(~ group,ncol=2) +
    coord_flip()


问:
Java derivating expression to expression and equations
I am trying to solve 2 problems.
I am doing app which should solve math problems.

I have expression parser based on grammar and AST but the main problem is that I need to create a derivate expression from expressions with unknown variable here is the example.

function :  (x1)^2+4(x2)^2-2x1-4x2

```<code>x1 = 5+α
x2 = 2
</code>```

I need derivate (5+α)^2+4(2)^2-2*(5+α)-4*2  === 2*(5+α)+8 => as String result

and then from 2*(5+α)+8 count α =?

答:
Thank you but i can t use symja . It has to be hand writen.

Still have troubles to make it .

Problem is that my AST after parsing is returning value so i need put expression with numbers only but i have to use variables witch i don t know :

like : -(30*x1+20*x2)+3/5*(3*x1^2+2*x2^2+(x1+x2)^2).

x1  = 2 , x2 = 2+a

Solution is derivative expresion and from expresion count a

Body:
I am trying to solve 2 problems.
I am doing app which should solve math problems.

I have expression parser based on grammar and AST but the main problem is that I need to create a derivate expression from expressions with unknown variable here is the example.

function :  (x1)^2+4(x2)^2-2x1-4x2

x1 = 5+α
x2 = 2

I need derivate (5+α)^2+4(2)^2-2*(5+α)-4*2  === 2*(5+α)+8 => as String result

and then from 2*(5+α)+8 count α =?


问:
How to perform 'OR' operation between several where conditions in LINQ
I am using  an IQueryable to build my query.

```<code> IQueryable<PropertyPosts> posts = context.PropertyPosts;
</code>```

After that based on several conditions I am appending Where clause into my query,

```<code> if (item.ApartmentCondo == 1)
 {
    posts= posts.Where(x => x.name == item.name &&
                            x.PropertyType == PropertyType.ApartmentCondo );

 }
 if (item.House == 1)
 {
  posts= posts.Where(x => x.name == item.name &&
                            x.PropertyType == PropertyType.House );

 }
</code>```

Note: There are several other where conditions also.

After that when I perform the following query,

```<code> List<PropertyPosts> posts2 = posts.ToList();
</code>```

All the above where conditions will be 'AND'ed.

But instead I need the Where conditions to be 'OR'ed.

Which means I need a way to append several Where conditions, but all these conditions should be  performing 'OR' condition between them.

How can I achieve this? Is there an alternative way rather than using 'Where'?

答:
Sorry for a new answer, but I have too little rep to comment.

The True/False works but are a little confusing and also generates multiple starting points. I've modified the code and removed the True<T> and False<T> methods and made a new overload method for Create<T>.

public static class PredicateBuilder
{
    public const bool TreatEntireExpressionAsAnd = true;
    public const bool TreatEntireExpressionAsOr = false;

    public static Expression<Func<T, bool>> Create<T>(bool value = TreatEntireExpressionAsAnd) { return param => value; }
    ...
```

Body:
I am using  an IQueryable to build my query.

 IQueryable<PropertyPosts> posts = context.PropertyPosts;

After that based on several conditions I am appending Where clause into my query,

 if (item.ApartmentCondo == 1)
 {
    posts= posts.Where(x => x.name == item.name &&
                            x.PropertyType == PropertyType.ApartmentCondo );

 }
 if (item.House == 1)
 {
  posts= posts.Where(x => x.name == item.name &&
                            x.PropertyType == PropertyType.House );

 }

Note: There are several other where conditions also.

After that when I perform the following query,

 List<PropertyPosts> posts2 = posts.ToList();

All the above where conditions will be 'AND'ed.

But instead I need the Where conditions to be 'OR'ed.

Which means I need a way to append several Where conditions, but all these conditions should be  performing 'OR' condition between them.

How can I achieve this? Is there an alternative way rather than using 'Where'?


问:
SQL Report Builder: Return only date for available parameter values
I have a SQL Server report which prompts for a import date. Later I pass this date to a procedure to get the data (dbo.spGetData). My procedure to get the available import dates looks like this:

```<code>ALTER PROCEDURE dbo.spGetImportDates
AS
BEGIN
    SELECT CONVERT(DATE, i.ImportDate) ImportDate
    FROM dbo.Import i
    ORDER BY i.ImportDate DESC
END
</code>```

In the report I've added this SP as a new dataset and selected it as "Available Values" for the Date/Time parameter @importDate to get a dropdown. So far, so good. The problem is that the time is also included in the result set when I leave it like this:

```<code>+---------------------+
| ImportDate          |
+---------------------+
| 29.03.2017 00:00:00 |
| 25.03.2017 00:00:00 |
| ...                 |
+---------------------+
</code>```

I couldn't find any option to change the format of the parameter prompt. I even tried to use the SELECT query directly in the query designer of the dataset but I get the same results.

Do I really have to use it as text parameter and then reconvert it to DATE in the procedure dbo.spGetData or is there any other solution?

答:
```<code>ALTER PROCEDURE dbo.spGetImportDates
AS
BEGIN
    SELECT CAST(CONVERT(DATE, i.ImportDate) AS NVARCHAR(10)) AS ImportDate
    FROM dbo.Import i
    ORDER BY i.ImportDate DESC
END
</code>```

You can get only the first 10 characters and then convert it to varchar

Body:
I have a SQL Server report which prompts for a import date. Later I pass this date to a procedure to get the data (dbo.spGetData). My procedure to get the available import dates looks like this:

ALTER PROCEDURE dbo.spGetImportDates
AS
BEGIN
    SELECT CONVERT(DATE, i.ImportDate) ImportDate
    FROM dbo.Import i
    ORDER BY i.ImportDate DESC
END

In the report I've added this SP as a new dataset and selected it as "Available Values" for the Date/Time parameter @importDate to get a dropdown. So far, so good. The problem is that the time is also included in the result set when I leave it like this:

+---------------------+
| ImportDate          |
+---------------------+
| 29.03.2017 00:00:00 |
| 25.03.2017 00:00:00 |
| ...                 |
+---------------------+

I couldn't find any option to change the format of the parameter prompt. I even tried to use the SELECT query directly in the query designer of the dataset but I get the same results.

Do I really have to use it as text parameter and then reconvert it to DATE in the procedure dbo.spGetData or is there any other solution?

Body:
ALTER PROCEDURE dbo.spGetImportDates
AS
BEGIN
    SELECT CAST(CONVERT(DATE, i.ImportDate) AS NVARCHAR(10)) AS ImportDate
    FROM dbo.Import i
    ORDER BY i.ImportDate DESC
END

You can get only the first 10 characters and then convert it to varchar


问:
Post request from angular2 to backend
I try to send request from frontend(angular2) to backend(ruby, sinatra).
Now, both of servers is working on one computer(angular on localhost:3001, sinatra on localhost:9292)

I use auth example(http://embed.plnkr.co/TIPmK3/?show=preview), and want to send user data to sinatra.

I see interesting string in app/_services/authentication.service.ts:

```<code>return this.http.post('/api/authenticate', JSON.stringify({ username: username, password: password }))
            .map((response: Response) => {...}
</code>```

But if replace '/api/authenticate' on http://localhost:9292/login nothing to happen. Request not sended, no errors. Only loading.

Can anyone to help me?

答:
Will you please provide more detail ?

But as per your question :
Most of the case the issue will be "Cross-Origin Request" ,

So please check if you set headers for that or not like,

I am using Angular in frontend (localhost:3000) and Node(192.168.2.117:4000) in backend ,
we were facing the same issue so we have set headers in node

```<code>   res.setHeader('Access-Control-Allow-Origin','*');
   res.setHeader('content-type','application/json');
   res.setHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Token, Timestamp, X-Requested-With, Language-Code");
</code>```

After that , it's working like charm.

Title: Post request from angular2 to backend

Body:
I try to send request from frontend(angular2) to backend(ruby, sinatra).
Now, both of servers is working on one computer(angular on localhost:3001, sinatra on localhost:9292)

I use auth example(http://embed.plnkr.co/TIPmK3/?show=preview), and want to send user data to sinatra.

I see interesting string in app/_services/authentication.service.ts:

return this.http.post('/api/authenticate', JSON.stringify({ username: username, password: password }))
            .map((response: Response) => {...}

But if replace '/api/authenticate' on http://localhost:9292/login nothing to happen. Request not sended, no errors. Only loading.

Can anyone to help me?

Body:
Will you please provide more detail ?

But as per your question :
Most of the case the issue will be "Cross-Origin Request" ,

So please check if you set headers for that or not like,

I am using Angular in frontend (localhost:3000) and Node(192.168.2.117:4000) in backend ,
we were facing the same issue so we have set headers in node

   res.setHeader('Access-Control-Allow-Origin','*');
   res.setHeader('content-type','application/json');
   res.setHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Token, Timestamp, X-Requested-With, Language-Code");

After that , it's working like charm.


问:
C++ Line into Vector
Wow I've been all over the place with questions today and I apologize if they seem to overlap, but for every question comes another question...Since one thing wont work......but I should use something else......etc.

Anyways, I have a text file:

```<code>6
3.0 2.5 -1.5 0.0 1.7 4.0
6 10
</code>```

6 is the Number of "floats" in the second line (the 3.0,2.5 etc...)
3.0,2.5,-1.5 are all a series of floats.
6 and 10 are just 2 integers.

I have a Vector

```<code>std::vector<double> numbers;
</code>```

All i need to do, is get the Second line put into numbers.
So right now I have

```<code>ifstream myfile (filename.c_str());
</code>```

I can simply just do a myfile>> to get the first value (6)
but how would I go about putting the second line in my vector? Remember I ONLY know how big line 2 is, by reading in the first line (the 6 in this case).

Also the last 2 numbers aren't supposed to be in this vector, but two seperate values.
Which i can just do myfile >> a >> b.

Sorry again for sooo many questions. but I've literally been looking everywhere and asking probably the wrong questions.

答:
```<code>myfile >> numElements;
numbers.resize(numElements);
for (int i = 0; i < numElements; i++) {
    myfile >> numbers[i];
}
myfile >> a >> b;
</code>```

Title: C++ Line into Vector

Body:
Wow I've been all over the place with questions today and I apologize if they seem to overlap, but for every question comes another question...Since one thing wont work......but I should use something else......etc.

Anyways, I have a text file:

6
3.0 2.5 -1.5 0.0 1.7 4.0
6 10

6 is the Number of "floats" in the second line (the 3.0,2.5 etc...)
3.0,2.5,-1.5 are all a series of floats.
6 and 10 are just 2 integers.

I have a Vector

std::vector<double> numbers;

All i need to do, is get the Second line put into numbers.
So right now I have

ifstream myfile (filename.c_str());

I can simply just do a myfile>> to get the first value (6)
but how would I go about putting the second line in my vector? Remember I ONLY know how big line 2 is, by reading in the first line (the 6 in this case).

Also the last 2 numbers aren't supposed to be in this vector, but two seperate values.
Which i can just do myfile >> a >> b.

Sorry again for sooo many questions. but I've literally been looking everywhere and asking probably the wrong questions.


问:
Instant value change handler on a GWT textbox
I would like to update a text field instantly when typing in a GWT TextBox. My problem is that ValueChangeEvent and ChangeEvent handlers only fire when the TextBox loses focus. I thought about using the KeyPressEvent but then nothing would happen when performing a copy paste with the mouse. </p>

<p>What's the simplest way to do that ? </p>

答:
As a general solution, what works for me (thx to gal-bracha comment):

Generally, GWT does not have classes to handle input event (described here
 and here). So we need to implement it by ourselves:

Handler class:

```<code>import com.google.gwt.event.shared.EventHandler;

public interface InputHandler extends EventHandler {

  void onInput(InputEvent event);

}
</code>```

Event class:

```<code>import com.google.gwt.event.dom.client.DomEvent;

public class InputEvent extends DomEvent<InputHandler> {

    private static final Type<InputHandler> TYPE = new Type<InputHandler>("input", new InputEvent());

    public static Type<InputHandler> getType() {
        return TYPE;
    }

    protected InputEvent() {
    }

    @Override
    public final Type<InputHandler> getAssociatedType() {
        return TYPE;
    }

    @Override
    protected void dispatch(InputHandler handler) {
        handler.onInput(this);
    }

}
</code>```

Usage:

```<code>box.addDomHandler(new InputHandler() {

    @Override
    public void onInput(InputEvent event) {
        text.setText(box.getText());
    }
},InputEvent.getType());
</code>```

It works on every TextBox value change including pasting using context menu. It does not react on arrows, ctrl, shift etc...

Body:
I would like to update a text field instantly when typing in a GWT TextBox. My problem is that ValueChangeEvent and ChangeEvent handlers only fire when the TextBox loses focus. I thought about using the KeyPressEvent but then nothing would happen when performing a copy paste with the mouse.

What's the simplest way to do that ?

Body:
As a general solution, what works for me (thx to gal-bracha comment):

Generally, GWT does not have classes to handle input event (described here
 and here). So we need to implement it by ourselves:

Handler class:

import com.google.gwt.event.shared.EventHandler;

public interface InputHandler extends EventHandler {

  void onInput(InputEvent event);

}

Event class:

import com.google.gwt.event.dom.client.DomEvent;

public class InputEvent extends DomEvent<InputHandler> {

    private static final Type<InputHandler> TYPE = new Type<InputHandler>("input", new InputEvent());

    public static Type<InputHandler> getType() {
        return TYPE;
    }

    protected InputEvent() {
    }

    @Override
    public final Type<InputHandler> getAssociatedType() {
        return TYPE;
    }

    @Override
    protected void dispatch(InputHandler handler) {
        handler.onInput(this);
    }

}

Usage:

box.addDomHandler(new InputHandler() {

    @Override
    public void onInput(InputEvent event) {
        text.setText(box.getText());
    }
},InputEvent.getType());

It works on every TextBox value change including pasting using context menu. It does not react on arrows, ctrl, shift etc...


问:
C# Read at a certain point of a line on text file
Hi I need to read from a text file that is structured like this:

```<code>DataSource = WS****\SQLEXPRESS
DataBase = *********
UserName = sa
PassWord = ****
</code>```

Where stars are information about the database

However I want to only start reading from 1 space after the '=' where the information starts this is the code I have so

```<code>string fileLocation = Environment.CurrentDirectory + "\\SQLConfigSettings.txt";

if (!File.Exists(fileLocation))
{
    using (File.Create(fileLocation)) { }
}
using (FileStream fs = new FileStream(fileLocation, FileMode.Open, FileAccess.Read))
{
    using (StreamReader sr = new StreamReader(fs))
    {
        fs.Seek(13, SeekOrigin.Begin);
        dataSource = sr.ReadLine();

        fs.Seek(11, SeekOrigin.Begin);
        dataBaseName = sr.ReadLine();
        MessageBox.Show(dataBaseName);

        fs.Seek(11, SeekOrigin.Begin);
        userName = sr.ReadLine();

        fs.Seek(11, SeekOrigin.Begin);
        passWord = sr.ReadLine();
    }
}
</code>```

My thoughts were that this would seek the first line read, move down a line, seek again, read the line etc. The first line works, however the next lines just display the entirety of the lines.

Thanks!

答:
```<code>List<string> lines = File.ReadLines(path, Encoding.Default).ToList();

string dataSource = lines[0].Replace("DataSource = ", "");
string database = lines[1].Replace("DataBase = ", "");
string userName = lines[2].Replace("UserName = ", "");
string password = lines[3].Replace("PassWord = ", "");
</code>```

Body:
Hi I need to read from a text file that is structured like this:

DataSource = WS****\SQLEXPRESS
DataBase = *********
UserName = sa
PassWord = ****

Where stars are information about the database

However I want to only start reading from 1 space after the '=' where the information starts this is the code I have so

string fileLocation = Environment.CurrentDirectory + "\\SQLConfigSettings.txt";

if (!File.Exists(fileLocation))
{
    using (File.Create(fileLocation)) { }
}
using (FileStream fs = new FileStream(fileLocation, FileMode.Open, FileAccess.Read))
{
    using (StreamReader sr = new StreamReader(fs))
    {
        fs.Seek(13, SeekOrigin.Begin);
        dataSource = sr.ReadLine();

        fs.Seek(11, SeekOrigin.Begin);
        dataBaseName = sr.ReadLine();
        MessageBox.Show(dataBaseName);

        fs.Seek(11, SeekOrigin.Begin);
        userName = sr.ReadLine();

        fs.Seek(11, SeekOrigin.Begin);
        passWord = sr.ReadLine();
    }
}

My thoughts were that this would seek the first line read, move down a line, seek again, read the line etc. The first line works, however the next lines just display the entirety of the lines.

Thanks!


问:
String companion object in scala
Given a type which has a "converter", I would like to have automatic conversion on method call using this type's companion object. That is, given the following definition,

```<code>case class Converted(name: String)

trait Converter[A] {
  def perform: Converted
}

implicit val StringConverter = new Converter[String] {
  def perform = Converted("String")
}
</code>```

make the following code to work:

```<code>implicit def toConverter(a: String.type): Converted =
  implicitly[Converter[String]].perform // Error: `Found String.type, required AnyRef`

def f(needsConverted: Converted) = ???

f(String) // <- That's what I would like to be able to write.
</code>```

But this fails and both attempts for conversion fail. Note that I cannot change f because it is provided by a third-party library and there are many of them.

Can I make f(String) compile using implicits?

If not possible for Strings, what about classes which do have a companion object, can I do this generically like:

```<code>object TheClass

case class TheClass()

implicit val TheClassConverter = new Converter[TheClass] {
  def perform = Converted("TheClass")
}

implicit def toConverter[A: Converter](a: A.type): Converted =
  implicitly[Converter[A]].perform // Error: `Not found value A`

implicit def toConverter(a: TheClass.type): Converted =
  implicitly[Converter[TheClass]].perform // This works but is not generic

f(TheClass) // This works.
</code>```

Can I make the first toConverter to compile ?

答:
Not sure, what are you trying to accomplish, but following works for me</p>

```<code>case class Converted(name: String)

trait Converter[A] {
  def perform: Converted
}

implicit def toConverted(name: String) = Converted("String")
implicit def toIntConverted(int: Int) = Converted("Int")

def f(needsConverted: Converted): String = needsConverted.name

f("some")
f(5)
</code>```

Title: String companion object in scala

Body:
Given a type which has a "converter", I would like to have automatic conversion on method call using this type's companion object. That is, given the following definition,

case class Converted(name: String)

trait Converter[A] {
  def perform: Converted
}

implicit val StringConverter = new Converter[String] {
  def perform = Converted("String")
}

make the following code to work:

implicit def toConverter(a: String.type): Converted =
  implicitly[Converter[String]].perform // Error: `Found String.type, required AnyRef`

def f(needsConverted: Converted) = ???

f(String) // <- That's what I would like to be able to write.

But this fails and both attempts for conversion fail. Note that I cannot change f because it is provided by a third-party library and there are many of them.

Can I make f(String) compile using implicits?

If not possible for Strings, what about classes which do have a companion object, can I do this generically like:

object TheClass

case class TheClass()

implicit val TheClassConverter = new Converter[TheClass] {
  def perform = Converted("TheClass")
}

implicit def toConverter[A: Converter](a: A.type): Converted =
  implicitly[Converter[A]].perform // Error: `Not found value A`

implicit def toConverter(a: TheClass.type): Converted =
  implicitly[Converter[TheClass]].perform // This works but is not generic

f(TheClass) // This works.

Can I make the first toConverter to compile ?

Body:
Not sure, what are you trying to accomplish, but following works for me

case class Converted(name: String)

trait Converter[A] {
  def perform: Converted
}

implicit def toConverted(name: String) = Converted("String")
implicit def toIntConverted(int: Int) = Converted("Int")

def f(needsConverted: Converted): String = needsConverted.name

f("some")
f(5)


问:
Registered alert script called on BrowserBack
I have a small class that displays an alert via Javascript. I am using this class on a page that checks if the user entered valid zip code. If a valid zip code is not entered, an alert is displayed, and the page is posted back to the same page so they can change it. If they enter a valid zip code, they are redirected to another page. The problem is that if they hit the back button on their browser, the alert is displayed regardless of whether the zip code is valid or not.

Here is the flow:

Zip entry page -> Enter Zip -> Check Zip

if valid zip -> goto overview.aspx
if not valid zip, goto zip entry page

On overview.aspx, if they hit their browser's back button, the alert is displayed. I don't want this to happen. Below is the code I have for the alert class which works great. And below that the code that checks and displays the alert when the LinkButton is clicked.

```<code>protected void GotoReview(object sender, EventArgs e) {
    if (ValidateZipCode(ZipCode)) {
        Response.Redirect(string.Format("~/checkout/overview.aspx?pc={0}&zc={1}",
        ProductCode, ZipCode));
    }
    else {
        Alert.Show("The entered zip code is invalid. Please ensure the zip code is a valid zip code.");
    }
}

private bool ValidateZipCode(string zip) {
    if (zip.Length < 5 || zip.Length > 5) {
        return false;
    }
    if (!Regex.IsMatch(zip, @"^(\d{5}-\d{4})|(\d{5})$")) {
        return false;
    }
    return true;
}

public static class Alert {
    public static void Show(string message) {
        string cleanMessage = message.Replace("'", "\\'");
        string script = "<script type=\"text/javascript\">alert('" + cleanMessage + "');</script>";
        Page page = HttpContext.Current.CurrentHandler as Page;
        if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert")) {
            page.ClientScript.RegisterClientScriptBlock(typeof(Alert), "alert", script);
        }
    }
}
</code>```

答:
Back buttons work differently on all browsers, some browsers will retrieve the newest version, others will simply return what the latest on disk copy is.

The best thing to do here is probably to bust out the old javascript and add an OnSubmit to the form to check for proper validations, jquery would be a great tool in this instance.

With this method, no matter the browsers back strategy, your alert will not be called unless they click on the submit button.

OwnerDisplayName: David Anderson

Body:
I have a small class that displays an alert via Javascript. I am using this class on a page that checks if the user entered valid zip code. If a valid zip code is not entered, an alert is displayed, and the page is posted back to the same page so they can change it. If they enter a valid zip code, they are redirected to another page. The problem is that if they hit the back button on their browser, the alert is displayed regardless of whether the zip code is valid or not.

Here is the flow:

Zip entry page -> Enter Zip -> Check Zip

if valid zip -> goto overview.aspx
if not valid zip, goto zip entry page

On overview.aspx, if they hit their browser's back button, the alert is displayed. I don't want this to happen. Below is the code I have for the alert class which works great. And below that the code that checks and displays the alert when the LinkButton is clicked.

protected void GotoReview(object sender, EventArgs e) {
    if (ValidateZipCode(ZipCode)) {
        Response.Redirect(string.Format("~/checkout/overview.aspx?pc={0}&zc={1}",
        ProductCode, ZipCode));
    }
    else {
        Alert.Show("The entered zip code is invalid. Please ensure the zip code is a valid zip code.");
    }
}

private bool ValidateZipCode(string zip) {
    if (zip.Length < 5 || zip.Length > 5) {
        return false;
    }
    if (!Regex.IsMatch(zip, @"^(\d{5}-\d{4})|(\d{5})$")) {
        return false;
    }
    return true;
}

public static class Alert {
    public static void Show(string message) {
        string cleanMessage = message.Replace("'", "\\'");
        string script = "";
        Page page = HttpContext.Current.CurrentHandler as Page;
        if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert")) {
            page.ClientScript.RegisterClientScriptBlock(typeof(Alert), "alert", script);
        }
    }
}

OwnerDisplayName: Tom Anderson


问:
How to delete last character from a string using jQuery?
How to delete last character from a string for instance in 123-4- when I delete 4 it should display 123- using jQuery.

答:
You can also try this in plain javascript

```<code>"1234".slice(0,-1)
</code>```

the negative second parameter is an offset from the last character, so you can use -2 to remove last 2 characters etc

Body:
You can also try this in plain javascript

"1234".slice(0,-1)

the negative second parameter is an offset from the last character, so you can use -2 to remove last 2 characters etc


问:
ASP.NET MVC Web Application - My enquiry page isn't sending to my DB when I hit submit, I can't see why
I am in the process of creating a web application for a class in school using ASP.NET MVC. For my DB, I am using Entity Framework - code first. I have a very simple enquiry page that asks for; Name, Email, Subject & Message. When filled out and the submit button is pressed, it should insert into my DB table but all it does is clears the form. I will show my code below, if someone could point out why it isn't sending to my DB table, that would be great! Thanks in advance :)

Here is also a screenshot showing the Enquiry table, if that helps;

ModelContext -

```<code>namespace SDP_Project.DAL
{
public class SDP_ProjectContext:DbContext

{
    public SDP_ProjectContext() : base("SDP_Project")
    {

    }

    public DbSet<TripType> TripTypes { get; set; }

    public DbSet<Customer> Customers { get; set; }

    public DbSet<Trip> Trips { get; set; }

    public DbSet<CustomerOrder> CustomerOrders { get; set; }

    public DbSet<OrderedProduct> Orderedproducts { get; set; }

    public DbSet<Cart> Carts { get; set; }

    public DbSet<Enquiry> Enquiries { get; set; }

}
}
</code>```

EnquiryController -

```<code>using System;
using SDP_Project.ViewModels;
using SDP_Project.Models;
using System.Web.Mvc;

namespace SDP_Project.Controllers
{
public class EnquiryController : Controller
{
    [HttpGet]
    public ActionResult Index()
    {
        return View();
    }
    [HttpPost]
    public ActionResult Index(Enquiry vm)
    {
        if (ModelState.IsValid)
        {
            EnquiryAdd enquiryAdd = new EnquiryAdd();
            try
            {
                enquiryAdd.Add(vm);
                ModelState.Clear();
                ViewBag.Message = "Thank you for Contacting us ";
            }
            catch (Exception ex)
            {
                ModelState.Clear();
                ViewBag.Message = $" Sorry we are facing Problem here {ex.Message}";
            }
        }

        return View();
    }
    public ActionResult Error()
    {
        return View();
    }
}
}
</code>```

Enquiry ViewModel -

```<code>using System.ComponentModel.DataAnnotations;

namespace SDP_Project.ViewModels
{
public class Enquiry
{
    [ScaffoldColumn(false)]
    public int Id { get; set; }
    [Required]
    [StringLength(20, MinimumLength = 5)]
    public string Name { get; set; }
    [Required]
    [EmailAddress]
    public string Email { get; set; }
    [Required]
    public string Subject { get; set; }
    [Required]
    public string Message { get; set; }
}
}
</code>```

EnquiryAdd Model -

```<code>using SDP_Project.DAL;
using SDP_Project.ViewModels;

namespace SDP_Project.Models
{
public class EnquiryAdd
{
    SDP_ProjectContext db = new SDP_ProjectContext();

    public void Add(Enquiry newEnquiry)
    {
        SDP_Project.ViewModels.Enquiry enquiry = new  SDP_Project.ViewModels.Enquiry();
        enquiry.Name = newEnquiry.Email;
        enquiry.Email = newEnquiry.Name;
        enquiry.Subject = newEnquiry.Subject;
        enquiry.Message = newEnquiry.Message;

        db.Enquiries.Add(enquiry);
        db.SaveChanges();
    }
}
}
</code>```

Enquiry View -

```<code>@model SDP_Project.ViewModels.Enquiry

@{
ViewData["Title"] = "Home Page";
}
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-   unobtrusive/jquery.validate.unobtrusive.min.js"></script>
<div>
<div class="col-md-6">
    <div>
        @if (ViewBag.Message == null)
        {
        <div>
            <form method="post">
                <div class="form-group">
                <p></p>
                <p></p>
                    <label asp-for="Name">Name</label>
                    <input asp-for="Name" class="form-control" />
                    <span asp-validation-for="Name"
                          class="text-muted"></span>
                </div>
                <div class="form-group">
                    <label asp-for="Email">Email</label>
                    <input asp-for="Email" class="form-control" />
                    <span asp-validation-for="Email"
                          class="text-muted"></span>
                </div>
                <div class="form-group">
                    <label asp-for="Subject">Subject</label>
                    <input asp-for="Subject" class="form-control" />
                    <span asp-validation-for="Subject"
                          class="text-muted"></span>
                </div>
                <div class="form-group">
                    <label asp-for="Message">Message</label>
                    <textarea rows="5" cols="15"
                              asp-for="Message" class="form-control">    </textarea>
                    <span asp-validation-for="Message"
                          class="text-muted"></span>
                </div>
                <div>
                    <button type="submit"
                            class="btn btn-success">
                        Send
                    </button>
                </div>

            </form>
        </div>
        }
    </div>

    <div>
        <div>
            @if (ViewBag.Message != null)
        {
        <div>@ViewBag.Message</div>

            }
        </div>
    </div>
</div>

</div>
</code>```

答:
You can look at [this][1].

[1]: How to write "Html.BeginForm" in Razor. Try creating the form with the MVC helper setting the right controller and action

Body:
I am in the process of creating a web application for a class in school using ASP.NET MVC. For my DB, I am using Entity Framework - code first. I have a very simple enquiry page that asks for; Name, Email, Subject & Message. When filled out and the submit button is pressed, it should insert into my DB table but all it does is clears the form. I will show my code below, if someone could point out why it isn't sending to my DB table, that would be great! Thanks in advance :)

Here is also a screenshot showing the Enquiry table, if that helps;

ModelContext -

namespace SDP_Project.DAL
{
public class SDP_ProjectContext:DbContext

{
    public SDP_ProjectContext() : base("SDP_Project")
    {

    }

    public DbSet<TripType> TripTypes { get; set; }

    public DbSet<Customer> Customers { get; set; }

    public DbSet<Trip> Trips { get; set; }

    public DbSet<CustomerOrder> CustomerOrders { get; set; }

    public DbSet<OrderedProduct> Orderedproducts { get; set; }

    public DbSet<Cart> Carts { get; set; }

    public DbSet<Enquiry> Enquiries { get; set; }

}
}

EnquiryController -

using System;
using SDP_Project.ViewModels;
using SDP_Project.Models;
using System.Web.Mvc;

namespace SDP_Project.Controllers
{
public class EnquiryController : Controller
{
    [HttpGet]
    public ActionResult Index()
    {
        return View();
    }
    [HttpPost]
    public ActionResult Index(Enquiry vm)
    {
        if (ModelState.IsValid)
        {
            EnquiryAdd enquiryAdd = new EnquiryAdd();
            try
            {
                enquiryAdd.Add(vm);
                ModelState.Clear();
                ViewBag.Message = "Thank you for Contacting us ";
            }
            catch (Exception ex)
            {
                ModelState.Clear();
                ViewBag.Message = $" Sorry we are facing Problem here {ex.Message}";
            }
        }

        return View();
    }
    public ActionResult Error()
    {
        return View();
    }
}
}

Enquiry ViewModel -

using System.ComponentModel.DataAnnotations;

namespace SDP_Project.ViewModels
{
public class Enquiry
{
    [ScaffoldColumn(false)]
    public int Id { get; set; }
    [Required]
    [StringLength(20, MinimumLength = 5)]
    public string Name { get; set; }
    [Required]
    [EmailAddress]
    public string Email { get; set; }
    [Required]
    public string Subject { get; set; }
    [Required]
    public string Message { get; set; }
}
}

EnquiryAdd Model -

using SDP_Project.DAL;
using SDP_Project.ViewModels;

namespace SDP_Project.Models
{
public class EnquiryAdd
{
    SDP_ProjectContext db = new SDP_ProjectContext();

    public void Add(Enquiry newEnquiry)
    {
        SDP_Project.ViewModels.Enquiry enquiry = new  SDP_Project.ViewModels.Enquiry();
        enquiry.Name = newEnquiry.Email;
        enquiry.Email = newEnquiry.Name;
        enquiry.Subject = newEnquiry.Subject;
        enquiry.Message = newEnquiry.Message;

        db.Enquiries.Add(enquiry);
        db.SaveChanges();
    }
}
}

Enquiry View -

@model SDP_Project.ViewModels.Enquiry

@{
ViewData["Title"] = "Home Page";
}

        @if (ViewBag.Message == null)
        {

            <form method="post">

                    Name
                    <input asp-for="Name" class="form-control" />

                    Email
                    <input asp-for="Email" class="form-control" />

                    Subject
                    <input asp-for="Subject" class="form-control" />

                    Message
                    <textarea rows="5" cols="15"
                              asp-for="Message" class="form-control">    </textarea>

                    <button type="submit"
                            class="btn btn-success">
                        Send
                    </button>

            </form>

        }

            @if (ViewBag.Message != null)
        {

@ViewBag.Message

            }


问:
Prevent mobile app exit
I am developing an hybrid mobile application with the Ionic framework and I'd want that when you want to close the application or switch app you need to enter a password.

The idea is that the phone running the application will be accessible to other people and I want to prevent people to simply press the home button and access to the rest of the user's phone.

Is it possible with an hybrid app or with native app from the code (with special permissions) without having the user to configure something from the phone's settings ?

答: No, it's not possible. But the functionality is also present in Android. Check "Screen pinning" (Settings -> Security -> Screen pinning) and you will be able to "pin" your app.

Title: Prevent mobile app exit


问:
Using linear interpolation to predict value in matlab
I have a set of data and would like to use linear interpolation in Matlab to find the corresponding value of a specific point.

```<code>x = [1 2 3 4 5 6 7 8 9];
y = [1 2 3 4 5 4 2 6 8];
xq = [1:0.25:9];
vq1 = interp1(x,y,xq);
plot(x,y,'o',xq,vq1,':.');
</code>```

After doing this, is there any way for me to find the value of x given a value of y? For example, when y = 3.5, x = ?

答:
Simple Interpolation

You could just interpolate the other way...

```<code>% Your code
x = [1 2 3 4 5 6 7 8 9];
y = [1 2 3 4 5 4 2 6 8];
xq = [1:0.25:9];
yq = interp1(x, y, xq);

% Interpolate your newly interpolated xq and yq to find x = x1 when y = 3.5
x1 = interp1(yq, xq, 3.5)
</code>```

Finding Zeros

This approach is more complicated but, depending on your data, may be more applicable.

You could use some sort of root finding approach using fzero, and a function defined as below

```<code>% Initialise
x = [1 2 3 4 5 6 7 8 9]; y = [1 2 3 4 5 4 2 6 8];
% Define function, like your interpolation, which will have a zero at x=x0
% when y = y0.
y0 = 3.5;
yq = @(xq) interp1(x, y, xq) - y0
% find the zero, intial guess must be good enough
y0 = fzero(yq, 1)
</code>```

As noted in the comments, the intial guess must be "good enough" - this is not only for convergence within fzero but if, during the evaluation, a value of x is tested which is outside of your interpolation then it will break.

Example:

```<code>y0 = fzero(yq, 1)
% >> Exiting fzero: aborting search for an interval containing a sign change
%    because NaN or Inf function value encountered during search.
%    (Function value at 0.971716 is NaN.)

y0 = fzero(yq, 5)
% >> y0 = 3.5, as expected from the input data.
</code>```

Body:
I have a set of data and would like to use linear interpolation in Matlab to find the corresponding value of a specific point.

x = [1 2 3 4 5 6 7 8 9];
y = [1 2 3 4 5 4 2 6 8];
xq = [1:0.25:9];
vq1 = interp1(x,y,xq);
plot(x,y,'o',xq,vq1,':.');

After doing this, is there any way for me to find the value of x given a value of y? For example, when y = 3.5, x = ?

Body:
Simple Interpolation

You could just interpolate the other way...

% Your code
x = [1 2 3 4 5 6 7 8 9];
y = [1 2 3 4 5 4 2 6 8];
xq = [1:0.25:9];
yq = interp1(x, y, xq);

% Interpolate your newly interpolated xq and yq to find x = x1 when y = 3.5
x1 = interp1(yq, xq, 3.5)

Finding Zeros

This approach is more complicated but, depending on your data, may be more applicable.

You could use some sort of root finding approach using fzero, and a function defined as below

% Initialise
x = [1 2 3 4 5 6 7 8 9]; y = [1 2 3 4 5 4 2 6 8];
% Define function, like your interpolation, which will have a zero at x=x0
% when y = y0.
y0 = 3.5;
yq = @(xq) interp1(x, y, xq) - y0
% find the zero, intial guess must be good enough
y0 = fzero(yq, 1)

As noted in the comments, the intial guess must be "good enough" - this is not only for convergence within fzero but if, during the evaluation, a value of x is tested which is outside of your interpolation then it will break.

Example:

y0 = fzero(yq, 1)
% >> Exiting fzero: aborting search for an interval containing a sign change
%    because NaN or Inf function value encountered during search.
%    (Function value at 0.971716 is NaN.)

y0 = fzero(yq, 5)
% >> y0 = 3.5, as expected from the input data.


问:
android upload file on shared folder inside htdocs
I need to upload file on shared folder inside lampp ht-docs directory.

The file is inside internal storage. I have also path of that file with me.

I have tried some of the solutions but it is not moving file to that shared folder inside lampp ht-docs.

I have the URL like this http://192.168.1...../OrderFiles/. OrderFiles is the shared folder inside lampp htdocs directory. I want to upload file here from file path of internal storage.

Here is what i have tried.

```<code>public void uploadLocal() {
        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        DataInputStream inStream = null;
        File fileName = new File(DBController.lastXmlPathLocal);
        Log.w("getAbsolutePath", fileName.getAbsolutePath());
        Log.w("getPath", fileName.getPath());
        String existingFileName = fileName.getAbsolutePath();
        Log.w("existingFileName", existingFileName);
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;
        String responseFromServer = "";
        String urlString = "http://192.168.1......./OrderFiles/";
        Log.w("urlString", urlString);
        try {
            //------------------ CLIENT REQUEST
            FileInputStream fileInputStream = new FileInputStream(new File(fileName.getPath()));
            // open a URL connection to the Servlet
            URL url = new URL(urlString);
            // Open a HTTP connection to the URL
            conn = (HttpURLConnection) url.openConnection();
            // Allow Inputs
            conn.setDoInput(true);
            // Allow Outputs
            conn.setDoOutput(true);
            // Don't use a cached copy.
            conn.setUseCaches(false);
            // Use a post method.
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            dos = new DataOutputStream(conn.getOutputStream());
            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + existingFileName + "\"" + lineEnd);
            dos.writeBytes(lineEnd);
            // create a buffer of maximum size
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];
            // read file and write it into form...
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            //while (bytesRead > 0)
            Log.v("info", ".size." + bytesRead);
            for (int n1 = 0; n1 < bytesRead; n1++) {

                dos.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            }

            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
            // close streams
            Log.v("info", "File is written");
            fileInputStream.close();
            dos.flush();
            dos.close();
        } catch (MalformedURLException ex) {
            Log.v("info", "error: " + ex.getMessage(), ex);
        } catch (IOException ioe) {
            Log.v("info", "error: " + ioe.getMessage(), ioe);
        }
        /*//------------------ read the SERVER RESPONSE
        try {
            inStream = new DataInputStream(conn.getInputStream());
            String str;

            while ((str = inStream.readLine()) != null) {
                Log.v("info", "Server Response " + str);
            }
            inStream.close();

        } catch (IOException ioex) {
            Log.v("info", "error: " + ioex.getMessage(), ioex);
        }*/
    }
</code>```

The above code showing File is written in logcat but inside that folder not showing any of the file.

Is their any other solution to integrate this ?

Any help would be greatly appreciated.

答: First you need a php script to upload a file to begin with. And after that the php script should contain code to move the uploaded file to your wanted folder. And that is how it goes. And that is how you should do it. </p>

Body:
I need to upload file on shared folder inside lampp ht-docs directory.

The file is inside internal storage. I have also path of that file with me.

I have tried some of the solutions but it is not moving file to that shared folder inside lampp ht-docs.

I have the URL like this http://192.168.1...../OrderFiles/. OrderFiles is the shared folder inside lampp htdocs directory. I want to upload file here from file path of internal storage.

Here is what i have tried.

public void uploadLocal() {
        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        DataInputStream inStream = null;
        File fileName = new File(DBController.lastXmlPathLocal);
        Log.w("getAbsolutePath", fileName.getAbsolutePath());
        Log.w("getPath", fileName.getPath());
        String existingFileName = fileName.getAbsolutePath();
        Log.w("existingFileName", existingFileName);
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;
        String responseFromServer = "";
        String urlString = "http://192.168.1......./OrderFiles/";
        Log.w("urlString", urlString);
        try {
            //------------------ CLIENT REQUEST
            FileInputStream fileInputStream = new FileInputStream(new File(fileName.getPath()));
            // open a URL connection to the Servlet
            URL url = new URL(urlString);
            // Open a HTTP connection to the URL
            conn = (HttpURLConnection) url.openConnection();
            // Allow Inputs
            conn.setDoInput(true);
            // Allow Outputs
            conn.setDoOutput(true);
            // Don't use a cached copy.
            conn.setUseCaches(false);
            // Use a post method.
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            dos = new DataOutputStream(conn.getOutputStream());
            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + existingFileName + "\"" + lineEnd);
            dos.writeBytes(lineEnd);
            // create a buffer of maximum size
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];
            // read file and write it into form...
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            //while (bytesRead > 0)
            Log.v("info", ".size." + bytesRead);
            for (int n1 = 0; n1 < bytesRead; n1++) {

                dos.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            }

            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
            // close streams
            Log.v("info", "File is written");
            fileInputStream.close();
            dos.flush();
            dos.close();
        } catch (MalformedURLException ex) {
            Log.v("info", "error: " + ex.getMessage(), ex);
        } catch (IOException ioe) {
            Log.v("info", "error: " + ioe.getMessage(), ioe);
        }
        /*//------------------ read the SERVER RESPONSE
        try {
            inStream = new DataInputStream(conn.getInputStream());
            String str;

            while ((str = inStream.readLine()) != null) {
                Log.v("info", "Server Response " + str);
            }
            inStream.close();

        } catch (IOException ioex) {
            Log.v("info", "error: " + ioex.getMessage(), ioex);
        }*/
    }

The above code showing File is written in logcat but inside that folder not showing any of the file.

Is their any other solution to integrate this ?

Any help would be greatly appreciated.


问:
Big quantity of data with MySql
i have a question about Mass storage. Actually, i'm working with 5 sensors which sends a lot of datas with a different frequency for each one and i'm using MySQL DATABASE.

so here is my questions:

1) is MySQL the perfect solution.
2) if not, is there a solution to store this big quantity of data in a data base?
3) I'm using Threads in this and i'm using mutexs also, i'm afraid if this can cause problems, Actually,it seems to be.

i hope i will have an answer to this question.

答:
Using a database can add extra computation overhead if you have a "lot of data". Another question is what you do with the data? If you only stack them, a map/vector can be enough.
The first step is maybe to use map/vector that you can serialize to a file when needed. Second you can add the database if you wish.

About mutex if you share some code with different thread and if (in this code) you work on the same data at the same time, then you need them. Otherwise remove them. BTW if you can separate read and write operations then you don't need mutex/semaphore mechanism.

Title: Big quantity of data with MySql


问:
friend vs member functions in Operator Overloading C++
Previously I learnt about overloading Operators in C++ as member functions as well as friend functions of a class. Although, I know how to overload operators in C++ using both techniques. But I am still confused that ** which one is better** ? A member function or a friend function to overload operators, which one should i use and why?
 Please guide me ! Your response will be appreciated greatly. I shall be glad and thankful for your answers.</p>

答:
There is probably not a fixed rule for this so I just give my opinion: when possible use member function for operator overloading.  The main reason for this is that I see operators as integral part of the class and the logic of the class is more localized.

The reason for prefering free functions for operator overloading would be to keep the class as lean as possible (only use friend when needed).

In some cases operators can't be members, so there is no discussion in that case.  Mainly member functions have the class instance as first parameter which isn't always possible (e.g. operator<< for i/o).


问:
JTable value being overwritten
My GUI application is Connecting to the DB and I have managed to add a product from the DB to my JTable on the GUI. When I click a second button it overwrites the first. I do not want this as it is an order till system and I want whatever I click to appear on the table as it is clicked. Is there any way to append onto the table rather than overwriting the values every time. Here is my code. </p>

```<code>americanoSmall.addActionListener(
        new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                try {
                    String query = "select ProductName, Price from product where ProductID = 24";
                    java.sql.PreparedStatement pst = connection.prepareStatement(query);
                    ResultSet rs = pst.executeQuery();
                    table.setModel(DbUtils.resultSetToTableModel(rs));

                    } catch (Exception e1)
                    {
                        e1.printStackTrace();
                    }
                }
            });
</code>```

答:
Don't change the table model whenever the model changes. Instead, use the addRow method of the TableModel. Here's a minimal, complete and verifiable example.

```<code>import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

public class Test {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Test");

        Container cont = frame.getContentPane();
        cont.setLayout(new BorderLayout());

        DefaultTableModel dtm = new DefaultTableModel(new Object[]{"Column 1","Column 2"}, 0);
        JTable table = new JTable(dtm);

        JScrollPane scroll = new JScrollPane(table);
        cont.add(scroll, BorderLayout.CENTER);

        dtm.addRow(new Object[]{"Value 1", "Value 2"});

        JButton add = new JButton("Add");
        cont.add(add, BorderLayout.NORTH);

        add.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                dtm.addRow(new Object[]{"Another value", "Another value"});
            }
        });

        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}
</code>```

Title: JTable value being overwritten

Body:
My GUI application is Connecting to the DB and I have managed to add a product from the DB to my JTable on the GUI. When I click a second button it overwrites the first. I do not want this as it is an order till system and I want whatever I click to appear on the table as it is clicked. Is there any way to append onto the table rather than overwriting the values every time. Here is my code.

americanoSmall.addActionListener(
        new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                try {
                    String query = "select ProductName, Price from product where ProductID = 24";
                    java.sql.PreparedStatement pst = connection.prepareStatement(query);
                    ResultSet rs = pst.executeQuery();
                    table.setModel(DbUtils.resultSetToTableModel(rs));

                    } catch (Exception e1)
                    {
                        e1.printStackTrace();
                    }
                }
            });

Body:
Don't change the table model whenever the model changes. Instead, use the addRow method of the TableModel. Here's a minimal, complete and verifiable example.

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

public class Test {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Test");

        Container cont = frame.getContentPane();
        cont.setLayout(new BorderLayout());

        DefaultTableModel dtm = new DefaultTableModel(new Object[]{"Column 1","Column 2"}, 0);
        JTable table = new JTable(dtm);

        JScrollPane scroll = new JScrollPane(table);
        cont.add(scroll, BorderLayout.CENTER);

        dtm.addRow(new Object[]{"Value 1", "Value 2"});

        JButton add = new JButton("Add");
        cont.add(add, BorderLayout.NORTH);

        add.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                dtm.addRow(new Object[]{"Another value", "Another value"});
            }
        });

        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}


问:
Better SQL Replace
I wanted to know if there is a better way of writing this Update.

```<code>update Alumni_Export_New
set phone = replace(replace(replace(replace(phone,'-',''),' ',''),')',''),'(','')
from tbl
</code>```

I have a stored procedure in MSSQL 2005 to clean the phone field in a table and thought there should be a better way of doing this then what I have.

答:
Have you considering make loop trough all string, if you need only numeric chars inside i

```<code>    CREATE FUNCTION fn_retun_only_numbers
(
    @myOrgString varchar(50)
)
RETURNS  varchar(50)
AS
BEGIN
    declare @lenOfString int, @i int
    declare @oneChar varchar(1),@newString varchar(50)

    set @lenOfString = (select len(@myOrgString))
    set @i = 1
    set @newString= ''

    while  (@lenOfstring>=@i)
    begin
    set @oneChar = substring(@myOrgString,@i,1)

if ((@oneChar)in ('0','1','2','3','4','5','6','7','8','9'))
begin
set @newString=@newString+@oneChar
end
set @i=@i+1
end
return @newString
END
GO
</code>```

And so as other mentioned you can  now

```<code>update Alumni_Export_New
set phone = dbo.fn_retun_only_numbers(phone)
from tbl
</code>```

I do not have SQL at home so maybe there is some mistakes in code

This is not maybe the best solution but if you need to be sure to always get only numbers
maybe this is one of possible approach

Title: Better SQL Replace

Body:
I wanted to know if there is a better way of writing this Update.

update Alumni_Export_New
set phone = replace(replace(replace(replace(phone,'-',''),' ',''),')',''),'(','')
from tbl

I have a stored procedure in MSSQL 2005 to clean the phone field in a table and thought there should be a better way of doing this then what I have.

Body:
Have you considering make loop trough all string, if you need only numeric chars inside i

    CREATE FUNCTION fn_retun_only_numbers
(
    @myOrgString varchar(50)
)
RETURNS  varchar(50)
AS
BEGIN
    declare @lenOfString int, @i int
    declare @oneChar varchar(1),@newString varchar(50)

    set @lenOfString = (select len(@myOrgString))
    set @i = 1
    set @newString= ''

    while  (@lenOfstring>=@i)
    begin
    set @oneChar = substring(@myOrgString,@i,1)

if ((@oneChar)in ('0','1','2','3','4','5','6','7','8','9'))
begin
set @newString=@newString+@oneChar
end
set @i=@i+1
end
return @newString
END
GO

And so as other mentioned you can  now

update Alumni_Export_New
set phone = dbo.fn_retun_only_numbers(phone)
from tbl

I do not have SQL at home so maybe there is some mistakes in code

This is not maybe the best solution but if you need to be sure to always get only numbers
maybe this is one of possible approach


问:
Select * from this week
I have a table with data and a column named 'week'. Everytime an user post something to the database, this is added to the column 'week':

```<code>$week = Date('W');
</code>```

So everything inserted in this week have the number '13' in the week-column. Now I would like a query that select everything from this week and post on my site, so I wrote a variable like the one above and wrote:

```<code>$sql = 'SELECT * FROM my_table WHERE week = $week';
</code>```

But it echos an error: Unknown column '$week' in 'where clause'.

It works fine, if I write SELECT * FROM my_table WHERE week = 13; but I would like it to automatically select the current week number.

答:
Be careful to SQL Injection and
change this

```<code>$sql = 'SELECT * FROM my_table WHERE week = $week';
</code>```

in

```<code>$sql = 'SELECT * FROM my_table WHERE week = '.$week;
</code>```

Title: Select * from this week

Body:
I have a table with data and a column named 'week'. Everytime an user post something to the database, this is added to the column 'week':

$week = Date('W');

So everything inserted in this week have the number '13' in the week-column. Now I would like a query that select everything from this week and post on my site, so I wrote a variable like the one above and wrote:

$sql = 'SELECT * FROM my_table WHERE week = $week';

But it echos an error: Unknown column '$week' in 'where clause'.

It works fine, if I write SELECT * FROM my_table WHERE week = 13; but I would like it to automatically select the current week number.

Body:
Be careful to SQL Injection and
change this

$sql = 'SELECT * FROM my_table WHERE week = $week';

in

$sql = 'SELECT * FROM my_table WHERE week = '.$week;


问:
SQL Server- get manager of employee (with exceptions)
I am currently stuck with a (for me) quite complicated problem.

I have created following table with cte's:

```<code>EmployeeID | OrganisationID | Level | Manager1 | Manager2 | Manager3 | Manager4 | Manager5
1          | 1001           | 1     | NULL     | NULL     | NULL     | NULL     | NULL
8          | 1011           | 1     | 1        | NULL     | NULL     | NULL     | NULL
2          | 1002           | 2     | 1        | 1        | NULL     | NULL     | NULL
3          | 1002           | 2     | 1        | 1        | NULL     | NULL     | NULL
4          | 1003           | 4     | 1        | 2        | NULL     | 4        | NULL
5          | 1004           | 3     | NULL     | NULL     | 2        | NULL     | NULL
6          | 1005           | 5     | 1        | NULL     | 2        | 6        | 6
7          | 1006           | 5     | NULL     | 7        | 7        | NULL     | NULL
</code>```

What I want to get from this is the manager of each employee, based on their Level. So for someone from level 5, I need to get his Manager5 However, there are some conditions:

If the EmployeeID and the ManagerX have the same value, we need to look at ManagerX-1. (And if that's the same too, we go one higher again, etc)

If the ManagerX is empty, we need to look at ManagerX-1. (And if that's empty too, we go one higher again, etc)

For employees from level 1, we can just take the manager1

So what I would like as result would be:

```<code>EmployeeID | RealManager
1          | NULL
8          | 1
2          | 1
3          | 1
4          | 2
5          | 2
6          | 2
7          | NULL
</code>```

I only got this far

```<code>SELECT EmployeeID,
Case
    when level = 1 then Manager1
    when level = 2 then ISNULL(Manager2,Manager1)
    when level = 3 then ISNULL(Manager3,ISNULL(Manager2,Manager1))
    when level = 4 then ISNULL(Manager4,ISNULL(Manager3,ISNULL(Manager2,Manager1)))
    when level = 5 then ISNULL(Manager5,ISNULL(Manager4,ISNULL(Manager3,ISNULL(Manager2,Manager1))))
    else null
    END as RealManager
FROM cte
</code>```

But this doesn't check the first condition (and it doesn't look quite performant).

Any sugestions or ideas?

答:
Please try to make use of below code:</p>

```<code>    DECLARE @Table TABLE
    (EmployeeID INT,OrganisationID INT,Level INT,Manager1 INT,Manager2 INT,Manager3 INT,Manager4 INT,Manager5 INT)

    INSERT INTO @Table VALUES
    (1,1001,1,NULL,NULL,NULL,NULL,NULL),
    (8,1011,1,1   ,NULL,NULL,NULL,NULL),
    (2,1002,2,1   ,1   ,NULL,NULL,NULL),
    (3,1002,2,1   ,1   ,NULL,NULL,NULL),
    (4,1003,4,1   ,2   ,NULL,4   ,NULL),
    (5,1004,3,NULL,NULL,2   ,NULL,NULL),
    (6,1005,5,1   ,NULL,2   ,6   ,6   ),
    (7,1006,5,NULL,7   ,7   ,NULL,NULL)

    SELECT EmployeeID,
    CASE
        WHEN level = 1 THEN  NULLIF(Manager1,EmployeeID)
        WHEN level = 2 THEN  COALESCE(NULLIF(Manager2,EmployeeID),NULLIF(Manager1,EmployeeID))
        WHEN level = 3 THEN  COALESCE(NULLIF(Manager3,EmployeeID),NULLIF(Manager2,EmployeeID),NULLIF(Manager1,EmployeeID))
        WHEN level = 4 THEN  COALESCE(NULLIF(Manager4,EmployeeID),NULLIF(Manager3,EmployeeID),NULLIF(Manager2,EmployeeID),NULLIF(Manager1,EmployeeID))
        WHEN level = 5 THEN  COALESCE(NULLIF(Manager5,EmployeeID),NULLIF(Manager4,EmployeeID),NULLIF(Manager3,EmployeeID),NULLIF(Manager2,EmployeeID),NULLIF(Manager1,EmployeeID))
        END AS Manager
    FROM @Table
</code>```

Body:
I am currently stuck with a (for me) quite complicated problem.

I have created following table with cte's:

EmployeeID | OrganisationID | Level | Manager1 | Manager2 | Manager3 | Manager4 | Manager5
1          | 1001           | 1     | NULL     | NULL     | NULL     | NULL     | NULL
8          | 1011           | 1     | 1        | NULL     | NULL     | NULL     | NULL
2          | 1002           | 2     | 1        | 1        | NULL     | NULL     | NULL
3          | 1002           | 2     | 1        | 1        | NULL     | NULL     | NULL
4          | 1003           | 4     | 1        | 2        | NULL     | 4        | NULL
5          | 1004           | 3     | NULL     | NULL     | 2        | NULL     | NULL
6          | 1005           | 5     | 1        | NULL     | 2        | 6        | 6
7          | 1006           | 5     | NULL     | 7        | 7        | NULL     | NULL

What I want to get from this is the manager of each employee, based on their Level. So for someone from level 5, I need to get his Manager5 However, there are some conditions:

If the EmployeeID and the ManagerX have the same value, we need to look at ManagerX-1. (And if that's the same too, we go one higher again, etc)

If the ManagerX is empty, we need to look at ManagerX-1. (And if that's empty too, we go one higher again, etc)

For employees from level 1, we can just take the manager1

So what I would like as result would be:

EmployeeID | RealManager
1          | NULL
8          | 1
2          | 1
3          | 1
4          | 2
5          | 2
6          | 2
7          | NULL

I only got this far

SELECT EmployeeID,
Case
    when level = 1 then Manager1
    when level = 2 then ISNULL(Manager2,Manager1)
    when level = 3 then ISNULL(Manager3,ISNULL(Manager2,Manager1))
    when level = 4 then ISNULL(Manager4,ISNULL(Manager3,ISNULL(Manager2,Manager1)))
    when level = 5 then ISNULL(Manager5,ISNULL(Manager4,ISNULL(Manager3,ISNULL(Manager2,Manager1))))
    else null
    END as RealManager
FROM cte

But this doesn't check the first condition (and it doesn't look quite performant).

Any sugestions or ideas?

Body:
Please try to make use of below code:

    DECLARE @Table TABLE
    (EmployeeID INT,OrganisationID INT,Level INT,Manager1 INT,Manager2 INT,Manager3 INT,Manager4 INT,Manager5 INT)

    INSERT INTO @Table VALUES
    (1,1001,1,NULL,NULL,NULL,NULL,NULL),
    (8,1011,1,1   ,NULL,NULL,NULL,NULL),
    (2,1002,2,1   ,1   ,NULL,NULL,NULL),
    (3,1002,2,1   ,1   ,NULL,NULL,NULL),
    (4,1003,4,1   ,2   ,NULL,4   ,NULL),
    (5,1004,3,NULL,NULL,2   ,NULL,NULL),
    (6,1005,5,1   ,NULL,2   ,6   ,6   ),
    (7,1006,5,NULL,7   ,7   ,NULL,NULL)

    SELECT EmployeeID,
    CASE
        WHEN level = 1 THEN  NULLIF(Manager1,EmployeeID)
        WHEN level = 2 THEN  COALESCE(NULLIF(Manager2,EmployeeID),NULLIF(Manager1,EmployeeID))
        WHEN level = 3 THEN  COALESCE(NULLIF(Manager3,EmployeeID),NULLIF(Manager2,EmployeeID),NULLIF(Manager1,EmployeeID))
        WHEN level = 4 THEN  COALESCE(NULLIF(Manager4,EmployeeID),NULLIF(Manager3,EmployeeID),NULLIF(Manager2,EmployeeID),NULLIF(Manager1,EmployeeID))
        WHEN level = 5 THEN  COALESCE(NULLIF(Manager5,EmployeeID),NULLIF(Manager4,EmployeeID),NULLIF(Manager3,EmployeeID),NULLIF(Manager2,EmployeeID),NULLIF(Manager1,EmployeeID))
        END AS Manager
    FROM @Table


问:
Angular 2 Code Snippet extension (from Mads) not working in VS 2017
I should have quite a lot of snippets available to me but when I type in "ng" I am not seeing them. All I get is what is in the below image. Is there a chance Resharper can be overriding it? If so, does anyone know how to resolve it? I have not been able to research a solution so this was my last hope.

答:
There are two ways to invoke Visual Studio's own code snippets when using ReSharper.

If you want to show VS's own code snippets menu, set your own shortcut for "Edit | Intellisense | Insert Snippet" item (via VS options -> Environment -> Keyboard).

If you want to have VS's code snippets in code completion, you can override code completion to come from Visual Studio instead of ReSharper. Go to ReSharper | Options | Environment | IntelliSense | General, and set code completion type to 'Visual Studio'. But please note that this disables ReSharper's own code completion.

ReSharper will include Angular 2 live templates since 2017.2, created a ticket for that: https://youtrack.jetbrains.com/issue/RSRP-464025.