问:
making linux virtual device driver work with udev
I'm trying to fix the v4l2loopback driver to work with udev (to have udev automatically assign stable device names).

The problem seems to be, that the device driver doesn't expose a few fields that are seemingly required by udev to properly work with the standard 60-persistent-v4l.rules, namely:

ID_BUS

ID_SERIAL

ID_PATH

Also, running udevadm test-builtin path_id on the device doesn't return anything (and the exit-code is 1).

Now any example I've found in the net assumes that I want to write a USB device driver. Unfortunately this is not true for the v4l2loopback device, which is a virtual device.

So the question is:

How do I add PATH, SERIAL and BUS properties to a virtual device driver, in order to make udev see them?

Note: The question is really targeted at fixing the device driver so that it plays nicely with existing udev rules (rather than tweaking udev so that it recognizes the device properly).

答:
Run this command to see everything sent from linux kernel to user space udev:

```<code>$ udevadm monitor --environment --udev
</code>```

If this shows what you need then use it in rule file otherwise create a shell script, invoke that script from within udev rule file and then from shell script parse sysfs to get parameters you are looking for. This is typical standard way fo doing it.

The environment variables are sent from kernel using add_uevent_var() function. In kernel mainly core, class and bus drivers calls functions to create and send uevent. Take a look at this link to note bus anc class driver. This link is also helpful to explore more about it.

One important difference to note between virtual and real device is when we get access to kobject on which we can call functions.

Body:
Run this command to see everything sent from linux kernel to user space udev:

$ udevadm monitor --environment --udev

If this shows what you need then use it in rule file otherwise create a shell script, invoke that script from within udev rule file and then from shell script parse sysfs to get parameters you are looking for. This is typical standard way fo doing it.

The environment variables are sent from kernel using add_uevent_var() function. In kernel mainly core, class and bus drivers calls functions to create and send uevent. Take a look at this link to note bus anc class driver. This link is also helpful to explore more about it.

One important difference to note between virtual and real device is when we get access to kobject on which we can call functions.


来源: stackexchange

问:
Trace: sys.argv[:] = args; TypeError: 'tuple' object does not support item assignment

Try to trace pdb:

python3 -m trace --trace pdb.py helloworld.py

    File "~/python362/lib/python3.6/pdb.py", line 1654, in main

```<code>sys.argv[:] = args
</code>```

I expect sys.argv is a list, but python3 raises an error.

TypeError: 'tuple' object does not support item assignment

答:
You are correct, there is a bug in trace.py:

```<code>sys.argv = opts.filename, *opts.arguments
</code>```

Log it.

ContentLicense: CC BY-SA 3.0

Body:
Try to trace pdb:

python3 -m trace --trace pdb.py helloworld.py

    File "~/python362/lib/python3.6/pdb.py", line 1654, in main

sys.argv[:] = args

I expect sys.argv is a list, but python3 raises an error.

TypeError: 'tuple' object does not support item assignment

Body:
You are correct, there is a bug in trace.py:

sys.argv = opts.filename, *opts.arguments

Log it.


问:
MonoTouch single-app licence?
This morning I've heard a rumour that one can buy a single-app licence of MonoTouch (licence for just 1 application). However, in their store (http://monotouch.net/Store) there is no such licence. Was this just a nasty joke?</p>

答: This was a scam. Such licence does not exist</p>

ContentLicense: CC BY-SA 2.5

Title: MonoTouch single-app licence?


问:
matplotlib color line by "value"
Various versions of this question have been asked before, and I'm not sure if I'm supposed to ask my question on one of the threads or start a new thread. Here goes:

I have a pandas dataframe where there is a column (eg: speed) that I'm trying to plot, and then another column (eg: active) which is, for now, true/false. Depending on the value of active, I'd like to color the line plot.

This thread seems to be the "right" solution, but I'm having an issue:
seaborn or matplotlib line chart, line color depending on variable The OP and I are trying to achieve the same thing:

Here's a broken plot/reproducer:

```<code>Values=[3,4,6, 6,5,4, 3,2,3, 4,5,6]
Colors=['red','red', 'red', 'blue','blue','blue', 'red', 'red', 'red', 'blue', 'blue', 'blue']
myf = pd.DataFrame({'speed': Values, 'colors': Colors})

grouped = myf.groupby('colors')
fig, ax = plt.subplots(1)

for key, group in grouped:
   group.plot(ax=ax, y="speed", label=key, color=key)
</code>```

The resultant plot has two issues: not only are the changed color lines not "connected", but the colors themselves connect "across" the end points:

What I want to see is the change from red to blue and back look like it's all one contiguous line.

Color line by third variable - Python seems to do the right thing, but I am not dealing with "linear" color data. I basically am assigning a set of line colors in a column. I  could easily set the values of the color column to numericals:

```<code>Colors=['1','1', '1', '2','2'...]
</code>```

if that makes generating the desired plot easier.

There is a comment in the first thread:

You could do it if you'll duplicate points when color changed, I've
  modified answer for that

But I basically copied and pasted the answer, so I'm not sure that comment is entirely accurate.

答:
Setup

```<code>import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline

Values=[3,4,6, 6,5,4, 3,2,3, 4,5,6]
Colors=['red','red', 'red', 'blue','blue','blue', 'red', 'red', 'red', 'blue', 'blue', 'blue']
myf = pd.DataFrame({'speed': Values, 'colors': Colors})
</code>```

Solution

1. Detect color change-points and label subgroups of contiguous colors, based on Pandas "diff()" with string

```<code>myf['change'] = myf.colors.ne(myf.colors.shift().bfill()).astype(int)
myf['subgroup'] = myf['change'].cumsum()

myf
   colors  speed  change  subgroup
0     red      3       0         0
1     red      4       0         0
2     red      6       0         0
3    blue      6       1         1
4    blue      5       0         1
5    blue      4       0         1
6     red      3       1         2
7     red      2       0         2
8     red      3       0         2
9    blue      4       1         3
10   blue      5       0         3
11   blue      6       0         3
</code>```

2. Create gaps in the index in which to fit duplicated rows between color subgroups

```<code>myf.index += myf['subgroup'].values

myf
   colors  speed  change  subgroup
0     red      3       0         0
1     red      4       0         0
2     red      6       0         0
4    blue      6       1         1  # index is now 4; 3 is missing
5    blue      5       0         1
6    blue      4       0         1
8     red      3       1         2  # index is now 8; 7 is missing
9     red      2       0         2
10    red      3       0         2
12   blue      4       1         3  # index is now 12; 11 is missing
13   blue      5       0         3
14   blue      6       0         3
</code>```

3. Save the indexes of each subgroup's first row

```<code>first_i_of_each_group = myf[myf['change'] == 1].index

first_i_of_each_group
Int64Index([4, 8, 12], dtype='int64')
</code>```

4. Copy each group's first row to the previous group's last row

```<code>for i in first_i_of_each_group:
    # Copy next group's first row to current group's last row
    myf.loc[i-1] = myf.loc[i]
    # But make this new row part of the current group
    myf.loc[i-1, 'subgroup'] = myf.loc[i-2, 'subgroup']
# Don't need the change col anymore
myf.drop('change', axis=1, inplace=True)
myf.sort_index(inplace=True)
# Create duplicate indexes at each subgroup border to ensure the plot is continuous.
myf.index -= myf['subgroup'].values

myf
   colors  speed  subgroup
0     red      3         0
1     red      4         0
2     red      6         0
3    blue      6         0  # this and next row both have index = 3
3    blue      6         1  # subgroup 1 picks up where subgroup 0 left off
4    blue      5         1
5    blue      4         1
6     red      3         1
6     red      3         2
7     red      2         2
8     red      3         2
9    blue      4         2
9    blue      4         3
10   blue      5         3
11   blue      6         3
</code>```

5. Plot

```<code>fig, ax = plt.subplots()
for k, g in myf.groupby('subgroup'):
    g.plot(ax=ax, y='speed', color=g['colors'].values[0], marker='o')
ax.legend_.remove()
</code>```

Title: matplotlib color line by "value"

Body:
Various versions of this question have been asked before, and I'm not sure if I'm supposed to ask my question on one of the threads or start a new thread. Here goes:

I have a pandas dataframe where there is a column (eg: speed) that I'm trying to plot, and then another column (eg: active) which is, for now, true/false. Depending on the value of active, I'd like to color the line plot.

This thread seems to be the "right" solution, but I'm having an issue:
seaborn or matplotlib line chart, line color depending on variable The OP and I are trying to achieve the same thing:

Here's a broken plot/reproducer:

Values=[3,4,6, 6,5,4, 3,2,3, 4,5,6]
Colors=['red','red', 'red', 'blue','blue','blue', 'red', 'red', 'red', 'blue', 'blue', 'blue']
myf = pd.DataFrame({'speed': Values, 'colors': Colors})

grouped = myf.groupby('colors')
fig, ax = plt.subplots(1)

for key, group in grouped:
   group.plot(ax=ax, y="speed", label=key, color=key)

The resultant plot has two issues: not only are the changed color lines not "connected", but the colors themselves connect "across" the end points:

What I want to see is the change from red to blue and back look like it's all one contiguous line.

Color line by third variable - Python seems to do the right thing, but I am not dealing with "linear" color data. I basically am assigning a set of line colors in a column. I  could easily set the values of the color column to numericals:

Colors=['1','1', '1', '2','2'...]

if that makes generating the desired plot easier.

There is a comment in the first thread:

You could do it if you'll duplicate points when color changed, I've
  modified answer for that

But I basically copied and pasted the answer, so I'm not sure that comment is entirely accurate.

Body:
Setup

import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline

Values=[3,4,6, 6,5,4, 3,2,3, 4,5,6]
Colors=['red','red', 'red', 'blue','blue','blue', 'red', 'red', 'red', 'blue', 'blue', 'blue']
myf = pd.DataFrame({'speed': Values, 'colors': Colors})

Solution

1. Detect color change-points and label subgroups of contiguous colors, based on Pandas "diff()" with string

myf['change'] = myf.colors.ne(myf.colors.shift().bfill()).astype(int)
myf['subgroup'] = myf['change'].cumsum()

myf
   colors  speed  change  subgroup
0     red      3       0         0
1     red      4       0         0
2     red      6       0         0
3    blue      6       1         1
4    blue      5       0         1
5    blue      4       0         1
6     red      3       1         2
7     red      2       0         2
8     red      3       0         2
9    blue      4       1         3
10   blue      5       0         3
11   blue      6       0         3

2. Create gaps in the index in which to fit duplicated rows between color subgroups

myf.index += myf['subgroup'].values

myf
   colors  speed  change  subgroup
0     red      3       0         0
1     red      4       0         0
2     red      6       0         0
4    blue      6       1         1  # index is now 4; 3 is missing
5    blue      5       0         1
6    blue      4       0         1
8     red      3       1         2  # index is now 8; 7 is missing
9     red      2       0         2
10    red      3       0         2
12   blue      4       1         3  # index is now 12; 11 is missing
13   blue      5       0         3
14   blue      6       0         3

3. Save the indexes of each subgroup's first row

first_i_of_each_group = myf[myf['change'] == 1].index

first_i_of_each_group
Int64Index([4, 8, 12], dtype='int64')

4. Copy each group's first row to the previous group's last row

for i in first_i_of_each_group:
    # Copy next group's first row to current group's last row
    myf.loc[i-1] = myf.loc[i]
    # But make this new row part of the current group
    myf.loc[i-1, 'subgroup'] = myf.loc[i-2, 'subgroup']
# Don't need the change col anymore
myf.drop('change', axis=1, inplace=True)
myf.sort_index(inplace=True)
# Create duplicate indexes at each subgroup border to ensure the plot is continuous.
myf.index -= myf['subgroup'].values

myf
   colors  speed  subgroup
0     red      3         0
1     red      4         0
2     red      6         0
3    blue      6         0  # this and next row both have index = 3
3    blue      6         1  # subgroup 1 picks up where subgroup 0 left off
4    blue      5         1
5    blue      4         1
6     red      3         1
6     red      3         2
7     red      2         2
8     red      3         2
9    blue      4         2
9    blue      4         3
10   blue      5         3
11   blue      6         3

5. Plot

fig, ax = plt.subplots()
for k, g in myf.groupby('subgroup'):
    g.plot(ax=ax, y='speed', color=g['colors'].values[0], marker='o')
ax.legend_.remove()


问:
how to change android app language programmaticallly
i'm new member to this community.first i say to everybody
"Hello".....
this is my first question.this is based on the android app development.
So this is my question.
I'm still developing an android application.so in that application i need to develop for the 3 multiple languages.

1.English            -"en"
2.Chinese (Simplified) - "zh_"
3.Chinese (Traditional) - "zh_TW"

So i add string resources for these languages and i implement a code part for this.But Unfortunately it's not working some time.but it's working some time. i can't identity the mistake of my code. it seems that it hasn't any error.

these is my testing string names(all lanuages)

"en" -Sign In

"zh_"-登录

"zh_TW"-登錄

and this is my code part

```<code>public class MainActivity extends AppCompatActivity {

private Spinner spinnerctrl;
private Locale myLocale;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

  spinnerctrl=(Spinner)findViewById(R.id.spinner1);

    spinnerctrl.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        public void onItemSelected(AdapterView<?> parent, View view,
                                   int pos, long id) {

            if (pos == 1) {

                Toast.makeText(parent.getContext(),
                        "You have selected Chinese(Simplified)", Toast.LENGTH_SHORT)
                        .show();
                saveLocale("zh");
            } else if (pos == 2) {

                Toast.makeText(parent.getContext(),
                        "You have selected Chinese(Traditional)", Toast.LENGTH_SHORT)
                        .show();
                saveLocale("zh_TW");

            }
            else if (pos == 3)
            {
                Toast.makeText(parent.getContext(),
                        "You have select English",Toast.LENGTH_SHORT)
                        .show();
                saveLocale("en");
            }

        }

        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub
        }

    });

    loadLocale();

@Override
public void onBackPressed()
{
    Intent MyProfile = new Intent(getApplicationContext(), MainActivity.class);
    startActivity(MyProfile);
    finish();
}

public void loadLocale() {
    String langPref = "Language";
    SharedPreferences prefs = getSharedPreferences("CommonPrefs",
            Activity.MODE_PRIVATE);
    String language = prefs.getString(langPref, "");
    changeLang(language);
}

public void changeLang(String lang) {
    if (lang.equals(""))
        return;
    myLocale = new Locale(lang);
    saveLocale(lang);
    Locale.setDefault(myLocale);
    Resources res = getResources();
    DisplayMetrics dm = res.getDisplayMetrics();
    Configuration conf = res.getConfiguration();
    conf.locale = myLocale;
    res.updateConfiguration(conf, dm);
}

public void saveLocale(String lang) {
    String langPref = "Language";
    SharedPreferences prefs = getSharedPreferences("CommonPrefs",
            Activity.MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString(langPref, lang);
    editor.commit();

}}
</code>```

So this is my problem.this code part run without any runtime errors,etc.but not working some time.i don't know why is that.So if any one can help me slove this problem it's very big help to me.
Thank you.

答:
```<code>public static void changeLocale(Context context, String localeString) {

String locale = "en";
if (localeString != null) {
    if (localeString.equals("Malay")) {
        locale = "ms";
    } else if (localeString.equals("Myanmar")) {
        locale = "my";
    } else if (localeString.equals("Tamil")) {
        locale = "ta";
    }
}

Locale myLocale = new Locale(locale);
Resources res = context.getResources();
DisplayMetrics dm = res.getDisplayMetrics();

Configuration conf = res.getConfiguration();
conf.locale = myLocale;
res.updateConfiguration(conf, dm);

}
</code>```

Body:
i'm new member to this community.first i say to everybody
"Hello".....
this is my first question.this is based on the android app development.
So this is my question.
I'm still developing an android application.so in that application i need to develop for the 3 multiple languages.

1.English            -"en"
2.Chinese (Simplified) - "zh_"
3.Chinese (Traditional) - "zh_TW"

So i add string resources for these languages and i implement a code part for this.But Unfortunately it's not working some time.but it's working some time. i can't identity the mistake of my code. it seems that it hasn't any error.

these is my testing string names(all lanuages)

"en" -Sign In

"zh_"-登录

"zh_TW"-登錄

and this is my code part

public class MainActivity extends AppCompatActivity {

private Spinner spinnerctrl;
private Locale myLocale;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

  spinnerctrl=(Spinner)findViewById(R.id.spinner1);

    spinnerctrl.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        public void onItemSelected(AdapterView<?> parent, View view,
                                   int pos, long id) {

            if (pos == 1) {

                Toast.makeText(parent.getContext(),
                        "You have selected Chinese(Simplified)", Toast.LENGTH_SHORT)
                        .show();
                saveLocale("zh");
            } else if (pos == 2) {

                Toast.makeText(parent.getContext(),
                        "You have selected Chinese(Traditional)", Toast.LENGTH_SHORT)
                        .show();
                saveLocale("zh_TW");

            }
            else if (pos == 3)
            {
                Toast.makeText(parent.getContext(),
                        "You have select English",Toast.LENGTH_SHORT)
                        .show();
                saveLocale("en");
            }

        }

        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub
        }

    });

    loadLocale();

@Override
public void onBackPressed()
{
    Intent MyProfile = new Intent(getApplicationContext(), MainActivity.class);
    startActivity(MyProfile);
    finish();
}

public void loadLocale() {
    String langPref = "Language";
    SharedPreferences prefs = getSharedPreferences("CommonPrefs",
            Activity.MODE_PRIVATE);
    String language = prefs.getString(langPref, "");
    changeLang(language);
}

public void changeLang(String lang) {
    if (lang.equals(""))
        return;
    myLocale = new Locale(lang);
    saveLocale(lang);
    Locale.setDefault(myLocale);
    Resources res = getResources();
    DisplayMetrics dm = res.getDisplayMetrics();
    Configuration conf = res.getConfiguration();
    conf.locale = myLocale;
    res.updateConfiguration(conf, dm);
}

public void saveLocale(String lang) {
    String langPref = "Language";
    SharedPreferences prefs = getSharedPreferences("CommonPrefs",
            Activity.MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString(langPref, lang);
    editor.commit();

}}

So this is my problem.this code part run without any runtime errors,etc.but not working some time.i don't know why is that.So if any one can help me slove this problem it's very big help to me.
Thank you.


问:
How to disable days of week in date picker based on response from web service
In my project there is many employees , each one of them has his own schedule per week , I've implemented a web service that returns a list of integers which represents the work days for the specified employee , the main idea for all of this is that I need to prevent users from making appointments in the other days of week .. how to hide those days from the date picker ? or if there is another way to do this ?

web service

```<code>[WebMethod]

    public void getWorkDays(int id)
    {
        WorkDays wd = new WorkDays(id);

        List<Days> workDays = new List<Days>();
        String docSch_query = "select * from workDays where empId = " + id + " and status=1";
        DBConnect conn = new DBConnect();
        DataTable dt = conn.select(docSch_query);

        foreach (DataRow r in dt.Rows)
        {
            switch (r["dayId"].ToString())
            {
                case "1":
                    workDays.Add(new Days(1,"sat"));
                    break;
                case "2":
                    workDays.Add(new Days(2, "sun"));
                    break;
                case "3":
                    workDays.Add(new Days(3, "mon"));
                    break;
                case "4":
                    workDays.Add(new Days(4, "tus"));
                    break;
                case "5":
                    workDays.Add(new Days(5, "wed"));
                    break;
                case "6":
                    workDays.Add(new Days(6, "thu"));
                    break;
            }
        }

        JavaScriptSerializer js = new JavaScriptSerializer();
        Context.Response.Write(js.Serialize(workDays));
    }
</code>```

date picker

```<code>$(document).ready(function () {

        var dates=$.ajax({
            type: "POST",
            url: "getdays.asmx/getWorkDays",
            data: {id:<%#int.Parse(Session["appWith"].ToString())%>},
            dataType: "json",

            success: function (data) {

                return data.d;
            }
        });

        $('#edob').datepicker({

            firstDay: 3,
            beforeShowDay: function (date) {
                var available = $.inArray(date.getDay(), dates['int']) > -1;

                if (available) {
                    return [1];   //return available date
                }
                else {
                    return [0];   //return not available
                }
            }
        });
    })
</code>```

答:
I found the solution for my question ..</p>

```<code>$(document).ready(function () {
        var dates = $.parseJSON(
            $.ajax({
                type: "POST",
                url: "getdays.asmx/getWorkDays",
                data: { id: <%=int.Parse(Session["appWith"].ToString())%> },
                dataType: "json",
                async: false
            }).responseText);

        $('#edob').datepicker({

            firstDay: 3,
            beforeShowDay: function (date) {
                var a =[];
                var weekend = false;
                for (i = 0; i < dates.length; i++) {
                    a.push(dates[i].Id);
                }
                var weekend = date.getDay() == 5 || date.getDay() == 6 || !($.inArray(date.getDay(),a)>-1);
                return [!weekend, weekend ? 'myweekend' : ''];
            }
      });
    });
</code>```

Body:
In my project there is many employees , each one of them has his own schedule per week , I've implemented a web service that returns a list of integers which represents the work days for the specified employee , the main idea for all of this is that I need to prevent users from making appointments in the other days of week .. how to hide those days from the date picker ? or if there is another way to do this ?

web service

[WebMethod]

    public void getWorkDays(int id)
    {
        WorkDays wd = new WorkDays(id);

        List<Days> workDays = new List<Days>();
        String docSch_query = "select * from workDays where empId = " + id + " and status=1";
        DBConnect conn = new DBConnect();
        DataTable dt = conn.select(docSch_query);

        foreach (DataRow r in dt.Rows)
        {
            switch (r["dayId"].ToString())
            {
                case "1":
                    workDays.Add(new Days(1,"sat"));
                    break;
                case "2":
                    workDays.Add(new Days(2, "sun"));
                    break;
                case "3":
                    workDays.Add(new Days(3, "mon"));
                    break;
                case "4":
                    workDays.Add(new Days(4, "tus"));
                    break;
                case "5":
                    workDays.Add(new Days(5, "wed"));
                    break;
                case "6":
                    workDays.Add(new Days(6, "thu"));
                    break;
            }
        }

        JavaScriptSerializer js = new JavaScriptSerializer();
        Context.Response.Write(js.Serialize(workDays));
    }

date picker

$(document).ready(function () {

        var dates=$.ajax({
            type: "POST",
            url: "getdays.asmx/getWorkDays",
            data: {id:<%#int.Parse(Session["appWith"].ToString())%>},
            dataType: "json",

            success: function (data) {

                return data.d;
            }
        });

        $('#edob').datepicker({

            firstDay: 3,
            beforeShowDay: function (date) {
                var available = $.inArray(date.getDay(), dates['int']) > -1;

                if (available) {
                    return [1];   //return available date
                }
                else {
                    return [0];   //return not available
                }
            }
        });
    })

Body:
I found the solution for my question ..

$(document).ready(function () {
        var dates = $.parseJSON(
            $.ajax({
                type: "POST",
                url: "getdays.asmx/getWorkDays",
                data: { id: <%=int.Parse(Session["appWith"].ToString())%> },
                dataType: "json",
                async: false
            }).responseText);

        $('#edob').datepicker({

            firstDay: 3,
            beforeShowDay: function (date) {
                var a =[];
                var weekend = false;
                for (i = 0; i < dates.length; i++) {
                    a.push(dates[i].Id);
                }
                var weekend = date.getDay() == 5 || date.getDay() == 6 || !($.inArray(date.getDay(),a)>-1);
                return [!weekend, weekend ? 'myweekend' : ''];
            }
      });
    });


问:
How can I detect the codepage of a serial of text,2 byte for a character,It's polish
How can I detect the codepage  of a serial of text,2 byte for a charactor,It's polish.And for normal English charactor ,just add 0x00 to the ansi code, for special Polish character,the two byte have the special meaning. there is no file head ,just bytes stream like this.

Sample here

string:   Połączenia

bytes:    50 00/6f 00/42 01/05 01/63 00/7a 00/65 00/69 00/61 00

I think it's not unicode ,because 0x4201 in unicode is a Chinese charactor
not Polish.

So Any one can help me? thanks very much!

Body:
Its UTF-16 Big Endian.

$ echo -n "Połączenia" | iconv -f UTF8 -t UTF16BE | hexdump
0000000 5000 6f00 4201 0501 6300 7a00 6500 6e00
0000010 6900 6100


问:
Form submit button onclick does not call my JS function included in JS file

I have an html form with a submit button. I have a js function in a file that I include in the head. I am trying to bind the onclick event of the button to call that function. However, all the methods I tried did not work.</p>

```<code><!DOCTYPE html>
<html>
<body>
    <script src="popup.js" type="text/javascript"></script>
    <button type="button" onclick="displayFormContents();">
</button>

<p id="demo"></p>
First name:<br>
<input type="text" name="firstname" >
<br>
Name:<br>
<input type="text" name="name" >
<br>

<form>
    age : <input type="date" name="Age">
</form>

<form>
    Phone : <input type="number" name="Phone">
</form>

<form>
    email : <input type="email" name="mail">
</form>

<form>
    Student at UCLA? : <input type="checkbox" name="Doe">
</form>

<form>
    <input type="radio" name="gender" value="male" checked> Male<br>
    <input type="radio" name="gender" value="female"> Female<br>
    <input type="radio" name="gender" value="other"> Other
</form>

<input type="submit">
</form>

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

答:
Use only a single form tag. popup.js should be in the same folder as the file containing this code. popup.js should have displayFormContents() function. Call the function on form submit.</p>

```<code><!DOCTYPE html>
<html>
<head>
    <script src="popup.js" type="text/javascript"></script>
</head>
<body>
<form onsubmit="displayFormContents()">
<p id="demo"></p>
First name:<br>
<input type="text" name="firstname" >
<br>
Name:<br>
<input type="text" name="name" >
<br>
    age : <input type="date" name="Age">
    Phone : <input type="number" name="Phone">
    email : <input type="email" name="mail">
    Student at UCLA? : <input type="checkbox" name="Doe">
    <input type="radio" name="gender" value="male" checked> Male<br>
    <input type="radio" name="gender" value="female"> Female<br>
    <input type="radio" name="gender" value="other"> Other
<input type="submit" value="Submit"/>
</form>

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

Body:
I have an html form with a submit button. I have a js function in a file that I include in the head. I am trying to bind the onclick event of the button to call that function. However, all the methods I tried did not work.

<!DOCTYPE html>

    <button type="button" onclick="displayFormContents();">
</button>

First name:

<input type="text" name="firstname" >

Name:

<input type="text" name="name" >

<form>
    age : <input type="date" name="Age">
</form>

<form>
    Phone : <input type="number" name="Phone">
</form>

<form>
    email : <input type="email" name="mail">
</form>

<form>
    Student at UCLA? : <input type="checkbox" name="Doe">
</form>

<form>
    <input type="radio" name="gender" value="male" checked> Male

    <input type="radio" name="gender" value="female"> Female

    <input type="radio" name="gender" value="other"> Other
</form>

<input type="submit">
</form>

Body:
Use only a single form tag. popup.js should be in the same folder as the file containing this code. popup.js should have displayFormContents() function. Call the function on form submit.

<!DOCTYPE html>
<html>
<head>
    <script src="popup.js" type="text/javascript"></script>
</head>
<body>
<form onsubmit="displayFormContents()">
<p id="demo"></p>
First name:<br>
<input type="text" name="firstname" >
<br>
Name:<br>
<input type="text" name="name" >
<br>
    age : <input type="date" name="Age">
    Phone : <input type="number" name="Phone">
    email : <input type="email" name="mail">
    Student at UCLA? : <input type="checkbox" name="Doe">
    <input type="radio" name="gender" value="male" checked> Male<br>
    <input type="radio" name="gender" value="female"> Female<br>
    <input type="radio" name="gender" value="other"> Other
<input type="submit" value="Submit"/>
</form>

</body>
</html>


问:
What does “Autoreleased with no pool in place” mean?
My Application structure is as follows,
the core part is written in C++ and using thread heavily, and i am developing UI in Objective C on top of it,
if i don't execute the thread it works fine, but i can't disable, stop thread, UI is crashing randomly in the log i could see , following message

```<code>__NSAutoreleaseNoPool(): Object 0x350270 of class NSCFString autoreleased with no pool in place - just leaking
</code>```

Similar messages coming more then once,
by googling come to know, i need to set NSAutoReleasePool to get rid of it, but how its possible to integrate the same with C++ code.

Edit: Core lib will be activated from UI , hence i suppose, its safe to say UI is running in the main thread, Lib is creating/terminating thread without notifying UI,
in this case, can i call AutoReleasePool in the UI

Can anyone guide me?

答:
See these docs for what you should know about multithreading with Cocoa: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Multithreading/ThreadSafetySummary/ThreadSafetySummary.html

It's OK to design your app like you have, but two things should be kept in mind:

Life is simplest (and sometimes necessary) when UI controls like views (AppKit or UIKit) are manipulated on the main thread. You can use Foundation objects and some AppKit/UIKit objects on background threads, and some Foundation objects can be used from multiple threads.

If you're using any Cocoa objects at all in background threads, you'll need to set up autorelease pools on those threads.

Like so:

```<code>- (void)backgroundThreadStart
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    // do stuff

    [pool release];
}
</code>```

That will fix your console errors, but you might have other issues that led to the actual crashing you were seeing.

Body:
My Application structure is as follows,
the core part is written in C++ and using thread heavily, and i am developing UI in Objective C on top of it,
if i don't execute the thread it works fine, but i can't disable, stop thread, UI is crashing randomly in the log i could see , following message

__NSAutoreleaseNoPool(): Object 0x350270 of class NSCFString autoreleased with no pool in place - just leaking

Similar messages coming more then once,
by googling come to know, i need to set NSAutoReleasePool to get rid of it, but how its possible to integrate the same with C++ code.

Edit: Core lib will be activated from UI , hence i suppose, its safe to say UI is running in the main thread, Lib is creating/terminating thread without notifying UI,
in this case, can i call AutoReleasePool in the UI

Can anyone guide me?

Body:
See these docs for what you should know about multithreading with Cocoa: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Multithreading/ThreadSafetySummary/ThreadSafetySummary.html

It's OK to design your app like you have, but two things should be kept in mind:

Life is simplest (and sometimes necessary) when UI controls like views (AppKit or UIKit) are manipulated on the main thread. You can use Foundation objects and some AppKit/UIKit objects on background threads, and some Foundation objects can be used from multiple threads.

If you're using any Cocoa objects at all in background threads, you'll need to set up autorelease pools on those threads.

Like so:

- (void)backgroundThreadStart
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    // do stuff

    [pool release];
}

That will fix your console errors, but you might have other issues that led to the actual crashing you were seeing.


问:
angular2-multiselect-dropdown shows empty list
I am using angular2-multiselect-dropdown but the dropdown is empty.

Following is the data in ts file:

```<code>this.list = [
{
   "docid":1,
   "value": "Europe"
},
{
   "docid":2,
   "value": "ASIA"
},
{
   "docid":3,
   "value": "AFRICA"
},
{
   "docid":4,
   "value": "LATIN AMERICA"
},
{
   "docid":5,
   "value": "NORTH AMERICA"
}

]
</code>```

In HTML :

```<code><angular2-multiselect [data]="List" [(ngModel)]="selectedItems"
        (onSelect)="onItemSelect($event)"
        (onDeSelect)="OnItemDeSelect($event)"
        (onSelectAll)="onSelectAll($event)"
        (onDeSelectAll)="onDeSelectAll($event)">
      </angular2-multiselect>
</code>```

In examples, he is using {"id":9,"itemName":"Italy"} which works well. So is there any way that the field itemName can be configured.

https://github.com/CuppaLabs/angular2-multiselect-dropdown
https://cuppalabs.github.io/angular2-multiselect-dropdown/#/basic

答:
The component is expecting the [data] property to be populated in a certain shape. In this case, it should be as follows:

```<code>export class ListItem{
    id: Number;
    itemName: String
}
</code>```

You will have to transform your list before setting it as the input to data.

You can use map to get this done.

```<code>this.list = this.list.map((item) => {
  return {
    id: item.docId,
    itemName: item.value
  }
})
</code>```

Body:
I am using angular2-multiselect-dropdown but the dropdown is empty.

Following is the data in ts file:

this.list = [
{
   "docid":1,
   "value": "Europe"
},
{
   "docid":2,
   "value": "ASIA"
},
{
   "docid":3,
   "value": "AFRICA"
},
{
   "docid":4,
   "value": "LATIN AMERICA"
},
{
   "docid":5,
   "value": "NORTH AMERICA"
}

]

In HTML :

<angular2-multiselect [data]="List" [(ngModel)]="selectedItems"
        (onSelect)="onItemSelect($event)"
        (onDeSelect)="OnItemDeSelect($event)"
        (onSelectAll)="onSelectAll($event)"
        (onDeSelectAll)="onDeSelectAll($event)">
      </angular2-multiselect>

In examples, he is using {"id":9,"itemName":"Italy"} which works well. So is there any way that the field itemName can be configured.

https://github.com/CuppaLabs/angular2-multiselect-dropdown
https://cuppalabs.github.io/angular2-multiselect-dropdown/#/basic

Body:
The component is expecting the [data] property to be populated in a certain shape. In this case, it should be as follows:

export class ListItem{
    id: Number;
    itemName: String
}

You will have to transform your list before setting it as the input to data.

You can use map to get this done.

this.list = this.list.map((item) => {
  return {
    id: item.docId,
    itemName: item.value
  }
})


问:
Echo Class Inside of HTML Tag with PHP
Trying to get this piece of code to run:

```<code><li><a <? if ($tab=='Home') echo 'class="activetab"' ?> href="/">Home</a></li>
</code>```

Right now, my PHP/Apache on EC2 setup spits out

```<code>href="/">Home
</code>```

It looks like the php inside the tag is messing up the rendering, and I'd like the tab to be rendered.

The  site is hosted somewhere else and works, so it seems like a configuration issue with either php or apache.

答:
Check your php short tag is open or not?

In your php.ini change the short_open_tag = Off to short_open_tag = On.

Title: Echo Class Inside of HTML Tag with PHP

Body:
Trying to get this piece of code to run:

<a <? if ($tab=='Home') echo 'class="activetab"' ?> href="/">Home

Right now, my PHP/Apache on EC2 setup spits out

href="/">Home

It looks like the php inside the tag is messing up the rendering, and I'd like the tab to be rendered.

The  site is hosted somewhere else and works, so it seems like a configuration issue with either php or apache.


问:
Time Complexity of Fibonacci Algorithm
So, i've got a recursive method in Java for getting the 'n'th fibonacci number - The only question i have, is: what's the time complexity? I think it's O(2^n), but i may be mistaken? (I know that iterative is way better, but it's an exercise)</p>

```<code>public int fibonacciRecursive(int n)
{
    if(n == 1 || n == 2) return 1;
    else return fibonacciRecursive(n-2) + fibonacciRecursive(n-1);
}
</code>```

答: Each function call does exactly one addition, or returns 1. The base cases only return the value one, so the total number of additions is fib(n)-1. The total number of function calls is therefore 2*fib(n)-1, so the time complexity is Θ(fib(N)) = Θ(phi^N), which is bounded by O(2^N).</p>

Title: Time Complexity of Fibonacci Algorithm

Body:
So, i've got a recursive method in Java for getting the 'n'th fibonacci number - The only question i have, is: what's the time complexity? I think it's O(2^n), but i may be mistaken? (I know that iterative is way better, but it's an exercise)

public int fibonacciRecursive(int n)
{
    if(n == 1 || n == 2) return 1;
    else return fibonacciRecursive(n-2) + fibonacciRecursive(n-1);
}


问:
Spring framework Servlet.init() for servlet dispatcher threw exception
I have some simple spring code
my controller:

```<code>package com.luv2code.springdemo.mvc;

import javax.validation.Valid;

import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/customer")
public class CustomerController {

    // add an initbinder ... to convert trim input strings
    // remove leading and trailing whitespace
    // resolve issue for our validation

    @InitBinder
    public void initBinder(WebDataBinder dataBinder) {

        StringTrimmerEditor stringTrimmerEditor = new StringTrimmerEditor(true);

        dataBinder.registerCustomEditor(String.class, stringTrimmerEditor);
    }

    @RequestMapping("/showForm")
    public String showForm(Model theModel) {

        theModel.addAttribute("customer", new Customer());

        return "customer-form";
    }

    @RequestMapping("/processForm")
    public String processForm(
            @Valid @ModelAttribute("customer") Customer theCustomer,
            BindingResult theBindingResult) {

        System.out.println("Last name: |" + theCustomer.getLastName() + "|");

        if (theBindingResult.hasErrors()) {
            return "customer-form";
        }
        else {
            return "customer-confirmation";
        }
    }
}
</code>```

my jsp:

```<code><%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

<html>

<head>
    <title>Customer Registration Form</title>

    <style>
        .error {color:red}
    </style>
</head>
<body>

<i>Fill out the form. Asterisk (*) means required.</i>
<br><br>

    <form:form action="processForm" modelAttribute="customer">

        First name: <form:input path="firstName" />

        <br><br>

        Last name (*): <form:input path="lastName" />
        <form:errors path="lastName" cssClass="error" />

        <br><br>

        Free passes  (*): <form:input path="freePasses" />
        <form:errors path="freePasses" cssClass="error" />

        <br><br>

        Postal Code: <form:input path="postalCode" />
        <form:errors path="postalCode" cssClass="error" />

        <br><br>

        <input type="submit" value="Submit" />

    </form:form>

</body>

</html>
</code>```

and my web.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    id="WebApp_ID" version="3.1">

    <display-name>spring-mvc-demo</display-name>

    <!-- Spring MVC Configs -->

    <!-- Step 1: Configure Spring MVC Dispatcher Servlet -->
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring-mvc-demo-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <!-- Step 2: Set up URL mapping for Spring MVC Dispatcher Servlet -->
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>
</code>```

stacktrace:

```<code>Dec 06, 2017 11:43:25 PM org.springframework.web.servlet.FrameworkServlet initServletBean
SEVERE: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean#0': Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: javax/el/ELManager
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1710)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:583)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:758)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:868)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:676)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:642)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:690)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:558)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:499)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:172)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1269)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1182)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1072)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5362)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5660)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1700)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1690)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NoClassDefFoundError: javax/el/ELManager
    at org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator.buildExpressionFactory(ResourceBundleMessageInterpolator.java:88)
    at org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator.<init>(ResourceBundleMessageInterpolator.java:47)
    at org.hibernate.validator.internal.engine.ConfigurationImpl.getDefaultMessageInterpolator(ConfigurationImpl.java:461)
    at org.springframework.validation.beanvalidation.LocalValidatorFactoryBean.afterPropertiesSet(LocalValidatorFactoryBean.java:267)
    at org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean.afterPropertiesSet(OptionalValidatorFactoryBean.java:40)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1769)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1706)
    ... 28 more
Caused by: java.lang.ClassNotFoundException: javax.el.ELManager
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1892)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1735)
    ... 35 more

Dec 06, 2017 11:43:25 PM org.apache.catalina.core.ApplicationContext log
SEVERE: StandardWrapper.Throwable
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean#0': Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: javax/el/ELManager
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1710)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:583)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:758)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:868)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:676)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:642)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:690)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:558)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:499)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:172)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1269)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1182)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1072)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5362)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5660)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1700)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1690)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NoClassDefFoundError: javax/el/ELManager
    at org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator.buildExpressionFactory(ResourceBundleMessageInterpolator.java:88)
    at org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator.<init>(ResourceBundleMessageInterpolator.java:47)
    at org.hibernate.validator.internal.engine.ConfigurationImpl.getDefaultMessageInterpolator(ConfigurationImpl.java:461)
    at org.springframework.validation.beanvalidation.LocalValidatorFactoryBean.afterPropertiesSet(LocalValidatorFactoryBean.java:267)
    at org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean.afterPropertiesSet(OptionalValidatorFactoryBean.java:40)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1769)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1706)
    ... 28 more
Caused by: java.lang.ClassNotFoundException: javax.el.ELManager
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1892)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1735)
    ... 35 more

Dec 06, 2017 11:43:25 PM org.apache.catalina.core.StandardContext loadOnStartup
SEVERE: Servlet [dispatcher] in web application [/spring-mvc-demo] threw load() exception
java.lang.ClassNotFoundException: javax.el.ELManager
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1892)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1735)
    at org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator.buildExpressionFactory(ResourceBundleMessageInterpolator.java:88)
    at org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator.<init>(ResourceBundleMessageInterpolator.java:47)
    at org.hibernate.validator.internal.engine.ConfigurationImpl.getDefaultMessageInterpolator(ConfigurationImpl.java:461)
    at org.springframework.validation.beanvalidation.LocalValidatorFactoryBean.afterPropertiesSet(LocalValidatorFactoryBean.java:267)
    at org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean.afterPropertiesSet(OptionalValidatorFactoryBean.java:40)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1769)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1706)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:583)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:758)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:868)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:676)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:642)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:690)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:558)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:499)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:172)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1269)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1182)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1072)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5362)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5660)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1700)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1690)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

Dec 06, 2017 11:43:25 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
Dec 06, 2017 11:43:25 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
Dec 06, 2017 11:43:25 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 3248 ms
Dec 06, 2017 11:43:26 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'dispatcher'
Dec 06, 2017 11:43:26 PM org.springframework.web.servlet.FrameworkServlet initServletBean
INFO: FrameworkServlet 'dispatcher': initialization started
Dec 06, 2017 11:43:26 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing WebApplicationContext for namespace 'dispatcher-servlet': startup date [Wed Dec 06 23:43:26 EST 2017]; root of context hierarchy
Dec 06, 2017 11:43:26 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/spring-mvc-demo-servlet.xml]
Dec 06, 2017 11:43:26 PM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry register
INFO: Mapped "{[/customer/showForm]}" onto public java.lang.String com.luv2code.springdemo.mvc.CustomerController.showForm(org.springframework.ui.Model)
Dec 06, 2017 11:43:26 PM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry register
INFO: Mapped "{[/customer/processForm]}" onto public java.lang.String com.luv2code.springdemo.mvc.CustomerController.processForm(com.luv2code.springdemo.mvc.Customer,org.springframework.validation.BindingResult)
Dec 06, 2017 11:43:26 PM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry register
INFO: Mapped "{[/]}" onto public java.lang.String com.luv2code.springdemo.mvc.HomeController.showPage()
Dec 06, 2017 11:43:26 PM org.springframework.context.support.AbstractApplicationContext refresh
WARNING: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean#0': Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: javax/el/ELManager
</code>```

but when I run on tomcat, it shows "HTTP Status 500 - Servlet.init() for servlet dispatcher threw exception", and description "description The server encountered an internal error that prevented it from fulfilling this request."  Actually I tried some easy spring code earlier today, it works. And this time I tried to use validation api and copy some hibernate files to lib, but failed. Anyone could help me out? Thanks!

答:
The error tells you that to use the ValidationApi Spring need the class javax.el.ELManager, which is part of the Java EL spec since the version 3.0.

Tomcat provide a el-api.jar that you'll find in the tomcat_home/lib that is the implementation of that spec, but Tomcat older version than 8.X doesn't provide the 3.0 version of the El spec (you can check see that here).

If you are not in the good version of tomcat try to upgrade it and see if it works.

Body:
I have some simple spring code
my controller:

package com.luv2code.springdemo.mvc;

import javax.validation.Valid;

import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/customer")
public class CustomerController {

    // add an initbinder ... to convert trim input strings
    // remove leading and trailing whitespace
    // resolve issue for our validation

    @InitBinder
    public void initBinder(WebDataBinder dataBinder) {

        StringTrimmerEditor stringTrimmerEditor = new StringTrimmerEditor(true);

        dataBinder.registerCustomEditor(String.class, stringTrimmerEditor);
    }

    @RequestMapping("/showForm")
    public String showForm(Model theModel) {

        theModel.addAttribute("customer", new Customer());

        return "customer-form";
    }

    @RequestMapping("/processForm")
    public String processForm(
            @Valid @ModelAttribute("customer") Customer theCustomer,
            BindingResult theBindingResult) {

        System.out.println("Last name: |" + theCustomer.getLastName() + "|");

        if (theBindingResult.hasErrors()) {
            return "customer-form";
        }
        else {
            return "customer-confirmation";
        }
    }
}

my jsp:

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

    <title>Customer Registration Form</title>

Fill out the form. Asterisk (*) means required.

    <form:form action="processForm" modelAttribute="customer">

        First name: <form:input path="firstName" />

        Last name (*): <form:input path="lastName" />
        <form:errors path="lastName" cssClass="error" />

        Free passes  (*): <form:input path="freePasses" />
        <form:errors path="freePasses" cssClass="error" />

        Postal Code: <form:input path="postalCode" />
        <form:errors path="postalCode" cssClass="error" />

        <input type="submit" value="Submit" />

    </form:form>

and my web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    id="WebApp_ID" version="3.1">

    <display-name>spring-mvc-demo</display-name>

    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring-mvc-demo-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

stacktrace:

Dec 06, 2017 11:43:25 PM org.springframework.web.servlet.FrameworkServlet initServletBean
SEVERE: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean#0': Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: javax/el/ELManager
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1710)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:583)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:758)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:868)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:676)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:642)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:690)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:558)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:499)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:172)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1269)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1182)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1072)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5362)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5660)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1700)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1690)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NoClassDefFoundError: javax/el/ELManager
    at org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator.buildExpressionFactory(ResourceBundleMessageInterpolator.java:88)
    at org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator.<init>(ResourceBundleMessageInterpolator.java:47)
    at org.hibernate.validator.internal.engine.ConfigurationImpl.getDefaultMessageInterpolator(ConfigurationImpl.java:461)
    at org.springframework.validation.beanvalidation.LocalValidatorFactoryBean.afterPropertiesSet(LocalValidatorFactoryBean.java:267)
    at org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean.afterPropertiesSet(OptionalValidatorFactoryBean.java:40)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1769)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1706)
    ... 28 more
Caused by: java.lang.ClassNotFoundException: javax.el.ELManager
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1892)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1735)
    ... 35 more

Dec 06, 2017 11:43:25 PM org.apache.catalina.core.ApplicationContext log
SEVERE: StandardWrapper.Throwable
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean#0': Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: javax/el/ELManager
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1710)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:583)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:758)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:868)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:676)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:642)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:690)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:558)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:499)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:172)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1269)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1182)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1072)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5362)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5660)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1700)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1690)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NoClassDefFoundError: javax/el/ELManager
    at org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator.buildExpressionFactory(ResourceBundleMessageInterpolator.java:88)
    at org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator.<init>(ResourceBundleMessageInterpolator.java:47)
    at org.hibernate.validator.internal.engine.ConfigurationImpl.getDefaultMessageInterpolator(ConfigurationImpl.java:461)
    at org.springframework.validation.beanvalidation.LocalValidatorFactoryBean.afterPropertiesSet(LocalValidatorFactoryBean.java:267)
    at org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean.afterPropertiesSet(OptionalValidatorFactoryBean.java:40)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1769)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1706)
    ... 28 more
Caused by: java.lang.ClassNotFoundException: javax.el.ELManager
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1892)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1735)
    ... 35 more

Dec 06, 2017 11:43:25 PM org.apache.catalina.core.StandardContext loadOnStartup
SEVERE: Servlet [dispatcher] in web application [/spring-mvc-demo] threw load() exception
java.lang.ClassNotFoundException: javax.el.ELManager
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1892)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1735)
    at org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator.buildExpressionFactory(ResourceBundleMessageInterpolator.java:88)
    at org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator.<init>(ResourceBundleMessageInterpolator.java:47)
    at org.hibernate.validator.internal.engine.ConfigurationImpl.getDefaultMessageInterpolator(ConfigurationImpl.java:461)
    at org.springframework.validation.beanvalidation.LocalValidatorFactoryBean.afterPropertiesSet(LocalValidatorFactoryBean.java:267)
    at org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean.afterPropertiesSet(OptionalValidatorFactoryBean.java:40)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1769)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1706)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:583)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:758)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:868)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:676)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:642)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:690)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:558)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:499)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:172)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1269)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1182)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1072)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5362)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5660)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1700)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1690)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

Dec 06, 2017 11:43:25 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
Dec 06, 2017 11:43:25 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
Dec 06, 2017 11:43:25 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 3248 ms
Dec 06, 2017 11:43:26 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'dispatcher'
Dec 06, 2017 11:43:26 PM org.springframework.web.servlet.FrameworkServlet initServletBean
INFO: FrameworkServlet 'dispatcher': initialization started
Dec 06, 2017 11:43:26 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing WebApplicationContext for namespace 'dispatcher-servlet': startup date [Wed Dec 06 23:43:26 EST 2017]; root of context hierarchy
Dec 06, 2017 11:43:26 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/spring-mvc-demo-servlet.xml]
Dec 06, 2017 11:43:26 PM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry register
INFO: Mapped "{[/customer/showForm]}" onto public java.lang.String com.luv2code.springdemo.mvc.CustomerController.showForm(org.springframework.ui.Model)
Dec 06, 2017 11:43:26 PM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry register
INFO: Mapped "{[/customer/processForm]}" onto public java.lang.String com.luv2code.springdemo.mvc.CustomerController.processForm(com.luv2code.springdemo.mvc.Customer,org.springframework.validation.BindingResult)
Dec 06, 2017 11:43:26 PM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry register
INFO: Mapped "{[/]}" onto public java.lang.String com.luv2code.springdemo.mvc.HomeController.showPage()
Dec 06, 2017 11:43:26 PM org.springframework.context.support.AbstractApplicationContext refresh
WARNING: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean#0': Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: javax/el/ELManager

but when I run on tomcat, it shows "HTTP Status 500 - Servlet.init() for servlet dispatcher threw exception", and description "description The server encountered an internal error that prevented it from fulfilling this request."  Actually I tried some easy spring code earlier today, it works. And this time I tried to use validation api and copy some hibernate files to lib, but failed. Anyone could help me out? Thanks!


问:
Laravel create array from model
I am trying to format the output of an Eloquent query to use in Highmaps

My code:

```<code>$regsByCtry = $regsByCtryArr->pluck('ctry', 'val')->map(function($country, $value) {
    return [
        "hc-key" => $country,
        "value"  => $value
    ];
})->toJson();
</code>```

Outputs:

```<code>"{
  "1": {"hc-key":"br","value":1},
  "5": {"hc-key":"au","value":5}
 }"
</code>```

I am trying to output the JSON without the keys, as an collection of objects:

```<code>"{
  {"hc-key":"br","value":1},
  {"hc-key":"au","value":5}
 }"
</code>```

Thanks for the help.

答:
Use values chained method</p>

```<code>$regsByCtry = $regsByCtryArr->pluck('ctry', 'val')->values()->map(function($country, $value) {
    return [
        "hc-key" => $country,
        "value"  => $value
    ];
})->values()->toJson();
</code>```

Title: Laravel create array from model

Body:
I am trying to format the output of an Eloquent query to use in Highmaps

My code:

$regsByCtry = $regsByCtryArr->pluck('ctry', 'val')->map(function($country, $value) {
    return [
        "hc-key" => $country,
        "value"  => $value
    ];
})->toJson();

Outputs:

"{
  "1": {"hc-key":"br","value":1},
  "5": {"hc-key":"au","value":5}
 }"

I am trying to output the JSON without the keys, as an collection of objects:

"{
  {"hc-key":"br","value":1},
  {"hc-key":"au","value":5}
 }"

Thanks for the help.

Body:
Use values chained method

$regsByCtry = $regsByCtryArr->pluck('ctry', 'val')->values()->map(function($country, $value) {
    return [
        "hc-key" => $country,
        "value"  => $value
    ];
})->values()->toJson();


问:
Reference External Javascript Library in .html files with angular-cli
Receiving error 404 referencing a legacy javascript library in angular application. My question is why?

These are the characteristics of my build environment

Angular CLI: 1.6.0

Node: 7.10.0

OS: win32 x64

Angular: 4.4.6

The image below shows the  tag in the index.html referencing the chart.js javascript file that was installed using node. I have checked the path and determined that the file is present at that location and would like to understand why I can't reference the javascript file directly in my html with the location in node_modules.

The image below shows the error that I receive trying to reference the javascript file in my html using the script tag

If a workaround is the answer, can the answer also contain the reason why the workaround is necessary using angular?

答:
Usually in webservers you have to define specific folders that are presented to the public. It is always depending on your webserver but you can usually add new folders that can be accessed by something like a browser. Otherwise all your content may just be public, which is usually not what you want.

In your case it just seems like your webserver does not use the node_modules folder for public access, so if you want to use that script inside of it you probably have to declare it as a public folder. This is of course dependent on your server, here's an example for nodejs with express framework.

app.use(express.static('node_modules'));


问:
onDrawerClosed and onDrawerOpened not being called
I am playing with the DrawerListener , and unfortunately the official documentation is not quite detailed, not to say there aren't any examples  given.

All I want to test is showing a Toast message when the Drawer closes, but its just not happening, its not being called at all, any ideas  ? Below the code

```<code>public class MainActivity extends ActionBarActivity implements DrawerLayout.DrawerListener {

  DrawerLayout.DrawerListener mele;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final DrawerLayout olia=(DrawerLayout)findViewById(R.id.container);

    ListView meka=(ListView)findViewById(R.id.left_drawer);

    String [] karo={"meka","deka","beka"};

    ArrayAdapter<String> mera=new ArrayAdapter<String>     ( this,android.R.layout.simple_list_item_1,karo);

    meka.setAdapter(mera);

     olia.setDrawerListener(mele);

    meka.setOnItemClickListener(new OnItemClickListener () {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            // TODO Auto-generated method stub

              olia.closeDrawers();
        }

    });

}

@Override
public void onDrawerClosed(View arg0) {
    // TODO Auto-generated method stub

    Toast.makeText(MainActivity.this, "OK Opened", Toast.LENGTH_LONG).show();
    Log.d("meke", "CLOSED  DRAWER" );
}
</code>```

答:
i have created a sample app for your issue Please check the solution , Now its working fine.</p>

```<code>    public class YourActivity extends AppCompatActivity implements  DrawerLayout.DrawerListener {

    DrawerLayout drawer;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dash_board);
 final DrawerLayout olia=(DrawerLayout)findViewById(R.id.container);
        olia.setDrawerListener(this);
    }//onCreate()

    @Override
    public void onDrawerOpened(View arg0) {
      //write your code
    }

    @Override
    public void onDrawerClosed(View arg0) {

    }

    @Override
    public void onDrawerSlide(View arg0, float arg1) {
        //write your code
    }

    @Override
    public void onDrawerStateChanged(int arg0) {
        //write your code
    }
}//class
</code>```

Body:
I am playing with the DrawerListener , and unfortunately the official documentation is not quite detailed, not to say there aren't any examples  given.

All I want to test is showing a Toast message when the Drawer closes, but its just not happening, its not being called at all, any ideas  ? Below the code

public class MainActivity extends ActionBarActivity implements DrawerLayout.DrawerListener {

  DrawerLayout.DrawerListener mele;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final DrawerLayout olia=(DrawerLayout)findViewById(R.id.container);

    ListView meka=(ListView)findViewById(R.id.left_drawer);

    String [] karo={"meka","deka","beka"};

    ArrayAdapter<String> mera=new ArrayAdapter<String>     ( this,android.R.layout.simple_list_item_1,karo);

    meka.setAdapter(mera);

     olia.setDrawerListener(mele);

    meka.setOnItemClickListener(new OnItemClickListener () {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            // TODO Auto-generated method stub

              olia.closeDrawers();
        }

    });

}

@Override
public void onDrawerClosed(View arg0) {
    // TODO Auto-generated method stub

    Toast.makeText(MainActivity.this, "OK Opened", Toast.LENGTH_LONG).show();
    Log.d("meke", "CLOSED  DRAWER" );
}

Body:
i have created a sample app for your issue Please check the solution , Now its working fine.

    public class YourActivity extends AppCompatActivity implements  DrawerLayout.DrawerListener {

    DrawerLayout drawer;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dash_board);
 final DrawerLayout olia=(DrawerLayout)findViewById(R.id.container);
        olia.setDrawerListener(this);
    }//onCreate()

    @Override
    public void onDrawerOpened(View arg0) {
      //write your code
    }

    @Override
    public void onDrawerClosed(View arg0) {

    }

    @Override
    public void onDrawerSlide(View arg0, float arg1) {
        //write your code
    }

    @Override
    public void onDrawerStateChanged(int arg0) {
        //write your code
    }
}//class


问:
Can ffmpeg convert audio to raw PCM? If so, how?
I'm currently using ffmpeg to convert FLV/Speex to WAV/pcm_s16le, successfully.  However, I now need the output format to be RAW, that is, PCM signed 16-bit little endian, without the WAV header.  I tried the following:

```<code>ffmpeg -y -i input.flv -vn -acodec pcm_s16le output.raw
</code>```

But ffmpeg responds with:

```<code>Unable to find a suitable output format for 'output.raw'
</code>```

I also tried using output.pcm and output as output file names, with the same result.

I also tried the -f flag to specify raw format, but that gives:

```<code>Unknown input or output format: raw
</code>```

Is this possible with FFmpeg?  If so, how?

答:
convert mp4 file to pcm

```<code>ffmpeg -y  -i input.mp4  -acodec pcm_s16le -f s16le -ac 1 -ar 16000 output.pcm
</code>```

you can also use it to convert mp3 to pcm

```<code>ffmpeg -y  -i input.mp3  -acodec pcm_s16le -f s16le -ac 1 -ar 16000 output.pcm
</code>```

key params means:

```<code>-f s16le … PCM signed 16-bit little-endian samples

-ac 1 … 1 channel (mono)

-ar 16000 … sample rate 16000Hz
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm currently using ffmpeg to convert FLV/Speex to WAV/pcm_s16le, successfully.  However, I now need the output format to be RAW, that is, PCM signed 16-bit little endian, without the WAV header.  I tried the following:

ffmpeg -y -i input.flv -vn -acodec pcm_s16le output.raw

But ffmpeg responds with:

Unable to find a suitable output format for 'output.raw'

I also tried using output.pcm and output as output file names, with the same result.

I also tried the -f flag to specify raw format, but that gives:

Unknown input or output format: raw

Is this possible with FFmpeg?  If so, how?

Body:
convert mp4 file to pcm

ffmpeg -y  -i input.mp4  -acodec pcm_s16le -f s16le -ac 1 -ar 16000 output.pcm

you can also use it to convert mp3 to pcm

ffmpeg -y  -i input.mp3  -acodec pcm_s16le -f s16le -ac 1 -ar 16000 output.pcm

key params means:

-f s16le … PCM signed 16-bit little-endian samples

-ac 1 … 1 channel (mono)

-ar 16000 … sample rate 16000Hz


问:
on Event Clicked issue
I'm using Bootstrap 4 Beta and JavaScript for my university project, I'm making some calendar event function. and I'm used Bootbox.js  for popup, my issue is When I click the calendar event alert is display but this alert cant customize ,I want to know how to added
 <button> text and etc for this alert, look my attached image, you can understand it

This is my script,

event

```<code> dp.events.list = [{
      start: "2017-12-20",
      end: "2017-12-28",
      id: "1",
         resource: "A",
      text: "Mahesh",
      backColor: "#70CB85",

    },
</code>```

click

```<code>dp.onEventClicked = function(args) {
 bootbox.alert(" " + args.e.text()); //Alert
};
</code>```

答:
you can put html in alert easily .

```<code>bootbox.alert("Your message <b>here…</b>")
</code>```

see this link for more option of alert

Title: on Event Clicked issue

Body:
I'm using Bootstrap 4 Beta and JavaScript for my university project, I'm making some calendar event function. and I'm used Bootbox.js  for popup, my issue is When I click the calendar event alert is display but this alert cant customize ,I want to know how to added
 <button> text and etc for this alert, look my attached image, you can understand it

This is my script,

event

 dp.events.list = [{
      start: "2017-12-20",
      end: "2017-12-28",
      id: "1",
         resource: "A",
      text: "Mahesh",
      backColor: "#70CB85",

    },

click

dp.onEventClicked = function(args) {
 bootbox.alert(" " + args.e.text()); //Alert
};

Body:
you can put html in alert easily .

bootbox.alert("Your message <b>here…</b>")

see this link for more option of alert


问:
DataInputStream for input text files?
I am learning to read and write in Java and am stuck with a simple exercise. The program reads from 2 txt files that each contain numbers in rows. It writes to an output file the result of the multiplication of each row of numbers. eg. file 1 row 1 : 10, file 2 row 1: 2 , the program should write 20 to the output file. My code seems to have something missing somewhere. The output file is created but nothing is written to it. Any ideas?</p>

```<code>import java.io.*;
import java.util.*;

class ReadWriteData
{
    public static void main(String[] args) throws Exception
    {

        //create ouput file
        PrintWriter output = new PrintWriter("output2.txt");

        DataInputStream file1 = new DataInputStream(new FileInputStream(args[0]));
        DataInputStream file2 = new DataInputStream(new FileInputStream(args[1]));

        try
        {

        // read data from file
        while (true)
        {
            double number1 = file1.readDouble();
            double number2 = file2.readDouble();
            double result = number1 * number2 ;
            output.println(result);

        }

        }

        catch (IOException e)
        {
            System.err.println("Error");
            System.exit(1);
        }

        output.close() ;

    }
}
</code>```

答:
With this while (true) without a break your code is basically running in an infinite loop and never stopping unless there's an exception.

If it did terminate but you didn't see an exception, then it might be caused by calling System.exit(1) in the catch. It might be too late then to print "Error" anyway (the stdout might have been abrupted too early) and the file will never be flushed/closed. Remove that System.exit(1) line.

Also, closing is supposed to happen in finally block. And best is to not print some nothing-saying message on exception but just let them go. Since you already have a throws Exception on the method, just remove the entire catch. Only use it when you can handle exceptions in a sensible manner.

```<code>PrintWriter output = new PrintWriter("output2.txt");
try {
    output.println("something");
} finally {
    output.close();
}
</code>```

Title: DataInputStream for input text files?

Body:
I am learning to read and write in Java and am stuck with a simple exercise. The program reads from 2 txt files that each contain numbers in rows. It writes to an output file the result of the multiplication of each row of numbers. eg. file 1 row 1 : 10, file 2 row 1: 2 , the program should write 20 to the output file. My code seems to have something missing somewhere. The output file is created but nothing is written to it. Any ideas?

import java.io.*;
import java.util.*;

class ReadWriteData
{
    public static void main(String[] args) throws Exception
    {

        //create ouput file
        PrintWriter output = new PrintWriter("output2.txt");

        DataInputStream file1 = new DataInputStream(new FileInputStream(args[0]));
        DataInputStream file2 = new DataInputStream(new FileInputStream(args[1]));

        try
        {

        // read data from file
        while (true)
        {
            double number1 = file1.readDouble();
            double number2 = file2.readDouble();
            double result = number1 * number2 ;
            output.println(result);

        }

        }

        catch (IOException e)
        {
            System.err.println("Error");
            System.exit(1);
        }

        output.close() ;

    }
}

Body:
With this while (true) without a break your code is basically running in an infinite loop and never stopping unless there's an exception.

If it did terminate but you didn't see an exception, then it might be caused by calling System.exit(1) in the catch. It might be too late then to print "Error" anyway (the stdout might have been abrupted too early) and the file will never be flushed/closed. Remove that System.exit(1) line.

Also, closing is supposed to happen in finally block. And best is to not print some nothing-saying message on exception but just let them go. Since you already have a throws Exception on the method, just remove the entire catch. Only use it when you can handle exceptions in a sensible manner.

PrintWriter output = new PrintWriter("output2.txt");
try {
    output.println("something");
} finally {
    output.close();
}


问:
What is the meaning and usage of __stdcall?
I've come across __stdcall a lot these days.

MSDN doesn't explain very clearly what it really means, when and why should it be used, if at all.

I would appreciate if someone would provide an explanation, preferably with an example or two.

答:
__stdcall is the calling convention used for the function. This tells the compiler the rules that apply for setting up the stack, pushing arguments and getting a return value. There are a number of other calling conventions like __cdecl, __thiscall, __fastcall and __naked.

__stdcall is the standard calling convention for Win32 system calls.

More details can be found on Wikipedia.