问:
push_back operation in c# containers
I need container like c++ vector. Often it is adviced to use List, but it dosen't support push_back operation. I know this is rather simple implementing an extension method for List container. But. Would Stack be a good alternative?

Thanks!

答:
You won't get a direct equivalent to vector in C# because you have no control over how the memory is allocated.  std::vector will always have its memory in a contiguous block; so if needed, you could access it like so:

```<code>std::vector<int> v;
// add items to v
CallSomeCFunction(&v[0]);
</code>```

C# gives you no control over how the memory is allocated, so the distinction between a vector/array and a list is non-existent.  You can use the List container is what you want.

Title: push_back operation in c# containers

Body:
You won't get a direct equivalent to vector in C# because you have no control over how the memory is allocated.  std::vector will always have its memory in a contiguous block; so if needed, you could access it like so:

std::vector<int> v;
// add items to v
CallSomeCFunction(&v[0]);

C# gives you no control over how the memory is allocated, so the distinction between a vector/array and a list is non-existent.  You can use the List container is what you want.


来源: stackexchange

问:
Asp.net C# How to redirect to another page if the current page has query string
I am stucked here. I have  page and opened it via request.query string. Hence called products.aspx?Id=483.

So my question is how am I going to redirect from this page to a page that still requires variable to be passed in, in this case the page details.aspx?Id=56

It fails to do so. How am I going to do this guys. Any help I will appreciate.

答:
By using the Request.QueryString property on your HttpContext and using Response.Redirect

For example:

```<code>string id = HttpContext.Current.Request.QueryString["id"];
if (!string.IsNullOrEmpty(id)) {
    Response.Redirect("/some-new-page.aspx");
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
By using the Request.QueryString property on your HttpContext and using Response.Redirect

For example:

string id = HttpContext.Current.Request.QueryString["id"];
if (!string.IsNullOrEmpty(id)) {
    Response.Redirect("/some-new-page.aspx");
}


问:
MVVM show new window from VM when seperated projects
My question involves something where thousand and one topics are created about,
and if I overlooked an answer to my question, I'm sorry, but as far as I looked none really could answer my question. For example:
Opening new window in MVVM WPF

The answers are okay when if you use just one WPF project (including models, vms and views) but since I'm learning how to implement MVVM the correct way (and I've read multiple times that best practice is to create seperate class lib (dll's) for model, viewmodel and a seperate gui project) that doesn't seem to work in my eyes because if I want to create an interface like IWindowService (described on previous url and also here, It's impossible to access Window or Control class because then I should have a reference to the gui project and the whole goal of the pattern is wrecked.

So my question is how to show a new window (with a new viewmodel) from for example the MainViewModel, while respecting the loosely coupled MVVM principles AND seperate projects.

More in depth example of what I'm trying to achieve:

I have following structure:

MODEL (dll project)

     Profile

VIEWMODEL (dll project)

     MainViewModel

     AddProfileViewModel

VIEW (WPF) (exe project)

     MainWindow

     AddProfileWindow

I open MainWindow and I want to press the button AddProfile, then AddProfileWindow needs to show up with the AddProfileViewModel attached to it.

答:
Define the IWindowService interface in the model project.

Reference the model project from the view model project.

Implement the IWindowService in the WPF application (view) project.

The button should then be bound to an ICommand that uses IWindowService to open the window. Something like this:

```<code>public class MainWindowViewModel
{
    private readonly IWindowService _windowService;

    public MainWindowViewModel(IWindowService windowService)
    {
        _windowService = windowService;
        AddProfile = new DelegateCommand(() =>
        {
            _windowService.OpenProfileWindow(new AddProfileViewModel());
        });
    }

    public ICommand AddProfile { get; }
}

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new MainWindowViewModel(new WindowService());
    }
}

public class WindowService : IWindowService
{
    public void OpenProfileWindow(AddProfileViewModel vm)
    {
        AddProfileWindow win = new AddProfileWindow();
        win.DataContext = vm;
        win.Show();
    }
}
</code>```

Body:
Define the IWindowService interface in the model project.

Reference the model project from the view model project.

Implement the IWindowService in the WPF application (view) project.

The button should then be bound to an ICommand that uses IWindowService to open the window. Something like this:

public class MainWindowViewModel
{
    private readonly IWindowService _windowService;

    public MainWindowViewModel(IWindowService windowService)
    {
        _windowService = windowService;
        AddProfile = new DelegateCommand(() =>
        {
            _windowService.OpenProfileWindow(new AddProfileViewModel());
        });
    }

    public ICommand AddProfile { get; }
}

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new MainWindowViewModel(new WindowService());
    }
}

public class WindowService : IWindowService
{
    public void OpenProfileWindow(AddProfileViewModel vm)
    {
        AddProfileWindow win = new AddProfileWindow();
        win.DataContext = vm;
        win.Show();
    }
}


问:
How do I read a file into a matrix in bash?
I have a text file like this

```<code>A;green;3
B;blue;2
A;red;4
C;red;2
C;blue;3
B;green;3
</code>```

I have to write a script that if started with parameter "B" gives me the color of the row with the biggest number (from the rows starting with B). In this case it would be the last line, so the output would be "green".

How do I separate the elements by ";"-s and newlines and store them into a matrix so I can work with it? Do I even need to do that, or is there an easier solution?

Thanks in advance!

答:
awk + sort solution:

```<code>awk -v param="B" -F';' '$1==param{ print $2; exit }' <(sort -t';' -k1,1 -k3nr file.txt)
</code>```

The output:

```<code>green
</code>```

Or in addition to @William Pursell's answer - to extract only color value:

```<code>awk -F';' '/^B/ && $3>m{ m=$3; c=$2 }END{ print c }' file.txt
green
</code>```

Via bash script:

get_max_color.sh script:

```<code>#!/bin/bash

awk -F';' -v p="$1" '$0~"^"p && $3>m{ m=$3; c=$2 }END{ print c }' "$2"
</code>```

Usage:

```<code>bash get_max_color.sh B "file.txt"
green
</code>```

Body:
I have a text file like this

A;green;3
B;blue;2
A;red;4
C;red;2
C;blue;3
B;green;3

I have to write a script that if started with parameter "B" gives me the color of the row with the biggest number (from the rows starting with B). In this case it would be the last line, so the output would be "green".

How do I separate the elements by ";"-s and newlines and store them into a matrix so I can work with it? Do I even need to do that, or is there an easier solution?

Thanks in advance!

Body:
awk + sort solution:

awk -v param="B" -F';' '$1==param{ print $2; exit }' <(sort -t';' -k1,1 -k3nr file.txt)

The output:

green

Or in addition to @William Pursell's answer - to extract only color value:

awk -F';' '/^B/ && $3>m{ m=$3; c=$2 }END{ print c }' file.txt
green

Via bash script:

get_max_color.sh script:

#!/bin/bash

awk -F';' -v p="$1" '$0~"^"p && $3>m{ m=$3; c=$2 }END{ print c }' "$2"

Usage:

bash get_max_color.sh B "file.txt"
green


问:
How can I return an object from a ArrayList?
I would like to return the Host thats have the same domain as the Host in the List. But it gives me and error: "This method have to return a type of Host".

How I have to return the object Host?

```<code>public class Manager {

private List<Host> hosts = new ArrayList<Host>();

public Host getHost (String domain) {

      for(int i = 0; i < hosts.size(); i++) {
          if(domain == hosts.get(i).getDomain()) {
              return hosts.get(i);
          }}
  }
</code>```

Thanks.

答:
Could it be because the last line in your method is not a return? Maybe try this:</p>

```<code>public Host getHost (String domain) {
      Host host = null;
      for(int i = 0; i < hosts.size(); i++) {
          if(domain.equals(hosts.get(i).getDomain())) {
              //saves in the variable declared outside of for
              host = hosts.get(i);
          }
      }
      //attention: if nothing is found in your arraylist, the returned object is refers to null
      return host;
  }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I would like to return the Host thats have the same domain as the Host in the List. But it gives me and error: "This method have to return a type of Host".

How I have to return the object Host?

public class Manager {

private List<Host> hosts = new ArrayList<Host>();

public Host getHost (String domain) {

      for(int i = 0; i < hosts.size(); i++) {
          if(domain == hosts.get(i).getDomain()) {
              return hosts.get(i);
          }}
  }

Thanks.

Body:
Could it be because the last line in your method is not a return? Maybe try this:

public Host getHost (String domain) {
      Host host = null;
      for(int i = 0; i < hosts.size(); i++) {
          if(domain.equals(hosts.get(i).getDomain())) {
              //saves in the variable declared outside of for
              host = hosts.get(i);
          }
      }
      //attention: if nothing is found in your arraylist, the returned object is refers to null
      return host;
  }


问:
Python style question: Support class as inner class?
I like to use the structures built into the language to organize my code. But there is one situation where I can't stay consistent, simply because I don't see a definitive best way of doing it. It's regarding support classes, that is, classes that are exclusively used internally by another class: Do I make them inner classes, or separate classes.

Inner classes:

```<code>class Complicated:
    class Utility1:
        pass
    class Utility2:
        pass
    pass
</code>```

Separate classes:

```<code>class Complicated:
    pass

class Utility1:
    pass

class Utility2:
    pass
</code>```

Inner classes has the advantage of being scoped inside the only class that uses them. But the problem is that I get less space to write code due to indentation.

Outer classes have neither the advantage nor the disadvantage. I am tired of always spending some mental energy whenever I write support classes, wondering about this silly issue.

My question is whether anyone with a substantial python experience on their back can advise as to whether there is a best practice regarding this? Even if the answer is that "it depends", it is appreciated if it comes with someone more experienced than myself.

答:
Whether I use an inner class or outer class largely depends on whether I expect to override the type, either in a subclass or on a per-instance basis:

```<code>class Foo(object):
    normalize = str

    def process(self, input):
        # Do some stuff in here...
        return self.normalize(output)

class UniFoo(Foo):
    normalize = unicode

class TotallyMungedFoo(Foo):
    class normalize(object): ...
</code>```

If I don't expect to need (or explicitly don't want) behavior like this, I use classes in the same module, but only include the "important" one in my __all__ declaration.

ContentLicense: CC BY-SA 2.5

Body:
I like to use the structures built into the language to organize my code. But there is one situation where I can't stay consistent, simply because I don't see a definitive best way of doing it. It's regarding support classes, that is, classes that are exclusively used internally by another class: Do I make them inner classes, or separate classes.

Inner classes:

class Complicated:
    class Utility1:
        pass
    class Utility2:
        pass
    pass

Separate classes:

class Complicated:
    pass

class Utility1:
    pass

class Utility2:
    pass

Inner classes has the advantage of being scoped inside the only class that uses them. But the problem is that I get less space to write code due to indentation.

Outer classes have neither the advantage nor the disadvantage. I am tired of always spending some mental energy whenever I write support classes, wondering about this silly issue.

My question is whether anyone with a substantial python experience on their back can advise as to whether there is a best practice regarding this? Even if the answer is that "it depends", it is appreciated if it comes with someone more experienced than myself.

Body:
Whether I use an inner class or outer class largely depends on whether I expect to override the type, either in a subclass or on a per-instance basis:

class Foo(object):
    normalize = str

    def process(self, input):
        # Do some stuff in here...
        return self.normalize(output)

class UniFoo(Foo):
    normalize = unicode

class TotallyMungedFoo(Foo):
    class normalize(object): ...

If I don't expect to need (or explicitly don't want) behavior like this, I use classes in the same module, but only include the "important" one in my __all__ declaration.


问:
Execute immediate UPDATE Statement
I try to make an update table CHECK_COMPRESSER into PROCEDURE and I use EXECUTE IMMEDIATE :

```<code>EXECUTE immediate 'update CHECK_COMPRESSER
set NEW_SIZE_MB = '||''''||TABLE_P_ENTRY.NEW_SIZE_MB || '''' ||
 ' WHERE EXEC_ID = ' || '''' || EXEC_ID || '''' || ' AND TABLE = ' || '''' || TABLE_P_ENTRY.SEGMENT_NAME || '''' || ' AND PARTITION = ' || '''' || TABLE_P_ENTRY.PARTITION_NAME || '''';
</code>```

dbms_output.put_line shows:

```<code>update CHECK_COMPRESSER set NEW_SIZE_MB = '182' WHERE EXEC_ID = '43' AND TABLE = 'MA_CONTACT_COMPRESS' AND PARTITION = 'P_OLD'
</code>```

but there is an error:

ORA-00936: missing expression ORA-06512: at "SASDBA.COMPRESS_TABLE",
  line 50

so, how should I edit this code?

答:
TABLE is a keyword. It can be used as identifier only if quoted: "TABLE".

P.S. PARTITION is the same.

Title: Execute immediate UPDATE Statement

Body:
I try to make an update table CHECK_COMPRESSER into PROCEDURE and I use EXECUTE IMMEDIATE :

EXECUTE immediate 'update CHECK_COMPRESSER
set NEW_SIZE_MB = '||''''||TABLE_P_ENTRY.NEW_SIZE_MB || '''' ||
 ' WHERE EXEC_ID = ' || '''' || EXEC_ID || '''' || ' AND TABLE = ' || '''' || TABLE_P_ENTRY.SEGMENT_NAME || '''' || ' AND PARTITION = ' || '''' || TABLE_P_ENTRY.PARTITION_NAME || '''';

dbms_output.put_line shows:

update CHECK_COMPRESSER set NEW_SIZE_MB = '182' WHERE EXEC_ID = '43' AND TABLE = 'MA_CONTACT_COMPRESS' AND PARTITION = 'P_OLD'

but there is an error:

ORA-00936: missing expression ORA-06512: at "SASDBA.COMPRESS_TABLE",
  line 50

so, how should I edit this code?


问:
AngularJS - Override CSS
I've inherited an AngularJS project which uses the 3rd party grid, Ag-grid.  There is an ag-grid-style.css file that has the following:

```<code>.ag-pinned-left-header.hasCategoryCol .ag-header-cell, .ag-pinned-left-cols-viewport.hasCategoryCol .ag-row .ag-cell {
    width: calc(100% / 7) !important;
}
</code>```

This works great for the grid already in use, the grid is nicely divided into 7 columns.
My problem is I have created new code, also using ag-grid, but I need the new grid divided into 6 columns, not 7.  I end up with one extra empty column.  Using Chrome for debugging and going into the developer tools, I can see the above CSS and if I change the 7 to a 6, my grid displays perfectly.  My question is what is the easiest way to accomplish what I want?  I've been trying to adjust the styling in code but haven't succeeded yet.  Suggestions?

答:
@Adosi's answer is the preferred solution -- CSS after all refers to cascading style sheets. If, however, you cannot modify the load order of your styles, the following is an alternative solution.

You can override a rule defined in an external stylesheet that has a !important attribute by adding your own definition inline to the element itself. I have demonstrated here using the background-color property as it is more obvious.

#foo {
  background-color: pink !important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="foo" style="background-color: cyan !important;">This paragraph has id foo.</p></code>```

The inline style will always take precedence -- eg be loaded last -- so the color defined there is the one that is displayed.

Note that this is not considered a good practice, but I indicate it as an alternative if you are unable to load a CSS rule after your third party asset. (You may wish to log a bug with the 3rd party library because the !important annotation should be used sparingly and in this case probably not at all.)

Title: AngularJS - Override CSS

Body:
I've inherited an AngularJS project which uses the 3rd party grid, Ag-grid.  There is an ag-grid-style.css file that has the following:

.ag-pinned-left-header.hasCategoryCol .ag-header-cell, .ag-pinned-left-cols-viewport.hasCategoryCol .ag-row .ag-cell {
    width: calc(100% / 7) !important;
}

This works great for the grid already in use, the grid is nicely divided into 7 columns.
My problem is I have created new code, also using ag-grid, but I need the new grid divided into 6 columns, not 7.  I end up with one extra empty column.  Using Chrome for debugging and going into the developer tools, I can see the above CSS and if I change the 7 to a 6, my grid displays perfectly.  My question is what is the easiest way to accomplish what I want?  I've been trying to adjust the styling in code but haven't succeeded yet.  Suggestions?

Body:
@Adosi's answer is the preferred solution -- CSS after all refers to cascading style sheets. If, however, you cannot modify the load order of your styles, the following is an alternative solution.

You can override a rule defined in an external stylesheet that has a !important attribute by adding your own definition inline to the element itself. I have demonstrated here using the background-color property as it is more obvious.

#foo {
  background-color: pink !important;
}

<p id="foo" style="background-color: cyan !important;">This paragraph has id foo.</p>

The inline style will always take precedence -- eg be loaded last -- so the color defined there is the one that is displayed.

Note that this is not considered a good practice, but I indicate it as an alternative if you are unable to load a CSS rule after your third party asset. (You may wish to log a bug with the 3rd party library because the !important annotation should be used sparingly and in this case probably not at all.)


问:
How to secure .env file in laravel using file permission?
My env file which has all the credentials is accessible through URL.
I found a few questions like How to secure .env file in laravel 5.4? which says to use htaccess to prevent users from accessing the file.

But I prefer using file permission so I changed permission to 0111 which is execute only but I found that the file is not accessible by the internal files as well so my question is what is the right permission.

And is it fine to depend on file permission for security purpose.

答:
I hope it will work for you.

add this code in .htaccess file

```<code><Files .env>
  Order allow,deny
    Deny from all
</Files>
</code>```

Body:
I hope it will work for you.

add this code in .htaccess file

<Files .env>
  Order allow,deny
    Deny from all
</Files>


问:
Extract string from custom object on listView item click
I have created my own class (Course) to hold multiple strings and pass the object to populate a list using ArrayAdapter and AsyncTaskLoader (the strings are being filled from a JSON api).

Let's say I have these 3 Strings inside my class:

```<code>private String mCourseTitle;
private String mTime;
private String mTrainer;

public String getCourseTitle() {
    return mCourseTitle;
}

public String getTime() {
    return mTime;
}

public String getTrainer() {
    return mTrainer;
}
</code>```

I want to set up an item click listener inside my Fragment that when tapped, shows a toast message with only the Course Title String and I'm kinda stuck...

How do I extract the title to show it in a Toast from the clicked item?

```<code> // Create a new adapter that takes an empty list of days as input
        mAdapter = new DayAdapter(getActivity(), new ArrayList<Day>());

        // Set the adapter on the {@link ListView}
        // so the list can be populated in the user interface
        listView.setAdapter(mAdapter);

        //on item click Listener
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                // Show the title
                Toast.makeText(getContext(), Title, Toast.LENGTH_SHORT).show();
            }
        });
</code>```

答:
Here is the answer </p>

```<code> //on item click Listener
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
             Course yourCourse = yourList.get(position);
              String yourCourseTitle = yourCourse.getCourseTitle();
            // Show the title
            Toast.makeText(getContext(), Title, Toast.LENGTH_SHORT).show();
        }
    });
</code>```

Body:
I have created my own class (Course) to hold multiple strings and pass the object to populate a list using ArrayAdapter and AsyncTaskLoader (the strings are being filled from a JSON api).

Let's say I have these 3 Strings inside my class:

private String mCourseTitle;
private String mTime;
private String mTrainer;

public String getCourseTitle() {
    return mCourseTitle;
}

public String getTime() {
    return mTime;
}

public String getTrainer() {
    return mTrainer;
}

I want to set up an item click listener inside my Fragment that when tapped, shows a toast message with only the Course Title String and I'm kinda stuck...

How do I extract the title to show it in a Toast from the clicked item?

 // Create a new adapter that takes an empty list of days as input
        mAdapter = new DayAdapter(getActivity(), new ArrayList<Day>());

        // Set the adapter on the {@link ListView}
        // so the list can be populated in the user interface
        listView.setAdapter(mAdapter);

        //on item click Listener
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                // Show the title
                Toast.makeText(getContext(), Title, Toast.LENGTH_SHORT).show();
            }
        });

Body:
Here is the answer

 //on item click Listener
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
             Course yourCourse = yourList.get(position);
              String yourCourseTitle = yourCourse.getCourseTitle();
            // Show the title
            Toast.makeText(getContext(), Title, Toast.LENGTH_SHORT).show();
        }
    });


问:
Export Sharepoint list to .csv and upload to Azure Data Lake Using Flow
I am trying to using Microsoft Flow to export a Sharepoint List to Azure Data Lake.

I want it so that anytime a particular online list is changed, its entire contents are loaded into a file in Data Lake. If the file already exists, I want to overwrite it. Can someone please explain how I can go about doing this, I have tried multiple ways, but they are not getting the job done.

Thanks

答:
I was able to get the items in the SharePoint list to near perfection. I will post the Flow here in case anyone in the future needs it.

So what I did is that every 5 minutes I "create" a file in Azure Data Lake which overwrites the file if it exists. The content of the files cannot be blank, so I added a newline to the content. Then I use Get Items to retrieve all the items in the SharePoint List. From there, using an Apply to each loop, I append the content of the current row of the Sharepoint list to the Data Lake file (separated by | and ending with a new line after all the content is added). This works to near perfection, with the only caveat being the newline at the beginning of the file, which I eliminate using PowerQuery.

This is exactly what I needed. If anybody sees a way to make this better, please post so that we can get this to perfection.


问:
Simply Restful Routing
Why would you want to use something like Simply Restful Routing from MVCContrib?  When creating a new item, why would you want an action method called New and an action method to handle the post request called Create?  Why not just create 2 methods called Create?  The same goes with edit and delete.</p>

答:
Why not just create to methods called Create?

It's more a convention than anything else. People working with RESTful systems are used to it. So someone/something not familiar with your application and willing to create a new item will GET /item/new because that's the convention. If you used Create he will need to contact you, read your documentation, ... in order to discover this because you have not used standard convention in your application.

Title: Simply Restful Routing


问:
Can't pass search term as parameter
I want to display some data in a dropdown and implement autocomplete. In order to do that I'm using select2, a jQuery plugin.
My problem is that the search term written in the search box is not being passed as parameter to my method in the controller . This is my ajax request:

```<code>$('#someId').select2({
        minimumInputLength: 1,
        allowClear: true,

        ajax: {
            url: "/controllerName/methodName",
            dataType: "json",
            type: "GET",
            data: function (params) {

                var queryParameters = {
                    term: params.term

                }
                return queryParameters;

            },

            processResults: function (data) {
                return {
                    results: $.map(data, function (students) {
                        return {
                            text: students.name,
                            id: students.id
                        }
                    })
                };
            }
        }
    });
</code>```

And this is the html:

```<code><div class="form-group">
<label asp-for="someId" class="col-md-2 control-label"></label>
 <div class="col-md-4">
<select asp-for="someId"  class="form-control" style="display:table-cell;
 width:100%"></select>
 </div>
 </div>
</code>```

This is my method in controller:

```<code>[HttpGet]
        public IActionResult GetStudents(string searchTerm)
    {
        //some code
    }
</code>```

Is there anything wrong in my Ajax request?

答:
You are sending a variable called "term" as your search parameter. But your controller is expecting a variable called "searchTerm".

The variable names need to match, otherwise how should the controller know what to pick out from the querystring?

Especially consider the very-common situation where there are multiple parameters being sent from the browser. At that point it's critical there is a naming convention so the correct parameters are matched to the correct variable in the controller method.

Title: Can't pass search term as parameter

Body:
I want to display some data in a dropdown and implement autocomplete. In order to do that I'm using select2, a jQuery plugin.
My problem is that the search term written in the search box is not being passed as parameter to my method in the controller . This is my ajax request:

$('#someId').select2({
        minimumInputLength: 1,
        allowClear: true,

        ajax: {
            url: "/controllerName/methodName",
            dataType: "json",
            type: "GET",
            data: function (params) {

                var queryParameters = {
                    term: params.term

                }
                return queryParameters;

            },

            processResults: function (data) {
                return {
                    results: $.map(data, function (students) {
                        return {
                            text: students.name,
                            id: students.id
                        }
                    })
                };
            }
        }
    });

And this is the html:

<select asp-for="someId"  class="form-control" style="display:table-cell;
 width:100%"></select>

This is my method in controller:

[HttpGet]
        public IActionResult GetStudents(string searchTerm)
    {
        //some code
    }

Is there anything wrong in my Ajax request?


问:
Translate Qt QML application on the fly
I'm trying to translate a qt QML application that is filled with </p>

```<code>tr("string");
</code>```

<p>All over the place, If I set the translator before the app starts it works perfectly, but I'm having troubles doing it on the fly. The only solution seems to be the empty string hack but I dont want to search for every "tr" and add the empty string </p>

答:
Up to Qt 5.9, the easiest solution is to add an empty string to each translatable string: How to do dynamic translation in QML

From Qt 5.10, it is possible to retranslate all strings by calling: QQmlEngine::retranslate

More information can be found in the QtQuick Internationalization documentation:

You can change the language that Qt translation functions use by
  adding and removing translators with
  QCoreApplication::installTranslator() and
  QCoreApplication::removeTranslator(). Afterwards you can call
  QQmlEngine::retranslate() to trigger a refresh of all bindings that
  use translations. As a result, your user interface will switch,
  dynamically, to the newly selected language.

Alternatively, you can also forward a QEvent::LanguageChange event to
  your application's QQmlEngine instance or connect your own signal to QQmlEngine::retranslate().

Note that at the time of writing, only beta releases of Qt 5.10 are available.

Title: Translate Qt QML application on the fly

Body:
I'm trying to translate a qt QML application that is filled with

tr("string");

All over the place, If I set the translator before the app starts it works perfectly, but I'm having troubles doing it on the fly. The only solution seems to be the empty string hack but I dont want to search for every "tr" and add the empty string


问:
Using same column multiple times in WHERE clause
I have a following table structure.

USERS

PROPERTY_VALUE

PROPERTY_NAME

USER_PROPERTY_MAP

I am trying to retrieve user/s from the users table who have matching properties in property_value table.

A single user can have multiple properties. The example data here has 2 properties for user '1', but there can be more than 2. I want to use all those user properties in the WHERE clause.

This query works if user has a single property but it fails for more than 1 properties:

```<code>SELECT * FROM users u
INNER JOIN user_property_map upm ON u.id = upm.user_id
INNER JOIN property_value pv ON upm.property_value_id = pv.id
INNER JOIN property_name pn ON pv.property_name_id = pn.id
WHERE (pn.id = 1 AND pv.id IN (SELECT id FROM property_value WHERE value like '101')
AND pn.id = 2 AND pv.id IN (SELECT id FROM property_value WHERE value like '102')) and u.user_name = 'user1' and u.city = 'city1'
</code>```

I understand since the query has pn.id = 1 AND pn.id = 2 it will always fail because pn.id can be either 1 or 2 but not both at the same time. So how can I re-write it to make it work for n number of properties?

In above example data there is only one user with id = 1 that has both matching properties used in the WHERE clause. The query should return a single record with all columns of the USERS table.

To clarify my requirements

I am working on an application that has a users list page on the UI listing all users in the system. This list has information like user id, user name, city etc. - all columns of the in USERS table. Users can have properties as detailed in the database model above.

The users list page also provides functionality to search users based on these properties. When searching for users with 2 properties, 'property1' and 'property2', the page should fetch and display only matching rows. Based on the test data above, only user '1' fits the bill.

A user with 4 properties including 'property1' and 'property2' qualifies. But a user with only one property 'property1' would be excluded due to the missing 'property2'.

答:
If you just want the distinct columns in U, it is:

```<code>SELECT DISTINCT u.*
  FROM Users u INNER JOIN USER_PROPERTY_MAP upm ON u.id = upm.[user_id]
                INNER JOIN PROPERTY_VALUE pv ON upm.property_value_id = pv.id
                INNER JOIN PROPERTY_NAME pn ON pv.property_name_id = pn.id

  WHERE (pn.id = 1 AND pv.[value] = '101')
     OR (pn.id = 2 AND pv.[value] = '102')
</code>```

Notice I used pv.[value] = instead of the subquery to reacquire id... this is simplification.

Body:
I have a following table structure.

USERS

PROPERTY_VALUE

PROPERTY_NAME

USER_PROPERTY_MAP

I am trying to retrieve user/s from the users table who have matching properties in property_value table.

A single user can have multiple properties. The example data here has 2 properties for user '1', but there can be more than 2. I want to use all those user properties in the WHERE clause.

This query works if user has a single property but it fails for more than 1 properties:

SELECT * FROM users u
INNER JOIN user_property_map upm ON u.id = upm.user_id
INNER JOIN property_value pv ON upm.property_value_id = pv.id
INNER JOIN property_name pn ON pv.property_name_id = pn.id
WHERE (pn.id = 1 AND pv.id IN (SELECT id FROM property_value WHERE value like '101')
AND pn.id = 2 AND pv.id IN (SELECT id FROM property_value WHERE value like '102')) and u.user_name = 'user1' and u.city = 'city1'

I understand since the query has pn.id = 1 AND pn.id = 2 it will always fail because pn.id can be either 1 or 2 but not both at the same time. So how can I re-write it to make it work for n number of properties?

In above example data there is only one user with id = 1 that has both matching properties used in the WHERE clause. The query should return a single record with all columns of the USERS table.

To clarify my requirements

I am working on an application that has a users list page on the UI listing all users in the system. This list has information like user id, user name, city etc. - all columns of the in USERS table. Users can have properties as detailed in the database model above.

The users list page also provides functionality to search users based on these properties. When searching for users with 2 properties, 'property1' and 'property2', the page should fetch and display only matching rows. Based on the test data above, only user '1' fits the bill.

A user with 4 properties including 'property1' and 'property2' qualifies. But a user with only one property 'property1' would be excluded due to the missing 'property2'.

Body:
If you just want the distinct columns in U, it is:

SELECT DISTINCT u.*
  FROM Users u INNER JOIN USER_PROPERTY_MAP upm ON u.id = upm.[user_id]
                INNER JOIN PROPERTY_VALUE pv ON upm.property_value_id = pv.id
                INNER JOIN PROPERTY_NAME pn ON pv.property_name_id = pn.id

  WHERE (pn.id = 1 AND pv.[value] = '101')
     OR (pn.id = 2 AND pv.[value] = '102')

Notice I used pv.[value] = instead of the subquery to reacquire id... this is simplification.


问:
Running a script with upstart server in ubuntu 14.04
I have a script named rotate.sh. After chmod +x rotate.sh, I can run it with the command /home/lin/Desktop/rotate.sh, and my screen will rotate left.

rotate.sh:

```<code>#!/bin/bash
xrandr --output VGA1 --rotate left
</code>```

Then I write a upstart job named testOne, located in /etc/init/testOne.conf.

testOne.conf:

```<code>description "test upstart job"
author "Lin a@i.com"

start on filesystem or runlevel [2345]
start on desktop-session-start
stop on shutdown

pre-start script
    mkdir -p /home/lin/Desktop/test1
end script

respawn
respawn limit 15 5

script
    exec /home/lin/Desktop/rotate.sh
    cd /home/lin/Desktop/
    mkdir test2
end script
</code>```

But when I run sudo start testOne, it doesn't work. Only the pre-start works. What am I doing wrong?

答:
Perhaps changing this line

```<code>exec /home/lin/Desktop/rotate.sh
</code>```

to

```<code>exec /home/lin/Desktop/rotate.sh start
</code>```

would help. As an alternative, you can also use exec stanzas instead of simple cases, in which case, it would be something like this

```<code>exec bash -c '/home/lin/Desktop/rotate.sh start'
</code>```

Check out some reference here on upstart and how to work with it: http://upstart.ubuntu.com/cookbook/#id300

Body:
I have a script named rotate.sh. After chmod +x rotate.sh, I can run it with the command /home/lin/Desktop/rotate.sh, and my screen will rotate left.

rotate.sh:

#!/bin/bash
xrandr --output VGA1 --rotate left

Then I write a upstart job named testOne, located in /etc/init/testOne.conf.

testOne.conf:

description "test upstart job"
author "Lin a@i.com"

start on filesystem or runlevel [2345]
start on desktop-session-start
stop on shutdown

pre-start script
    mkdir -p /home/lin/Desktop/test1
end script

respawn
respawn limit 15 5

script
    exec /home/lin/Desktop/rotate.sh
    cd /home/lin/Desktop/
    mkdir test2
end script

But when I run sudo start testOne, it doesn't work. Only the pre-start works. What am I doing wrong?

Body:
Perhaps changing this line

exec /home/lin/Desktop/rotate.sh

to

exec /home/lin/Desktop/rotate.sh start

would help. As an alternative, you can also use exec stanzas instead of simple cases, in which case, it would be something like this

exec bash -c '/home/lin/Desktop/rotate.sh start'

Check out some reference here on upstart and how to work with it: http://upstart.ubuntu.com/cookbook/#id300


答:
You just need to return null after your loop.

```<code>  public Host getHost (String domain) {
        for(int i = 0; i < hosts.size(); i++) {
            if(domain.equals(hosts.get(i).getDomain())) {
              return hosts.get(i);
            }
        }
        return null;
    }
</code>```

You can also throw an Exception if nothing found.

Title: How can I return an object from a ArrayList?

Body:
You just need to return null after your loop.

  public Host getHost (String domain) {
        for(int i = 0; i < hosts.size(); i++) {
            if(domain.equals(hosts.get(i).getDomain())) {
              return hosts.get(i);
            }
        }
        return null;
    }

You can also throw an Exception if nothing found.


问:
Spark ML Linear Regression - What Hyper-parameters to Tune
I'm using the LinearRegression model in the Spark ML for predicting price. It is a single variate regression (x=time, y=price).

Assume my data is clean, what are the usual steps to take to improve this model?

So far, I tried tuning regularization parameter using cross-validation, and got rmse=15 given stdev=30.

Are there any other significant hyper-parameters I should care about? It seems Spark ML is not well documented for hyper-parameter tuning...

Update

I was able to tune up parameters using ParamGrid and Cross-Validation. However, is there any way to see how the fitted line looks like after correctly training a linear regression model? How can I know if the line is quadric or cubic etc? It would be great if there is a way to visualize the fitted line with all training data points.

答:
val session = SparkSession.builder().master("local").appName("PredictiveAnalysis").getOrCreate();

```<code>def main(args: Array[String]): Unit = {

        val data = session.sparkContext.textFile("C:\\Users\\Test\\new_workspace\\PredictionAlgo\\src\\main\\resources\\data.txt");
        val parsedData = data.map { line =>
        val x : Array[String] = line.replace(",", " ").split(" ")
        val y = x.map{ (a => a.toDouble)}
        val d = y.size - 1
                val c = Vectors.dense(y(0),y(d))
                LabeledPoint(y(0), c)
        }.cache();
        val numIterations = 100;
        val stepSize = 0.00000001;
        val model = LinearRegressionWithSGD.train(parsedData, numIterations, stepSize);

        val valuesAndPreds = parsedData.map { point =>
        val prediction = model.predict(point.features)
        (point.label, prediction)
        }

        valuesAndPreds.foreach((result) => println(s"predicted label: ${result._1}, actual label: ${result._2}"))

        val MSE = valuesAndPreds.map{ case(v, p) => math.pow((v - p), 2) }.mean()
        println("training Mean Squared Error = " + MSE)
}
</code>```

}

Body:
val session = SparkSession.builder().master("local").appName("PredictiveAnalysis").getOrCreate();

def main(args: Array[String]): Unit = {

        val data = session.sparkContext.textFile("C:\\Users\\Test\\new_workspace\\PredictionAlgo\\src\\main\\resources\\data.txt");
        val parsedData = data.map { line =>
        val x : Array[String] = line.replace(",", " ").split(" ")
        val y = x.map{ (a => a.toDouble)}
        val d = y.size - 1
                val c = Vectors.dense(y(0),y(d))
                LabeledPoint(y(0), c)
        }.cache();
        val numIterations = 100;
        val stepSize = 0.00000001;
        val model = LinearRegressionWithSGD.train(parsedData, numIterations, stepSize);

        val valuesAndPreds = parsedData.map { point =>
        val prediction = model.predict(point.features)
        (point.label, prediction)
        }

        valuesAndPreds.foreach((result) => println(s"predicted label: ${result._1}, actual label: ${result._2}"))

        val MSE = valuesAndPreds.map{ case(v, p) => math.pow((v - p), 2) }.mean()
        println("training Mean Squared Error = " + MSE)
}

}


问:
Vaadin custom JS component refresh rate
I am using custom js components in vaadin 8 (followin this documentation : https://vaadin.com/docs/v8/framework/gwt/gwt-javascript.html)

And I have found a problem for my component : if I spam (by programmation) the setValue method server side in a thread with a 100ms sleep, the client side skip a lot of events because notification rate between the server side and the client side seems to be linked to the global vaadin refresh rate.

If there a way to make the js rcp calls to be faster without breaking everything else ?

Best regards.

答:
Ok, after enabling push extension, added @Push annotation to my UI, and using lock and push on my ui in my spam thread, the refresh rate is high as we are now using websocket.

I can send notifications in a loop with 10ms sleep between each notification without any problem.

Title: Vaadin custom JS component refresh rate


问:
ionic 2: ionic run android shows error
i have error when i run "ionic run android" or "ionic build android" in my ionic 2 app
this is the error i get. i just tryinh to see my app in the emulator of android.
i tried to make new ionic 2 project but it's the same problem.</p>

```<code>Running 'build:before' npm script before build
> ionic-hello-world@ build C:\Users\Adir\MyApps\tasklist
> ionic-app-scripts build --rollup ./config/rollup.config.js
[20:16:33]  ionic-app-scripts 0.0.30
[20:16:33]  build prod started ...
[20:16:33]  clean started ...
[20:16:33]  clean finished in 24 ms
[20:16:33]  copy started ...
[20:16:33]  ngc started ...
[20:16:33]  lint started ...
[20:16:33]  copy finished in 182 ms
[20:16:34]  lint finished in 770 ms
[20:16:52]  ngc finished in 18.71 s
[20:16:52]  bundle prod started ...
[20:16:52]  bundle prod failed:  Could not resolve entry (/app/main.prod.ts)

[20:16:52]  Error: Could not resolve entry (/app/main.prod.ts)
    at C:\Users\Adir\MyApps\tasklist\node_modules\rollup\dist\rollup.js:8635:28
    at process._tickCallback (internal/process/next_tick.js:103:7)

Error running ionic app script "build": Error: Could not resolve entry (/app/main.prod.ts)

npm
 ERR! Windows_NT 10.0.14393

npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "run" "build"
npm ERR! node v6.7.0
npm ERR! npm  v3.10.3
npm ERR! code ELIFECYCLE
npm ERR! ionic-hello-world@ build: `ionic-app-scripts build --rollup ./config/rollup.config.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the ionic-hello-world@ build script 'ionic-app-scripts build --rollup ./config/rollup.config.js'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the ionic-hello-world package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!
     ionic-app-scripts build --rollup ./config/rollup.config.js
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs ionic-hello-world
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls ionic-hello-world
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     C:\Users\Adir\MyApps\tasklist\npm-debug.log

Caught exception:
 undefined

Mind letting us know? https://github.com/driftyco/ionic-cli/issues

C:\Users\Adir\MyApps\tasklist>
</code>```

答: Close all ionic folders and serve or lab. And try again, ionic cordova build android.

Title: ionic 2: ionic run android shows error

Body:
i have error when i run "ionic run android" or "ionic build android" in my ionic 2 app
this is the error i get. i just tryinh to see my app in the emulator of android.
i tried to make new ionic 2 project but it's the same problem.

Running 'build:before' npm script before build
> ionic-hello-world@ build C:\Users\Adir\MyApps\tasklist
> ionic-app-scripts build --rollup ./config/rollup.config.js
[20:16:33]  ionic-app-scripts 0.0.30
[20:16:33]  build prod started ...
[20:16:33]  clean started ...
[20:16:33]  clean finished in 24 ms
[20:16:33]  copy started ...
[20:16:33]  ngc started ...
[20:16:33]  lint started ...
[20:16:33]  copy finished in 182 ms
[20:16:34]  lint finished in 770 ms
[20:16:52]  ngc finished in 18.71 s
[20:16:52]  bundle prod started ...
[20:16:52]  bundle prod failed:  Could not resolve entry (/app/main.prod.ts)

[20:16:52]  Error: Could not resolve entry (/app/main.prod.ts)
    at C:\Users\Adir\MyApps\tasklist\node_modules\rollup\dist\rollup.js:8635:28
    at process._tickCallback (internal/process/next_tick.js:103:7)

Error running ionic app script "build": Error: Could not resolve entry (/app/main.prod.ts)

npm
 ERR! Windows_NT 10.0.14393

npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "run" "build"
npm ERR! node v6.7.0
npm ERR! npm  v3.10.3
npm ERR! code ELIFECYCLE
npm ERR! ionic-hello-world@ build: `ionic-app-scripts build --rollup ./config/rollup.config.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the ionic-hello-world@ build script 'ionic-app-scripts build --rollup ./config/rollup.config.js'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the ionic-hello-world package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!
     ionic-app-scripts build --rollup ./config/rollup.config.js
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs ionic-hello-world
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls ionic-hello-world
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     C:\Users\Adir\MyApps\tasklist\npm-debug.log

Caught exception:
 undefined

Mind letting us know? https://github.com/driftyco/ionic-cli/issues

C:\Users\Adir\MyApps\tasklist>


问:
XSL: Manipulating a node while applying its descendant templates
I work with XML text editions, where text nodes often appear alongside element nodes. For instance, <w> word elements contain text nodes but may also contain further formatting, e.g. to signal abbreviations, which are contained in <choice> environments:

```<code><s><w>Any</w> <w>sentence</w> <w>may</w> <w>contain</w> <w>an</w> <w><choice>
 <abbr>abbr<am>.</am></abbr>
 <expan>abbr<ex>eviation</ex></expan></choice></w>.</s>
</code>```

The source manuscripts often use word spacing that differs from where we would conventionally place our spaces. This manuscript word spacing is preserved within <w> word element tags, so a case of odd spacing could be <w>ele phant</w>. My XSL stylesheet is applied using a parameter to signal whether the current operation wants to output manuscript spacing ("ele phant") or lexical word spacing ("elephant").

My question: how do I conditionally remove spacing from within <w> nodes and make sure all descendant templates are still applied?

To clarify, the following will not work:

<xsl:strip-space>: this function cannot be applied conditionally. I need to build in an if-clause to check whether the normalization parameter is active, but strip-space is only allowed at the document's top level.

<xsl:value-of> in an environment like the following:

```<code><xsl:template match="w">
 <xsl:choose>
  <xsl:when test="contains($display, 'normalized')">
   <xsl:value-of select="translate(., ' ', '')"/>
  </xsl:when>
  <xsl:otherwise>
   <xsl:apply-templates/>
  </xsl:otherwise>
 </xsl:choose>
</xsl:template>
</code>```

The issue with my syntax here is that templates written for descendants are ignored, so that, for instance, a <choice> environment like the one in the first code block above outputs both the abbreviation and its expansion rather than one or the other.

Finally, xsl:apply-templates, which ensures the recursion lacking from the example with xsl:value-of, does not allow syntax like translate in its select attribute value.

How can I remove all spacing from the content of <w> nodes if a condition like the one in the xsl:value-of example is met, but still have it apply the templates of any descendant nodes?

Using XSLT 2.0.

答:
I am not very confident in transcribing original spacings with whitespace characters. If you want to document odd word or letter spacing, maybe you should think about a more explicit method. For example, there is <tei:space>. The odd spacing of <w>ele phant</w> would then be transcribed as <w>ele<space/>phant</w>. Additionally, you can describe how wide the space actually is, with @quantity and @unit. Such an element is much easier and more reliable to process with XSL than a (whitespace) character.

If you want to stick with the whitespace method, which I still consider legitimate nonetheless, Martin Honnen already gave a valid and solid approach. To expand on that, I would combine it with @mode, instead of querying $displayon each single node:

```<code><xsl:template match="w//text()" mode="normalizeSpace">
    <xsl:value-of select="translate(.,' ','')"/>
</xsl:template>
</code>```

and instead call it from your main template like that:

```<code><xsl:choose>
    <xsl:when test="contains($display, 'normalized')">
        <xsl:apply-templates mode="normalizeSpace"/>
    </xsl:when>
    <xsl:otherwise>
        <xsl:apply-templates/>
    </xsl:otherwise>
</xsl:choose>
</code>```

This would give you a greater flexibility to define other post-processing routines, and probably a better performance as well.

Body:
I work with XML text editions, where text nodes often appear alongside element nodes. For instance, <w> word elements contain text nodes but may also contain further formatting, e.g. to signal abbreviations, which are contained in <choice> environments:

<s><w>Any</w> <w>sentence</w> <w>may</w> <w>contain</w> <w>an</w> <w><choice>
 abbr<am>.</am>
 <expan>abbr<ex>eviation</ex></expan></choice></w>.</s>

The source manuscripts often use word spacing that differs from where we would conventionally place our spaces. This manuscript word spacing is preserved within <w> word element tags, so a case of odd spacing could be <w>ele phant</w>. My XSL stylesheet is applied using a parameter to signal whether the current operation wants to output manuscript spacing ("ele phant") or lexical word spacing ("elephant").

My question: how do I conditionally remove spacing from within <w> nodes and make sure all descendant templates are still applied?

To clarify, the following will not work:

<xsl:strip-space>: this function cannot be applied conditionally. I need to build in an if-clause to check whether the normalization parameter is active, but strip-space is only allowed at the document's top level.

<xsl:value-of> in an environment like the following:

<xsl:template match="w">
 <xsl:choose>
  <xsl:when test="contains($display, 'normalized')">
   <xsl:value-of select="translate(., ' ', '')"/>
  </xsl:when>
  <xsl:otherwise>
   <xsl:apply-templates/>
  </xsl:otherwise>
 </xsl:choose>
</xsl:template>

The issue with my syntax here is that templates written for descendants are ignored, so that, for instance, a <choice> environment like the one in the first code block above outputs both the abbreviation and its expansion rather than one or the other.

Finally, xsl:apply-templates, which ensures the recursion lacking from the example with xsl:value-of, does not allow syntax like translate in its select attribute value.

How can I remove all spacing from the content of <w> nodes if a condition like the one in the xsl:value-of example is met, but still have it apply the templates of any descendant nodes?

Using XSLT 2.0.

Body:
I am not very confident in transcribing original spacings with whitespace characters. If you want to document odd word or letter spacing, maybe you should think about a more explicit method. For example, there is <tei:space>. The odd spacing of <w>ele phant</w> would then be transcribed as <w>ele<space/>phant</w>. Additionally, you can describe how wide the space actually is, with @quantity and @unit. Such an element is much easier and more reliable to process with XSL than a (whitespace) character.

If you want to stick with the whitespace method, which I still consider legitimate nonetheless, Martin Honnen already gave a valid and solid approach. To expand on that, I would combine it with @mode, instead of querying $displayon each single node:

<xsl:template match="w//text()" mode="normalizeSpace">
    <xsl:value-of select="translate(.,' ','')"/>
</xsl:template>

and instead call it from your main template like that:

<xsl:choose>
    <xsl:when test="contains($display, 'normalized')">
        <xsl:apply-templates mode="normalizeSpace"/>
    </xsl:when>
    <xsl:otherwise>
        <xsl:apply-templates/>
    </xsl:otherwise>
</xsl:choose>

This would give you a greater flexibility to define other post-processing routines, and probably a better performance as well.


问:
How do I read a file into a matrix in bash?
I have a text file like this

```<code>A;green;3
B;blue;2
A;red;4
C;red;2
C;blue;3
B;green;3
</code>```

I have to write a script that if started with parameter "B" gives me the color of the row with the biggest number (from the rows starting with B). In this case it would be the last line, so the output would be "green".

How do I separate the elements by ";"-s and newlines and store them into a matrix so I can work with it? Do I even need to do that, or is there an easier solution?

Thanks in advance!

答:
You just need to filter out the appropriate lines and store the one with the max value seen.  The obvious solution is:

```<code>awk '/^B/ && $3 > m{s=$0} END { print s}' FS=\; input
</code>```

To use a parameter, do

```<code>awk "/^$1/"' && $3 > m{s=$0} END { print s}' FS=\; input
</code>```

Body:
I have a text file like this

A;green;3
B;blue;2
A;red;4
C;red;2
C;blue;3
B;green;3

I have to write a script that if started with parameter "B" gives me the color of the row with the biggest number (from the rows starting with B). In this case it would be the last line, so the output would be "green".

How do I separate the elements by ";"-s and newlines and store them into a matrix so I can work with it? Do I even need to do that, or is there an easier solution?

Thanks in advance!

Body:
You just need to filter out the appropriate lines and store the one with the max value seen.  The obvious solution is:

awk '/^B/ && $3 > m{s=$0} END { print s}' FS=\; input

To use a parameter, do

awk "/^$1/"' && $3 > m{s=$0} END { print s}' FS=\; input


问:
Get Previous and day before Previous date in batch file(cmd)
I have the following to determine the date and grab a file based on date. I need to modify this grab a file that has a date of yesterday and day before yesterday, i.e. date-1 and date-2. What do I need to change? Thanks!</p>

```<code>echo @echo off > uploadsp.txt
set mydate=%date:~10,4%%date:~4,2%%date:~7,2%
echo set mydate=%date:~10,4%%date:~4,2%%date:~7,2% >> uploadsp.txt

set myfile=Epic_DSH360144_Drug_Utilization_%mydate%_DU.txt
echo put %myfile% >> uploadsp.txt
exit
</code>```

答:
This should do the trick.</p>

```<code>@echo off
set nd=-1
set nd=-2
set mydate=%date:~10,4%%date:~4,2%%date:~7,2%
echo mydate=%date:~10,4%%date:~4,2%%date:~7,2%

echo s=DateAdd("d",%nd%,now) : d=weekday(s) >"%temp%\%~n1.vbs"
echo WScript.Echo year(s)^& right(100+month(s),2)^& right(100+day(s),2) >>"%temp%\%~n1.vbs"
for /f %%a in ('cscript /nologo "%temp%\%~n1.vbs"') do set "result=%%a"
del "%temp%\%~n1.vbs"
set yday=%result%

echo s=DateAdd("d",%nd%,now) : d=weekday(s) >"%temp%\%~n2.vbs"
echo WScript.Echo year(s)^& right(100+month(s),2)^& right(100+day(s),2) >>"%temp%\%~n2.vbs"
for /f %%a in ('cscript /nologo "%temp%\%~n2.vbs"') do set "result=%%a"
del "%temp%\%~n2.vbs"
set yyday=%result%

set myfile=Epic_DSH360144_Drug_Utilization_%mydate%_DU.txt
set yfile=Epic_DSH360144_Drug_Utilization_%ydate%_DU.txt
set yyfile=Epic_DSH360144_Drug_Utilization_%yydate%_DU.txt
echo put %myfile% >> uploadsp.txt
echo put %yfile% >> uploadsp.txt
echo put %yyfile% >> uploadsp.txt
pause
</code>```

Body:
I have the following to determine the date and grab a file based on date. I need to modify this grab a file that has a date of yesterday and day before yesterday, i.e. date-1 and date-2. What do I need to change? Thanks!

echo @echo off > uploadsp.txt
set mydate=%date:~10,4%%date:~4,2%%date:~7,2%
echo set mydate=%date:~10,4%%date:~4,2%%date:~7,2% >> uploadsp.txt

set myfile=Epic_DSH360144_Drug_Utilization_%mydate%_DU.txt
echo put %myfile% >> uploadsp.txt
exit

Body:
This should do the trick.

@echo off
set nd=-1
set nd=-2
set mydate=%date:~10,4%%date:~4,2%%date:~7,2%
echo mydate=%date:~10,4%%date:~4,2%%date:~7,2%

echo s=DateAdd("d",%nd%,now) : d=weekday(s) >"%temp%\%~n1.vbs"
echo WScript.Echo year(s)^& right(100+month(s),2)^& right(100+day(s),2) >>"%temp%\%~n1.vbs"
for /f %%a in ('cscript /nologo "%temp%\%~n1.vbs"') do set "result=%%a"
del "%temp%\%~n1.vbs"
set yday=%result%

echo s=DateAdd("d",%nd%,now) : d=weekday(s) >"%temp%\%~n2.vbs"
echo WScript.Echo year(s)^& right(100+month(s),2)^& right(100+day(s),2) >>"%temp%\%~n2.vbs"
for /f %%a in ('cscript /nologo "%temp%\%~n2.vbs"') do set "result=%%a"
del "%temp%\%~n2.vbs"
set yyday=%result%

set myfile=Epic_DSH360144_Drug_Utilization_%mydate%_DU.txt
set yfile=Epic_DSH360144_Drug_Utilization_%ydate%_DU.txt
set yyfile=Epic_DSH360144_Drug_Utilization_%yydate%_DU.txt
echo put %myfile% >> uploadsp.txt
echo put %yfile% >> uploadsp.txt
echo put %yyfile% >> uploadsp.txt
pause


问:
Choosing the main category for a post in Wordpress
i have a post in WP, lets call it Cheesecake. And i have this post set to 3 categories: in "Coffee" in "Cake" and in "Desserts". And now i want the main category for Cheesecake to be "Cake" so the URL would be www.mywordpress.com/category/cake/cheesecake

The problem is: i created the category "Coffee" first and so WP takes the lowest category ID and the URL is www.mywordpress.com/category/coffee/cheesecake

Is there anything i can do to prevent WP from doing this? Maybe a plugin?

答:
This mechanism is provided by the plugin Yoast SEO. It allows you to select or change the "main" category that is used to create the permalink.

Or you can use WP Category Permalink plugin. It does the same thing.


问:
MySQL time_zone gets reset after restart
It's 15:10 o'clock here but MySQL SELECT NOW(); says it's 14:10 o'clock.

I fixed it by SET GLOBAL time_zone = '+1:00';

But after restarting the MySQL server it's the same problem as before.

I also added default_time_zone = Europe/Berlin in my my.cnf but that results in: SQLSTATE[HY000] [2002] Connection refused

What can I do?

答:
I solved it by adding default_time_zone = '+1:00' below [mysqld] in /etc/mysql/my.cnf.

I don't if it'll work after time change on March 26th. I simply created a reminder and I'll check it then.


问:
iOS11 + Webview - Images in scrolling div disappear, don't come back
This issue doesn't occur in iOS9 or iOS10.

The webview is part of an app made using Cordova.

An element has a series of tiles with images and titles in them, for selecting media to view.

The elements have position: relative but no values for any side.
They have a child with position: absolute, this is the title of the media content.
The elements have a unique background image each, with the following accompanying css:

    background-size: cover;
    background-position: top center;
    background-repeat: no-repeat;

When the content is scrolled, there is frequently an issue where the elements are derendered, including the text, but when they should scroll back into view, they don't reappear. You can actually still click where an item should be rendered, and go the the correct page.

This is pretty bad because a full screen height of content appears blank in many situations.

Does anyone have any ideas for how to prevent this issue?

答: add little animation (2pxX2px) on the page where content disappears. it will refresh view render and you will see all content. Not best solution, but it works</p>


问:
Toggle div tag on button click
I have many buttons with id b1, b2 ... and each has a div tag after it with id q1, q2...
I want to toggle the div tag when the corresponding button is clicked. Example: When b1 is clicked q1 should toggle.
It is given here. http://upscfever.com/upsc-fever/en/topper/en-toppers.html

$(document).ready(function(){
  $(".info").hide();
  $("#b1").click(function(){
    $("#q1").toggle();
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="b1" type="button" class="btn btn-primary btn-block"></button>

<div id="q1" class="info"></div></code>```

But as i might have 100 of buttons, how can i do the same thing without adding click on each button?

答:
Use an extra variable state to check your state and for first time only your first div is toggled later on both the divs are toggled.

$(document).ready(function(){
var state = 0;
  $(".info").hide();
  $("#b1").click(function(){
if(state ==0 ) {
   $('#q1').toggle();
state = 1;

}
   else  {
       $("#q1").toggle();
$('#q2').toggle();
    }

  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="b1" type="button" class="btn btn-primary btn-block">Toggle Divs</button>

<div id="q1" class="info">Hello div 1</div>
<div id="q2" class="info">Hello div 2</div></code>```

Title: Toggle div tag on button click

Body:
I have many buttons with id b1, b2 ... and each has a div tag after it with id q1, q2...
I want to toggle the div tag when the corresponding button is clicked. Example: When b1 is clicked q1 should toggle.
It is given here. http://upscfever.com/upsc-fever/en/topper/en-toppers.html

$(document).ready(function(){
  $(".info").hide();
  $("#b1").click(function(){
    $("#q1").toggle();
  });
});

<button id="b1" type="button" class="btn btn-primary btn-block"></button>

But as i might have 100 of buttons, how can i do the same thing without adding click on each button?

Body:
Use an extra variable state to check your state and for first time only your first div is toggled later on both the divs are toggled.

$(document).ready(function(){
var state = 0;
  $(".info").hide();
  $("#b1").click(function(){
if(state ==0 ) {
   $('#q1').toggle();
state = 1;

}
   else  {
       $("#q1").toggle();
$('#q2').toggle();
    }

  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="b1" type="button" class="btn btn-primary btn-block">Toggle Divs</button>

<div id="q1" class="info">Hello div 1</div>
<div id="q2" class="info">Hello div 2</div>


问:
JavaScript Mobile number verification for Turkey
I want to check for mobile number entry via JavaScript RegEx but I am having difficulty on construction the proper query. What I want is to validate mobile numbers only. The format I require is :
5(0/3/4)X XXX XXXX
including the spaces.

For example;
532 123 4567 will be valid while
532 1234567 is invalid. Also
458 123 4567 is invalid.

To clarify the rules are:

First digit must be 5

Second digit must be either 0 or 3 or 4 or 5

Followed by any digit according to the following rules:

If previous digit is 0 this digit must be (5, 6 or 7)

If previous digit is 3 this digit can be (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

If previous digit is 4 this digit can be (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

If previous digit is 5 this digit can be (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

Single space

Any 3-digit number

Single space

Any 4-digit number

Code I am using is as follows:

```<code>function isPhone(phone) {
    var pattern = [PATTERN HERE];
    return pattern.test(phone);
}
</code>```

Which pattern should I use for validation?

Regards.

答:
A simple regex to match your exact rules are:

```<code>^5(0[5-7]|[3-5]\d) \d{3} \d{4}$
</code>```

Test it on regex101 here

Note that if you are validating user input, you should allow any input that is usable without requiring formatting. In that case you should make the spaces optional:

```<code>^5(0[5-7]|[3-5]\d) ?\d{3} ?\d{4}$
</code>```

Body:
I want to check for mobile number entry via JavaScript RegEx but I am having difficulty on construction the proper query. What I want is to validate mobile numbers only. The format I require is :
5(0/3/4)X XXX XXXX
including the spaces.

For example;
532 123 4567 will be valid while
532 1234567 is invalid. Also
458 123 4567 is invalid.

To clarify the rules are:

First digit must be 5

Second digit must be either 0 or 3 or 4 or 5

Followed by any digit according to the following rules:

If previous digit is 0 this digit must be (5, 6 or 7)

If previous digit is 3 this digit can be (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

If previous digit is 4 this digit can be (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

If previous digit is 5 this digit can be (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

Single space

Any 3-digit number

Single space

Any 4-digit number

Code I am using is as follows:

function isPhone(phone) {
    var pattern = [PATTERN HERE];
    return pattern.test(phone);
}

Which pattern should I use for validation?

Regards.

Body:
A simple regex to match your exact rules are:

^5(0[5-7]|[3-5]\d) \d{3} \d{4}$

Test it on regex101 here

Note that if you are validating user input, you should allow any input that is usable without requiring formatting. In that case you should make the spaces optional:

^5(0[5-7]|[3-5]\d) ?\d{3} ?\d{4}$


问:
How to delete values from first table by using name of the second sql
I have a table groups

```<code>group_id | name_group
1          ISI
2          IZI
</code>```

And a table students

```<code>id | first_name | last_name | group_id
6    Bob          Surname1    1
17   John         Surname2    2
</code>```

How can I delete all information from student table by using groups.name?

i.e. I need query which select all students with the same group_id which is equivalent to name.

```<code>group_id 1 = 'ISI'
group_id 2 = 'IZI'
</code>```

And a query must delete exactly by name.

答:
You can use this query

```<code>Delete from Students where group_id=(Select group_id from groups where name_group='ISI');
</code>```

This all the records with the group_id of 1 (via group_name='ISi').

Body:
I have a table groups

group_id | name_group
1          ISI
2          IZI

And a table students

id | first_name | last_name | group_id
6    Bob          Surname1    1
17   John         Surname2    2

How can I delete all information from student table by using groups.name?

i.e. I need query which select all students with the same group_id which is equivalent to name.

group_id 1 = 'ISI'
group_id 2 = 'IZI'

And a query must delete exactly by name.

Body:
You can use this query

Delete from Students where group_id=(Select group_id from groups where name_group='ISI');

This all the records with the group_id of 1 (via group_name='ISi').


问:
Excel VBA macro script to copy format and values from sheet in template workbook into a new attachment workbook
I have a template file with the formula based sheets Outlook View and Outlook Summary that compute from data sheets in the template.   All content within these sheets is found in the ranges specified in the respective range codes. I would like to have these sheets copied into a new workbook and saved as a filename found on the template sheet CONTROLS in cell G12.     My problem is I can only get it to work with one of the sheets, and not both.

For example, this works:

```<code>Sub idpattach()

Dim myWB As New Workbook
Set myWB = ActiveWorkbook

Sheets("Outlook View").Copy
Sheets("Outlook View").Range("a1:bm74").Copy
Sheets("Outlook View").Range("a1:bm74").PasteSpecial xlPasteValues

Sheets("CRM Outlook View").Select

ActiveWorkbook.SaveAs myWB.Sheets("CONTROLS").Range("g12").Value, FileFormat:=51

Application.DisplayAlerts = False

ActiveWorkbook.Save
ActiveWorkbook.Close

Sheets("CONTROLS").Select

End Sub
</code>```

But this doesn't:

```<code>Sub idpattach()

Dim myWB As New Workbook
Set myWB = ActiveWorkbook

Sheets("Outlook View").Copy
Sheets("Outlook View").Range("a1:bm74").Copy
Sheets("Outlook View").Range("a1:bm74").PasteSpecial xlPasteValues

Sheets("Outlook Summary").Copy
Sheets("Outlook Summary").Range("a1:q12").Copy
Sheets("Outlook Summary").Range("a1:q12").PasteSpecial xlPasteValues

Sheets("CRM Outlook View").Select

ActiveWorkbook.SaveAs myWB.Sheets("CONTROLS").Range("g12").Value, FileFormat:=51

Application.DisplayAlerts = False

ActiveWorkbook.Save
ActiveWorkbook.Close

Sheets("CONTROLS").Select

End Sub
</code>```

If you could be so kind and please point out my error and show me the correct way to get this working so I don't have to copy the data sheets into the attachment.

Thank you

**EDIT

Got it working like this, but does anyone have any tips on how to do it better?

```<code>Sub idpattach()

Dim myWB As New Workbook
Set myWB = ActiveWorkbook

Sheets(Array("Outlook View", "CRM Outlook Summary")).Copy

Sheets("Outlook View").Range("a1:bm74").Copy
Sheets("Outlook View").Range("a1:bm74").PasteSpecial xlPasteValues

Sheets("Outlook Summary").Range("a1:q12").Copy
Sheets("Outlook Summary").Range("a1:q12").PasteSpecial xlPasteValues

Sheets("CRM Outlook View").Range("A1").Select

ActiveWorkbook.SaveAs myWB.Sheets("CONTROLS").Range("g12").Value, FileFormat:=51

Application.DisplayAlerts = False

ActiveWorkbook.Save
ActiveWorkbook.Close

Sheets("CONTROLS").Select

End Sub
</code>```

答:
These can be simplified

```<code>Sheets("Outlook View").Range("a1:bm74").Copy
Sheets("Outlook View").Range("a1:bm74").PasteSpecial xlPasteValues

Sheets("Outlook Summary").Range("a1:q12").Copy
Sheets("Outlook Summary").Range("a1:q12").PasteSpecial xlPasteValues
</code>```

into

```<code>Sheets("Outlook View").Range("a1:bm74").Copy Destination:= Sheets("Outlook View").Range("a1:bm74").PasteSpecial xlPasteValues
Sheets("Outlook Summary").Range("a1:q12").Copy Destination:= Sheets("Outlook Summary").Range("a1:q12").PasteSpecial xlPasteValues
</code>```

EDIT - The full block can be modified to..

```<code>Sub idpattach()

Dim myWB As New Workbook
Dim outlookView As Worksheet
Dim outlookSummary As Worksheet

Set myWB = ActiveWorkbook
Set outlookView = Sheets("Outlook View")
Set outlookSummary = Sheets("Outlook Summary")

Sheets(Array("Outlook View", "CRM Outlook Summary")).Copy

outlookView.Range("a1:bm74").Copy Destination:= outlookView.Range("a1:bm74").PasteSpecial xlPasteValues
outlookSummary.Range("a1:q12").Copy Destination:= outlookSummary.Range("a1:q12").PasteSpecial xlPasteValues

Sheets("CRM Outlook View").Range("A1").Select

ActiveWorkbook.SaveAs myWB.Sheets("CONTROLS").Range("g12").Value, FileFormat:=51

Application.DisplayAlerts = False

ActiveWorkbook.Save
ActiveWorkbook.Close

Sheets("CONTROLS").Select

End Sub
</code>```

Body:
I have a template file with the formula based sheets Outlook View and Outlook Summary that compute from data sheets in the template.   All content within these sheets is found in the ranges specified in the respective range codes. I would like to have these sheets copied into a new workbook and saved as a filename found on the template sheet CONTROLS in cell G12.     My problem is I can only get it to work with one of the sheets, and not both.

For example, this works:

Sub idpattach()

Dim myWB As New Workbook
Set myWB = ActiveWorkbook

Sheets("Outlook View").Copy
Sheets("Outlook View").Range("a1:bm74").Copy
Sheets("Outlook View").Range("a1:bm74").PasteSpecial xlPasteValues

Sheets("CRM Outlook View").Select

ActiveWorkbook.SaveAs myWB.Sheets("CONTROLS").Range("g12").Value, FileFormat:=51

Application.DisplayAlerts = False

ActiveWorkbook.Save
ActiveWorkbook.Close

Sheets("CONTROLS").Select

End Sub

But this doesn't:

Sub idpattach()

Dim myWB As New Workbook
Set myWB = ActiveWorkbook

Sheets("Outlook View").Copy
Sheets("Outlook View").Range("a1:bm74").Copy
Sheets("Outlook View").Range("a1:bm74").PasteSpecial xlPasteValues

Sheets("Outlook Summary").Copy
Sheets("Outlook Summary").Range("a1:q12").Copy
Sheets("Outlook Summary").Range("a1:q12").PasteSpecial xlPasteValues

Sheets("CRM Outlook View").Select

ActiveWorkbook.SaveAs myWB.Sheets("CONTROLS").Range("g12").Value, FileFormat:=51

Application.DisplayAlerts = False

ActiveWorkbook.Save
ActiveWorkbook.Close

Sheets("CONTROLS").Select

End Sub

If you could be so kind and please point out my error and show me the correct way to get this working so I don't have to copy the data sheets into the attachment.

Thank you

**EDIT

Got it working like this, but does anyone have any tips on how to do it better?

Sub idpattach()

Dim myWB As New Workbook
Set myWB = ActiveWorkbook

Sheets(Array("Outlook View", "CRM Outlook Summary")).Copy

Sheets("Outlook View").Range("a1:bm74").Copy
Sheets("Outlook View").Range("a1:bm74").PasteSpecial xlPasteValues

Sheets("Outlook Summary").Range("a1:q12").Copy
Sheets("Outlook Summary").Range("a1:q12").PasteSpecial xlPasteValues

Sheets("CRM Outlook View").Range("A1").Select

ActiveWorkbook.SaveAs myWB.Sheets("CONTROLS").Range("g12").Value, FileFormat:=51

Application.DisplayAlerts = False

ActiveWorkbook.Save
ActiveWorkbook.Close

Sheets("CONTROLS").Select

End Sub

Body:
These can be simplified

Sheets("Outlook View").Range("a1:bm74").Copy
Sheets("Outlook View").Range("a1:bm74").PasteSpecial xlPasteValues

Sheets("Outlook Summary").Range("a1:q12").Copy
Sheets("Outlook Summary").Range("a1:q12").PasteSpecial xlPasteValues

into

Sheets("Outlook View").Range("a1:bm74").Copy Destination:= Sheets("Outlook View").Range("a1:bm74").PasteSpecial xlPasteValues
Sheets("Outlook Summary").Range("a1:q12").Copy Destination:= Sheets("Outlook Summary").Range("a1:q12").PasteSpecial xlPasteValues

EDIT - The full block can be modified to..

Sub idpattach()

Dim myWB As New Workbook
Dim outlookView As Worksheet
Dim outlookSummary As Worksheet

Set myWB = ActiveWorkbook
Set outlookView = Sheets("Outlook View")
Set outlookSummary = Sheets("Outlook Summary")

Sheets(Array("Outlook View", "CRM Outlook Summary")).Copy

outlookView.Range("a1:bm74").Copy Destination:= outlookView.Range("a1:bm74").PasteSpecial xlPasteValues
outlookSummary.Range("a1:q12").Copy Destination:= outlookSummary.Range("a1:q12").PasteSpecial xlPasteValues

Sheets("CRM Outlook View").Range("A1").Select

ActiveWorkbook.SaveAs myWB.Sheets("CONTROLS").Range("g12").Value, FileFormat:=51

Application.DisplayAlerts = False

ActiveWorkbook.Save
ActiveWorkbook.Close

Sheets("CONTROLS").Select

End Sub


问:
Pattern and Matcher java problem

"SOMETHING, SOMETHING1,
  SOMETHING2,..."

How can I split that string to

SOMETHING SOMETHING1 SOMETHING2

This is what I have at the moment:

```<code>Pattern p = Pattern.compile("\\,+");
Matcher m = p.matcher(nVI);
while(m.find()){
System.out.println(m.group(1));
</code>```

However, it is not producing the desired result.

答:
Here's a more generic solution (splitting by non-word characters):

```<code>String[] stringList = s.split("\\W+");
</code>```

From the Pattern javadocs:

```<code>\w  A word character: [a-zA-Z_0-9]
\W  A non-word character: [^\w]
</code>```

Or if you use Guava, you can do the equivalent (actually not quite equivalent, as it also matches non-ascii letters):

```<code>for(String word:
Splitter.on(CharMatcher.JAVA_LETTER_OR_DIGIT.negate()).split(str)){
    // do something
}
</code>```

Title: Pattern and Matcher java problem

Body:
"SOMETHING, SOMETHING1,
  SOMETHING2,..."

How can I split that string to

SOMETHING SOMETHING1 SOMETHING2

This is what I have at the moment:

Pattern p = Pattern.compile("\\,+");
Matcher m = p.matcher(nVI);
while(m.find()){
System.out.println(m.group(1));

However, it is not producing the desired result.

Body:
Here's a more generic solution (splitting by non-word characters):

String[] stringList = s.split("\\W+");

From the Pattern javadocs:

\w  A word character: [a-zA-Z_0-9]
\W  A non-word character: [^\w]

Or if you use Guava, you can do the equivalent (actually not quite equivalent, as it also matches non-ascii letters):

for(String word:
Splitter.on(CharMatcher.JAVA_LETTER_OR_DIGIT.negate()).split(str)){
    // do something
}