问:
Identical Dataframes Asserting Not Equal - Python Pandas
I am trying to unit test my code. I have a method that given a MySQL query, returns the result as a pandas dataframe. Note that in the database, all returned values in created and external_id are NULL. Here is the test:

```<code>def test_get_data(self):

    ### SET UP

    self.report._query = "SELECT * FROM floor LIMIT 3";
    self.report._columns = ['id', 'facility_id', 'name', 'created', 'modified', 'external_id']
    self.d = {'id': p.Series([1, 2, 3]),
              'facility_id': p.Series([1, 1, 1]),
              'name': p.Series(['1st Floor', '2nd Floor', '3rd Floor']),
              'created': p.Series(['None', 'None', 'None']),
              'modified': p.Series([datetime.strptime('2012-10-06 01:08:27', '%Y-%m-%d %H:%M:%S'),
                                    datetime.strptime('2012-10-06 01:08:27', '%Y-%m-%d %H:%M:%S'),
                                    datetime.strptime('2012-10-06 01:08:27', '%Y-%m-%d %H:%M:%S')]),
              'external_id': p.Series(['None', 'None', 'None'])
              }
    self.df = p.DataFrame(data=self.d, columns=['id', 'facility_id', 'name', 'created', 'modified', 'external_id'])
    self.df.fillna('None')
    print(self.df)
    ### CODE UNDER TEST

    result = self.report.get_data(self.report._cursor_web)
    print(result)
    ### ASSERTIONS

    assert_frame_equal(result, self.df)
</code>```

Here is the console output (note the print statements in the test code. The manually constructed dataframe is on top, the one derived from the function being tested is on the bottom):

```<code>.   id  facility_id       name created            modified external_id
0   1            1  1st Floor    None 2012-10-06 01:08:27        None
1   2            1  2nd Floor    None 2012-10-06 01:08:27        None
2   3            1  3rd Floor    None 2012-10-06 01:08:27        None
   id  facility_id       name created            modified external_id
0   1            1  1st Floor    None 2012-10-06 01:08:27        None
1   2            1  2nd Floor    None 2012-10-06 01:08:27        None
2   3            1  3rd Floor    None 2012-10-06 01:08:27        None
F
======================================================================
FAIL: test_get_data (__main__.ReportTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/path/to/file/ReportsTestCase.py", line 46, in test_get_data
    assert_frame_equal(result, self.df)
   File "/usr/local/lib/python2.7/site-packages/pandas/util/testing.py", line 1313, in assert_frame_equal
obj='DataFrame.iloc[:, {0}]'.format(i))
  File "/usr/local/lib/python2.7/site-packages/pandas/util/testing.py", line 1181, in assert_series_equal
obj='{0}'.format(obj))
  File "pandas/src/testing.pyx", line 59, in pandas._testing.assert_almost_equal (pandas/src/testing.c:4156)
  File "pandas/src/testing.pyx", line 173, in pandas._testing.assert_almost_equal (pandas/src/testing.c:3274)
  File "/usr/local/lib/python2.7/site-packages/pandas/util/testing.py", line 1018, in raise_assert_detail
raise AssertionError(msg)
</code>```

AssertionError: DataFrame.iloc[:, 3] are different

```<code>DataFrame.iloc[:, 3] values are different (100.0 %)
[left]:  [None, None, None]
[right]: [None, None, None]

----------------------------------------------------------------------
Ran 1 test in 0.354s

FAILED (failures=1)
</code>```

By my reckoning, column 'created' contains three string values of 'None' in both the left and right dataframes. Why is it asserting not equal?

答:
Python also has a built-in constant None that is different from the string 'None'. From the docs:

None

The sole value of the type NoneType. None is frequently used to
  represent the absence of a value, as when default arguments are not
  passed to a function. Assignments to None are illegal and raise a
  SyntaxError.

In the case of comparing None  against 'None' (None == 'None') the result will be False. Therefore, assert_frame_equal will raise an AssertionError if one of the DataFrames contains None  but the other contains 'None'.

Body:
I am trying to unit test my code. I have a method that given a MySQL query, returns the result as a pandas dataframe. Note that in the database, all returned values in created and external_id are NULL. Here is the test:

def test_get_data(self):

    ### SET UP

    self.report._query = "SELECT * FROM floor LIMIT 3";
    self.report._columns = ['id', 'facility_id', 'name', 'created', 'modified', 'external_id']
    self.d = {'id': p.Series([1, 2, 3]),
              'facility_id': p.Series([1, 1, 1]),
              'name': p.Series(['1st Floor', '2nd Floor', '3rd Floor']),
              'created': p.Series(['None', 'None', 'None']),
              'modified': p.Series([datetime.strptime('2012-10-06 01:08:27', '%Y-%m-%d %H:%M:%S'),
                                    datetime.strptime('2012-10-06 01:08:27', '%Y-%m-%d %H:%M:%S'),
                                    datetime.strptime('2012-10-06 01:08:27', '%Y-%m-%d %H:%M:%S')]),
              'external_id': p.Series(['None', 'None', 'None'])
              }
    self.df = p.DataFrame(data=self.d, columns=['id', 'facility_id', 'name', 'created', 'modified', 'external_id'])
    self.df.fillna('None')
    print(self.df)
    ### CODE UNDER TEST

    result = self.report.get_data(self.report._cursor_web)
    print(result)
    ### ASSERTIONS

    assert_frame_equal(result, self.df)

Here is the console output (note the print statements in the test code. The manually constructed dataframe is on top, the one derived from the function being tested is on the bottom):

.   id  facility_id       name created            modified external_id
0   1            1  1st Floor    None 2012-10-06 01:08:27        None
1   2            1  2nd Floor    None 2012-10-06 01:08:27        None
2   3            1  3rd Floor    None 2012-10-06 01:08:27        None
   id  facility_id       name created            modified external_id
0   1            1  1st Floor    None 2012-10-06 01:08:27        None
1   2            1  2nd Floor    None 2012-10-06 01:08:27        None
2   3            1  3rd Floor    None 2012-10-06 01:08:27        None
F
======================================================================
FAIL: test_get_data (__main__.ReportTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/path/to/file/ReportsTestCase.py", line 46, in test_get_data
    assert_frame_equal(result, self.df)
   File "/usr/local/lib/python2.7/site-packages/pandas/util/testing.py", line 1313, in assert_frame_equal
obj='DataFrame.iloc[:, {0}]'.format(i))
  File "/usr/local/lib/python2.7/site-packages/pandas/util/testing.py", line 1181, in assert_series_equal
obj='{0}'.format(obj))
  File "pandas/src/testing.pyx", line 59, in pandas._testing.assert_almost_equal (pandas/src/testing.c:4156)
  File "pandas/src/testing.pyx", line 173, in pandas._testing.assert_almost_equal (pandas/src/testing.c:3274)
  File "/usr/local/lib/python2.7/site-packages/pandas/util/testing.py", line 1018, in raise_assert_detail
raise AssertionError(msg)

AssertionError: DataFrame.iloc[:, 3] are different

DataFrame.iloc[:, 3] values are different (100.0 %)
[left]:  [None, None, None]
[right]: [None, None, None]

----------------------------------------------------------------------
Ran 1 test in 0.354s

FAILED (failures=1)

By my reckoning, column 'created' contains three string values of 'None' in both the left and right dataframes. Why is it asserting not equal?


来源: stackexchange

问:
Why do I have to hold down a cell in my tableview to open it?
It seems like with a few apps that I've made and launched to my IPhone, I have to hold down on a table view cell to before any functionally I programmed happens. Can anyone tell me why, and how to fix it?

here is an example

```<code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let message = messages[indexPath.row]
    let chatPartnerId: String?
    if message.fromId == FIRAuth.auth()?.currentUser?.uid{
        chatPartnerId = message.toId
    }else{
        chatPartnerId = message.fromId
    }

    let ref = FIRDatabase.database().reference().child("users").child(chatPartnerId!)
    ref.observeSingleEvent(of: .value, with: { (snapshot) in
        guard let dictionary = snapshot.value as? [String:AnyObject] else{
            return
        }
        let user = User()
        user.uid = chatPartnerId
        user.setValuesForKeys(dictionary)
        chosenUser = user
        self.performSegue(withIdentifier: "chatLog1", sender: nil)
    })

}
</code>```

答:
Instead of using the didSelectRowAt:indexPath method you could use the didHighlightRowAt:indexPath method like this:</p>

```<code>   func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) {
        self.performSegue(withIdentifier: "chatLog1", sender: nil)
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
It seems like with a few apps that I've made and launched to my IPhone, I have to hold down on a table view cell to before any functionally I programmed happens. Can anyone tell me why, and how to fix it?

here is an example

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let message = messages[indexPath.row]
    let chatPartnerId: String?
    if message.fromId == FIRAuth.auth()?.currentUser?.uid{
        chatPartnerId = message.toId
    }else{
        chatPartnerId = message.fromId
    }

    let ref = FIRDatabase.database().reference().child("users").child(chatPartnerId!)
    ref.observeSingleEvent(of: .value, with: { (snapshot) in
        guard let dictionary = snapshot.value as? [String:AnyObject] else{
            return
        }
        let user = User()
        user.uid = chatPartnerId
        user.setValuesForKeys(dictionary)
        chosenUser = user
        self.performSegue(withIdentifier: "chatLog1", sender: nil)
    })

}

Body:
Instead of using the didSelectRowAt:indexPath method you could use the didHighlightRowAt:indexPath method like this:

   func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) {
        self.performSegue(withIdentifier: "chatLog1", sender: nil)
    }


问:
How can I change color efficiently for right/wrong characters in a typing speed test?
I was doing an exercise involving a typing speed test. I added a color palette that makes the whole text green if the character matches the test text and red if it does not match.

If I wanted individual characters to change though, all the ways I can think of going about this seem quite tedious. I've tried creating individual span tags every time a character is entered and assigning them to the array value of the text string but haven't been able to get it to work. Is there a more efficient way to do this or is my current method the "best" way to go about it?

I would much more prefer a general path to solve this as opposed to someone just writing out a complete solution so I can write it out on my own please.

const testWrapper = document.querySelector(".test-wrapper");
const testArea = document.querySelector("#test-area");
const originText = document.querySelector("#origin-text p").innerHTML;
const resetButton = document.querySelector("#reset");
const theTimer = document.querySelector(".timer");
var interval;
var timer = [0,0,0,0];
var timerRunning = false;

// Add leading zero to numbers 9 or below (purely for aesthetics):
function leadingZero(time) {
 if (time <= 9) {
  time = "0" + time;
 }
 return time;
}

// Run a standard minute/second/hundredths timer:
function runTimer() {
 let currentTime = leadingZero(timer[0]) + ":" + leadingZero(timer[1]) + ":" + leadingZero(timer[2]);
 theTimer.innerHTML = currentTime;
 timer[3]++;

 timer[0] = Math.floor((timer[3]/100)/60);
 timer[1] = Math.floor((timer[3]/100) - (timer[0] * 60));
 timer[2] = Math.floor(timer[3] - (timer[1] * 100) - (timer[0] * 6000));
}

// Match the text entered with the provided text on the page:
function spellCheck() {
 let textEntered = testArea.value;
 let originTextMatch = originText.substring(0,textEntered.length);
 if (textEntered == originText) {
  testWrapper.style.borderColor = "#429890";
  clearInterval(interval);
 } else {
  if (textEntered == originTextMatch) {
   testWrapper.style.borderColor = "#65ccf3";
   testArea.style.color = "#00B400";
  } else {
   testWrapper.style.borderColor = "#e95d0f";
   testArea.style.color = "#FF0000"
  }
 }
}

// Start the timer:
function start() {
 let textEnteredLength = testArea.value.length;
 if(textEnteredLength === 0 && !timerRunning) {
  timerRunning = true;
  interval = setInterval(runTimer, 10);
 }
}

// Reset everything:
function reset(){
 timer = [0,0,0,0];
 theTimer.innerHTML = "00:00:00";
 clearInterval(interval);
 testArea.value = "";
 timerRunning = false;
 console.log("The reset button has been pressed.");
}

// Event listeners for keyboard input and the reset button:
testArea.addEventListener("keypress", start, false);
testArea.addEventListener("keyup", spellCheck, false);
resetButton.addEventListener("click", reset, false);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/*--------------------------------------------------------------
Typography
--------------------------------------------------------------*/

body,
button,
input,
select,
textarea {
 font-family: 'Source Sans Pro', 'Helvetica', Arial, sans-serif;
 font-size: 18px;
 line-height: 1.5;
}

h1,
h2,
h3,
h4,
h5,
h6 {
 clear: both;
}

p {
 margin-bottom: 1.5em;
}

b,
strong {
 font-weight: bold;
}

dfn,
cite,
em,
i {
 font-style: italic;
}

blockquote {
 margin: 0 1.5em;
}

address {
 margin: 0 0 1.5em;
}

pre {
 background: #eee;
 font-family: "Courier 10 Pitch", Courier, monospace;
 font-size: 15px;
 font-size: 1.5rem;
 line-height: 1.6;
 margin-bottom: 1.6em;
 max-width: 100%;
 overflow: auto;
 padding: 1.6em;
}

code,
kbd,
tt,
var {
 font: 15px Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace;
}

abbr,
acronym {
 border-bottom: 1px dotted #666;
 cursor: help;
}

mark,
ins {
 background: #fff9c0;
 text-decoration: none;
}

sup,
sub {
 font-size: 75%;
 height: 0;
 line-height: 0;
 position: relative;
 vertical-align: baseline;
}

sup {
 bottom: 1ex;
}

sub {
 top: .5ex;
}

small {
 font-size: 75%;
}

big {
 font-size: 125%;
}

/*--------------------------------------------------------------
Layout
--------------------------------------------------------------*/
body {
    margin: 0;
    padding: 0;
}

.masthead {
    padding: 1em 2em;
    background-color: #0D1B2E;
    color: white;
}

.masthead h1 {
    text-align: center;
}

.intro {
    padding: 2em 2em;
    color: #ffffff;
    background: #429890;
}

.intro p,
.test-area {
    margin: 0 auto;
    max-width: 550px;
}

.test-area {
    margin-bottom: 4em;
    padding: 0 2em;
}

.test-wrapper {
    border: 10px solid grey;
    border-radius: 10px;
}

#origin-text {
    margin: 1em 0;
    padding: 1em 1em 0;
    background-color: #ededed;
}

#origin-text p {
    margin: 0;
    padding-bottom: 1em;
}

.test-wrapper {
    display: flex;
}

.test-wrapper textarea {
    flex: 1;
}

.meta {
    margin-top: 1em;
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
}

.timer {
    font-size: 3em;
    font-weight: bold;
}

#reset {
    padding: .5em 1em;
    font-size: 1.2em;
    font-weight: bold;
    color: #E95D0F;
    background: white ;
    border: 10px solid #E95D0F;
}

#reset:hover {
    color: white;
    background-color: #E95D0F;
}</code>```

Test Your Typing Speed

This is a typing test. Your goal is to duplicate the provided text, EXACTLY, in the field below. The timer starts when you start typing, and only stops when you match this text exactly. Good Luck!

The text to test.

                <textarea id="test-area" name="textarea" rows="6" placeholder="The clock starts when you start typing."></textarea>

00:00:00

                <button id="reset">Start over</button>

    ```

答:
If efficiency is your question, I would say to use an MVVM framework such as KnockoutJS or Angular, then it's really easy to determine differences and keeps the code real clean.

I'd split the text to copy into two, side by side:
1. Text typed | 2. Text to copy

With a separate box to type into.

You would subtract what you type upon key press, probably bassed on string length, from 2.text to copy, and put it into 1.text typed.

Use a calculated method to determine if it matched, and set the class on 1.text typed accordingly.

Body:
I was doing an exercise involving a typing speed test. I added a color palette that makes the whole text green if the character matches the test text and red if it does not match.

If I wanted individual characters to change though, all the ways I can think of going about this seem quite tedious. I've tried creating individual span tags every time a character is entered and assigning them to the array value of the text string but haven't been able to get it to work. Is there a more efficient way to do this or is my current method the "best" way to go about it?

I would much more prefer a general path to solve this as opposed to someone just writing out a complete solution so I can write it out on my own please.

const testWrapper = document.querySelector(".test-wrapper");
const testArea = document.querySelector("#test-area");
const originText = document.querySelector("#origin-text p").innerHTML;
const resetButton = document.querySelector("#reset");
const theTimer = document.querySelector(".timer");
var interval;
var timer = [0,0,0,0];
var timerRunning = false;

// Add leading zero to numbers 9 or below (purely for aesthetics):
function leadingZero(time) {
 if (time <= 9) {
  time = "0" + time;
 }
 return time;
}

// Run a standard minute/second/hundredths timer:
function runTimer() {
 let currentTime = leadingZero(timer[0]) + ":" + leadingZero(timer[1]) + ":" + leadingZero(timer[2]);
 theTimer.innerHTML = currentTime;
 timer[3]++;

 timer[0] = Math.floor((timer[3]/100)/60);
 timer[1] = Math.floor((timer[3]/100) - (timer[0] * 60));
 timer[2] = Math.floor(timer[3] - (timer[1] * 100) - (timer[0] * 6000));
}

// Match the text entered with the provided text on the page:
function spellCheck() {
 let textEntered = testArea.value;
 let originTextMatch = originText.substring(0,textEntered.length);
 if (textEntered == originText) {
  testWrapper.style.borderColor = "#429890";
  clearInterval(interval);
 } else {
  if (textEntered == originTextMatch) {
   testWrapper.style.borderColor = "#65ccf3";
   testArea.style.color = "#00B400";
  } else {
   testWrapper.style.borderColor = "#e95d0f";
   testArea.style.color = "#FF0000"
  }
 }
}

// Start the timer:
function start() {
 let textEnteredLength = testArea.value.length;
 if(textEnteredLength === 0 && !timerRunning) {
  timerRunning = true;
  interval = setInterval(runTimer, 10);
 }
}

// Reset everything:
function reset(){
 timer = [0,0,0,0];
 theTimer.innerHTML = "00:00:00";
 clearInterval(interval);
 testArea.value = "";
 timerRunning = false;
 console.log("The reset button has been pressed.");
}

// Event listeners for keyboard input and the reset button:
testArea.addEventListener("keypress", start, false);
testArea.addEventListener("keyup", spellCheck, false);
resetButton.addEventListener("click", reset, false);

/*--------------------------------------------------------------
Typography
--------------------------------------------------------------*/

body,
button,
input,
select,
textarea {
 font-family: 'Source Sans Pro', 'Helvetica', Arial, sans-serif;
 font-size: 18px;
 line-height: 1.5;
}

h1,
h2,
h3,
h4,
h5,
h6 {
 clear: both;
}

p {
 margin-bottom: 1.5em;
}

b,
strong {
 font-weight: bold;
}

dfn,
cite,
em,
i {
 font-style: italic;
}

blockquote {
 margin: 0 1.5em;
}

address {
 margin: 0 0 1.5em;
}

pre {
 background: #eee;
 font-family: "Courier 10 Pitch", Courier, monospace;
 font-size: 15px;
 font-size: 1.5rem;
 line-height: 1.6;
 margin-bottom: 1.6em;
 max-width: 100%;
 overflow: auto;
 padding: 1.6em;
}

code,
kbd,
tt,
var {
 font: 15px Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace;
}

abbr,
acronym {
 border-bottom: 1px dotted #666;
 cursor: help;
}

mark,
ins {
 background: #fff9c0;
 text-decoration: none;
}

sup,
sub {
 font-size: 75%;
 height: 0;
 line-height: 0;
 position: relative;
 vertical-align: baseline;
}

sup {
 bottom: 1ex;
}

sub {
 top: .5ex;
}

small {
 font-size: 75%;
}

big {
 font-size: 125%;
}

/*--------------------------------------------------------------
Layout
--------------------------------------------------------------*/
body {
    margin: 0;
    padding: 0;
}

.masthead {
    padding: 1em 2em;
    background-color: #0D1B2E;
    color: white;
}

.masthead h1 {
    text-align: center;
}

.intro {
    padding: 2em 2em;
    color: #ffffff;
    background: #429890;
}

.intro p,
.test-area {
    margin: 0 auto;
    max-width: 550px;
}

.test-area {
    margin-bottom: 4em;
    padding: 0 2em;
}

.test-wrapper {
    border: 10px solid grey;
    border-radius: 10px;
}

#origin-text {
    margin: 1em 0;
    padding: 1em 1em 0;
    background-color: #ededed;
}

#origin-text p {
    margin: 0;
    padding-bottom: 1em;
}

.test-wrapper {
    display: flex;
}

.test-wrapper textarea {
    flex: 1;
}

.meta {
    margin-top: 1em;
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
}

.timer {
    font-size: 3em;
    font-weight: bold;
}

#reset {
    padding: .5em 1em;
    font-size: 1.2em;
    font-weight: bold;
    color: #E95D0F;
    background: white ;
    border: 10px solid #E95D0F;
}

#reset:hover {
    color: white;
    background-color: #E95D0F;
}

Test Your Typing Speed

This is a typing test. Your goal is to duplicate the provided text, EXACTLY, in the field below. The timer starts when you start typing, and only stops when you match this text exactly. Good Luck!

The text to test.

                <textarea id="test-area" name="textarea" rows="6" placeholder="The clock starts when you start typing."></textarea>

00:00:00

                <button id="reset">Start over</button>


问:
Setting default value for <select/> using ng-options with (key, value) in angularjs
I want to set a default value for the following select:

```<code><select ng-model="selected"
      ng-options="key as value.Name for (key, value) in attributes">
</select>
</code>```

I use attributes as a map with an id as key and an object as value. I want to show the name of the value in the select-box, but bind the key to the model, because when I access selected, I need the id, not the name.
This works but now I want to set a default value. The default value must also show value.Name, but bind id.

According to this, it should work something like this:

```<code>$scope.selected = { 1: {Name : "Attribute1"}};
</code>```

I haven't made it yet. I would appreciate any help.

EDIT:

My attributes variable looks like this (TypeScript):

```<code>export interface IAttributes {
    [id: number]: IAttributeProperties;
}

export interface IAttributeProperties {
    Name: string;
    DataType: string;
}
</code>```

答:
The solution was to set the following default value:

```<code>$scope.selected = '1';
</code>```

So I just needed to set the id (key). In the select box was displayed "Attribute1" now and the related id is bound.

Body:
I want to set a default value for the following select:

<select ng-model="selected"
      ng-options="key as value.Name for (key, value) in attributes">
</select>

I use attributes as a map with an id as key and an object as value. I want to show the name of the value in the select-box, but bind the key to the model, because when I access selected, I need the id, not the name.
This works but now I want to set a default value. The default value must also show value.Name, but bind id.

According to this, it should work something like this:

$scope.selected = { 1: {Name : "Attribute1"}};

I haven't made it yet. I would appreciate any help.

EDIT:

My attributes variable looks like this (TypeScript):

export interface IAttributes {
    [id: number]: IAttributeProperties;
}

export interface IAttributeProperties {
    Name: string;
    DataType: string;
}

Body:
The solution was to set the following default value:

$scope.selected = '1';

So I just needed to set the id (key). In the select box was displayed "Attribute1" now and the related id is bound.


问:
Using tortoise for existing project
my project is connected to svn repository by eclipse plugin, and by tortoise, i used to checkout and update my code from both tools, the problem appeared when i needed to update tortoise, now i cant find any thing related to tortoise in the context menu from windows, its like i need to download the project again with tortoise .... is there any way to do it without re download the code... (i have many changes and cant commit from eclipse, need to use tortoise).  </p>

答: Checkout to a new directory, replace the files you need to update on the repository and then do the commit, that might be the easiest and safest way.</p>

ContentLicense: CC BY-SA 2.5

Title: Using tortoise for existing project


问:
LINQ Contains clause - more then one value in criteria
I have a collection which is filtered based on criteria for which I am using contains clause given below.
I am further creating a new collection based on filtered records and returning the same.

Issue:

If I have more then one value in "multipleCodes" which is used in contains clause.. it does not work.
If I put only 1 value... it does work.

Any idea what am I missing ? or is there any better approach to filter records and retrun only filtered resultset ?

```<code>collectionToFilter.Where(d => (d.Code.**Contains**(multipleCodes)) &&
                d.NeededDate > minNeedDate && d.NeededDate < maxNeedDate)
                    .ToList()
                    .ForEach(d => filteredCollection.Add(d));
</code>```

答:
From your comment I wanted to show you a cleaner and more readable answer.  </p>

```<code>var _multipleCodes = multipleCodes.Split(',');
collectionToFilter.Where(d => _multipleCodes.Contains(d.Code));
</code>```

Body:
I have a collection which is filtered based on criteria for which I am using contains clause given below.
I am further creating a new collection based on filtered records and returning the same.

Issue:

If I have more then one value in "multipleCodes" which is used in contains clause.. it does not work.
If I put only 1 value... it does work.

Any idea what am I missing ? or is there any better approach to filter records and retrun only filtered resultset ?

collectionToFilter.Where(d => (d.Code.**Contains**(multipleCodes)) &&
                d.NeededDate > minNeedDate && d.NeededDate < maxNeedDate)
                    .ToList()
                    .ForEach(d => filteredCollection.Add(d));

Body:
From your comment I wanted to show you a cleaner and more readable answer.

var _multipleCodes = multipleCodes.Split(',');
collectionToFilter.Where(d => _multipleCodes.Contains(d.Code));


问:
Multiple Tomcat instances: Port already in use: 8086 (tried checking server.xml)
I have to run multiple Tomcat instance on app server (Apache Tomcat 7.0.33 and 7.0.42). Everything was working until last week. Now when I start one instance, another throws following error and couldn't start tomcat instance, and vice-a-versa. I thought of changing the port from 8086 to other, but there is no mention of port 8086 in both instance's config (conf/server.xml) files. How can I keep both instances running, without killing another instance?

Error:
2017-06-06 11:09:17 Commons Daemon procrun stderr initialized
Error: Exception thrown by the agent : java.rmi.server.ExportException: Port already in use: 8086; nested exception is:
    java.net.BindException: Address already in use: JVM_Bind

答:
It got resolved by removing one third party application which was using 8086 port. This port was mentioned in Java tab -> Java Options of the Apache Tomcat Properties.</p>

<p>-Dcom.sun.management.jmxremote.port=8086 </p>

Body:
It got resolved by removing one third party application which was using 8086 port. This port was mentioned in Java tab -> Java Options of the Apache Tomcat Properties.

-Dcom.sun.management.jmxremote.port=8086


问:
How to express in JSON schema all or none for multiple optional properties?
I want to express that all or none of optional properties are present. For example

```<code>{
}
</code>```

and

```<code>{
    "a" : 1,
    "b" : 2
}
</code>```

should be both valid, but

```<code>{
    "a" : 1
}
</code>```

and

```<code>{
    "b" : 2
}
</code>```

should be both invalid.

答:
A simpler way:</p>

```<code>{
"properties:" {
  "a" : {"type" : "integer"},
  "b" : {"type" : "integer"}
},
"dependencies" : {
  "a" : ["b"],
  "b" : ["a"]
}
}
</code>```

Body:
I want to express that all or none of optional properties are present. For example

{
}

and

{
    "a" : 1,
    "b" : 2
}

should be both valid, but

{
    "a" : 1
}

and

{
    "b" : 2
}

should be both invalid.

Body:
A simpler way:

{
"properties:" {
  "a" : {"type" : "integer"},
  "b" : {"type" : "integer"}
},
"dependencies" : {
  "a" : ["b"],
  "b" : ["a"]
}
}


问:
Firebase CrashReporting + Fabric
As announced by Google, the Firebase Crash Reporting is joining forces with Fabric. Here's a link

The exact details of how is this going to happen are abstract. But for developers who were using Firebase Crash Reporting, does this mean that they have to create a new account on Fabric and integrate its SDK and remove the one from Firebase?

I know I could wait until Google does the actual implementation, but switching from one SDK to another is not the best approach, if anyone has any insight on this...

答:
The following is the text from the Firebase console when looking at Crash Reporting for the first time without any existing data.  There's no additional information available about how exactly it's going to work.

Fabric’s Crashlytics

In the future, Fabric’s Crashlytics will become our primary crash
reporter because it provides advanced tools for solving stability
issues. If you’d like to be an early adopter, you can get a head start
by using Crashlytics on Fabric’s platform.

Crash Reporting

If you prefer to monitor stability in Firebase, you still have access
to Firebase Crash Reporting, which equips you with the essential tools
you need to track and resolve crashes. Eventually, Firebase Crash
Reporting will be seamlessly upgraded to Crashlytics.

Title: Firebase CrashReporting + Fabric


问:
android cannot open database
I have problem with work database in android. android cannot open database. my app only have this class and mainActivity class.
my code is:
`

```<code>public class G  {
public static Context        context;
public static SQLiteDatabase database;
public static final String   DIR_SDCARD   = Environment.getExternalStorageDirectory().getAbsolutePath();
public static final String   DIR_DATABASE = DIR_SDCARD + "/database-test";
@Override
public void onCreate() {
    super.onCreate();
    context = this.getApplicationContext();
   // new File(DIR_DATABASE).mkdirs();
    File file=new File(DIR_DATABASE);
    file.mkdirs();
    database = SQLiteDatabase.openOrCreateDatabase(DIR_DATABASE + "/database.sqlite", null);
    database.execSQL("CREATE  TABLE  IF NOT EXISTS person (person_name TEXT NOT NULL ," +
                " person_family TEXT NOT NULL , " +
                " person_password TEXT NOT NULL   )");
}
</code>```

and this error is:

```<code>06-06 19:44:23.978 24284-24284/com.example.khatere.mydatabasetests E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.khatere.mydatabasetests, PID: 24284
                                                                                java.lang.RuntimeException: Unable to create application com.example.khatere.mydatabasetests.G: android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
                                                                                at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5406)
                                                                                at android.app.ActivityThread.-wrap2(ActivityThread.java)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1545)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                                                                                Caused by: android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
                                                                                at android.database.sqlite.SQLiteConnection.nativeOpen(Native Method)
                                                                                at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:209)
                                                                                at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:193)
                                                                                at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
                                                                                at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
                                                                                at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
                                                                                at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:808)
                                                                                at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:793)
                                                                                at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:696)
                                                                                at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:711)
                                                                                at com.example.khatere.mydatabasetests.G.onCreate(G.java:29)
                                                                                at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1024)
</code>```

`
I have no idea for to solve this problem. please help me.

答:
Add the write permission to the Android Manifest

```<code><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</code>```

If you're running your app on API level 23 or greater you have to request permission at runtime.

Request permission:

```<code>String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestPermissions(permissions, WRITE_REQUEST_CODE);
</code>```

Then handle the result:

```<code>@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
       case WRITE_REQUEST_CODE:
         if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
           //Granted.
           //Continue with the database process

         }
       else{
           //Denied.
         }
        break;
    }
}
</code>```

For more information visit Requesting Permissions at Run Time - Android Doc

Title: android cannot open database

Body:
I have problem with work database in android. android cannot open database. my app only have this class and mainActivity class.
my code is:
`

public class G  {
public static Context        context;
public static SQLiteDatabase database;
public static final String   DIR_SDCARD   = Environment.getExternalStorageDirectory().getAbsolutePath();
public static final String   DIR_DATABASE = DIR_SDCARD + "/database-test";
@Override
public void onCreate() {
    super.onCreate();
    context = this.getApplicationContext();
   // new File(DIR_DATABASE).mkdirs();
    File file=new File(DIR_DATABASE);
    file.mkdirs();
    database = SQLiteDatabase.openOrCreateDatabase(DIR_DATABASE + "/database.sqlite", null);
    database.execSQL("CREATE  TABLE  IF NOT EXISTS person (person_name TEXT NOT NULL ," +
                " person_family TEXT NOT NULL , " +
                " person_password TEXT NOT NULL   )");
}

and this error is:

06-06 19:44:23.978 24284-24284/com.example.khatere.mydatabasetests E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.khatere.mydatabasetests, PID: 24284
                                                                                java.lang.RuntimeException: Unable to create application com.example.khatere.mydatabasetests.G: android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
                                                                                at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5406)
                                                                                at android.app.ActivityThread.-wrap2(ActivityThread.java)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1545)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                                                                                Caused by: android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
                                                                                at android.database.sqlite.SQLiteConnection.nativeOpen(Native Method)
                                                                                at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:209)
                                                                                at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:193)
                                                                                at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
                                                                                at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
                                                                                at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
                                                                                at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:808)
                                                                                at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:793)
                                                                                at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:696)
                                                                                at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:711)
                                                                                at com.example.khatere.mydatabasetests.G.onCreate(G.java:29)
                                                                                at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1024)

`
I have no idea for to solve this problem. please help me.

Body:
Add the write permission to the Android Manifest

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

If you're running your app on API level 23 or greater you have to request permission at runtime.

Request permission:

String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestPermissions(permissions, WRITE_REQUEST_CODE);

Then handle the result:

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
       case WRITE_REQUEST_CODE:
         if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
           //Granted.
           //Continue with the database process

         }
       else{
           //Denied.
         }
        break;
    }
}

For more information visit Requesting Permissions at Run Time - Android Doc


问:
How to get FormControl Validator in HTML view
I'm using Reactive form. I want to get Validator of FormControl in view like this:

```<code><span *ngIf="productForm.controls.ProductName.validator?.required" class="required-field">*</span>
</code>```

My component code is like this :

```<code>    this.productForm = new FormGroup({
            'ProductName': new FormControl('', [Validators.required])
})
</code>```

Is there any way to know on view that ProductName have a validator and that is required

答:
Can be checked using

```<code>*ngIf = "productForm.controls.Productname.errors.required"
</code>```

to check if the input has a required validator.

Body:
I'm using Reactive form. I want to get Validator of FormControl in view like this:

*

My component code is like this :

    this.productForm = new FormGroup({
            'ProductName': new FormControl('', [Validators.required])
})

Is there any way to know on view that ProductName have a validator and that is required

Body:
Can be checked using

*ngIf = "productForm.controls.Productname.errors.required"

to check if the input has a required validator.


问:
Can't submit form without reloading page
I build a link shortener,just for fun!
Everything works, but everytime I create a link and submit the form, the page reloads! I wanted to prevent that with onclick="return false;"but it didnt work.

```<code><input class="submit" type="submit" value="Create!"  />

$('#contactForm').submit(function () {
    sendContactForm();
    return false;
});
</code>```

But nothing works, the file is just stuck and doesn't do anything! What am I doing from ? This is the problem page https://viid.su
PHP

```<code>   require("db_config.php");
       $uid = 1;
      $flink = $_POST['url'];
      if(!preg_match("/^[a-zA-Z]+[:\/\/]+[A-Za-z0-9\-_]+\\.+[A-Za-z0-9\.\/%&=\?\-_]+$/i", $flink)) {
        $html = "Error: invalid URL";
      } else {

        $db = mysqli_connect($host, $username, $password);
        $conn = new mysqli($host, $username, $password, $database);

          $id = substr(md5(time().$flink), 0, 5);
          if($conn->query("INSERT INTO `".$database."`.`link` (`id`, `flink`,`adonly`,`userid`) VALUES ('".$id."', '".$flink."','true','".$uid."');")) {
            $html = 'Your short URL is <a class="test" href="https://viid.su/'.$id.'">https://viid.su/'.$id.'</a>';
          } else {
            $html = "Error: cannot find database";
          }
        mysqli_close($db);
      }
</code>```

答:
You can submit a form without reloading the page by using something like an AJAX call.

JavaScript

```<code>$('#contactForm').submit(function (e) {
    e.preventDefault();

    $.ajax({
           type: "POST",
           url: "path/to/your/script.php",
           data: $('#contactForm').serialize(), // Packs the form's elements
           success: function(data)
           {
               // Do something  here if the call succeeded
               alert(data);
           }
         });
}
</code>```

HTML

```<code><form id="contactForm">
    <input type="text" name="username" />
    <input type="text" name="email" />
    <input type="submit" value="Submit form" />
</form>
</code>```

PHP

```<code><?php

echo $_POST['username'];

?>
</code>```

Something along those lines should work, and you don't need anything else, as you are already using jQuery.

Body:
I build a link shortener,just for fun!
Everything works, but everytime I create a link and submit the form, the page reloads! I wanted to prevent that with onclick="return false;"but it didnt work.

<input class="submit" type="submit" value="Create!"  />

$('#contactForm').submit(function () {
    sendContactForm();
    return false;
});

But nothing works, the file is just stuck and doesn't do anything! What am I doing from ? This is the problem page https://viid.su
PHP

   require("db_config.php");
       $uid = 1;
      $flink = $_POST['url'];
      if(!preg_match("/^[a-zA-Z]+[:\/\/]+[A-Za-z0-9\-_]+\\.+[A-Za-z0-9\.\/%&=\?\-_]+$/i", $flink)) {
        $html = "Error: invalid URL";
      } else {

        $db = mysqli_connect($host, $username, $password);
        $conn = new mysqli($host, $username, $password, $database);

          $id = substr(md5(time().$flink), 0, 5);
          if($conn->query("INSERT INTO `".$database."`.`link` (`id`, `flink`,`adonly`,`userid`) VALUES ('".$id."', '".$flink."','true','".$uid."');")) {
            $html = 'Your short URL is https://viid.su/'.$id.'';
          } else {
            $html = "Error: cannot find database";
          }
        mysqli_close($db);
      }

Body:
You can submit a form without reloading the page by using something like an AJAX call.

JavaScript

$('#contactForm').submit(function (e) {
    e.preventDefault();

    $.ajax({
           type: "POST",
           url: "path/to/your/script.php",
           data: $('#contactForm').serialize(), // Packs the form's elements
           success: function(data)
           {
               // Do something  here if the call succeeded
               alert(data);
           }
         });
}

HTML

<form id="contactForm">
    <input type="text" name="username" />
    <input type="text" name="email" />
    <input type="submit" value="Submit form" />
</form>

PHP

<?php

echo $_POST['username'];

?>

Something along those lines should work, and you don't need anything else, as you are already using jQuery.


问:
How can I encode/decode this proprietary checksum (Athena 16C PID controller)?
I have an Athena 16C controller that I am controlling via RS232.  Its messaging protocol requires a proprietary checksum:

"CHKSUM: This is a two character Message Code Numbering System, representing the sum of all the ASCII values of all the characters (excluding the START, CHAR, the END CHAR, and the CHKSM themselves) in the message. The sum is computed using the following formula:
CHKSM = SUM(All Message Characters)%256 where % represents the modulus operator."

An example message (from their documentation) is this:

```<code>$Ø1Ø1RØ5C1<CR>
</code>```

and can be broken down as:

```<code>$ [START CHAR] 01 [ID] 01 [ZONE] R [TYPE] 05 [PARAM] C1 [CHKSM] <CR> [END CHAR]
</code>```

I have sent this message to the controller and it works as expected.

I am writing my code in JS and have the following that is supposed to calculate the CHKSM to put at the end of the message:

```<code>var sum = 'Ø1Ø1RØ5'
   .split('')
   .map(function(char) {
       return char.charCodeAt(0);
   })
   .reduce(function(current, previous) {
       return previous + current;
   });

var chksm = (sum % 256);
console.log(chksm.toString(16));
</code>```

The checksum should be 'C1' according to the message format.  But the calculated sum is 377 which results in a checksum of 121 which equals 79 in hex.

```<code>// 0 = 48, 1 = 49, R = 82, 5 = 53 (ASCII values)
// 48 + 49 + 48 + 49 + 82 + 48 + 53 = 377
// 377 % 256 = 121 (decimal) = 79 (hex)
</code>```

An engineer from Athena sent me the following VB code but I cannot understand the logic, nor the syntax particularly.  Is there something basic I am missing with this problem in general?

```<code>' Covert the mod % 256 checksum to the 2 chars:
' Will set First and Second chars for encoded value. Pass in the value (Checksum mod 256)
' and where to return the 1st and 2nd chars to.
Public Sub EncodeIt(ByVal Value As Integer, ByRef FirstChar As Integer, ByRef SecondChar As Integer)

    If Value > 359 Then 'Z9 = 359, absolute max possible
        Value = 359
    End If

    'Note: backslash '\' means integer divide, not floating point!!
    If Value > 99 Then
        FirstChar = (Value \ 10) + 65 - 10    '65 = ascii "A"
    Else
        FirstChar = (Value \ 10) + 48          '48 = ascii "0"
    End If

    SecondChar = (Value Mod 10) + 48

End Sub

' Convert the two chars received in a message back to normal integer.
' Take the 2 chars and return a decoded integer value
Public Function DecodeIt(ByVal FirstChar As Integer, ByVal SecondChar As Integer) As Integer

    '65 = ascii "A", 48 = ascii "0"
    If FirstChar > 57 Then '57 = ascii "9"
        Return ((FirstChar - 65 + 10) * 10) + (SecondChar - 48)
    Else
        Return ((FirstChar - 48) * 10) + (SecondChar - 48)

    End If

End Function
</code>```

答:
I just went through this for C# and with the help of above, came up with this code that works (for me):
'reqtemp'  is the string that contains controller ID#, Zone, Parameter, etc. without the start and checksum characters.</p>

```<code>   // generate checksum for Athena
            int x = 0;
            int sl = reqtemp.Length;
            int FirstChar = 0; //checksum 1st character
            int SecondChar = 0; //checksum 2nd char

            string crcr; // crc for requests

            for (int c = 0; c < sl; c++)
            {
                string sel = reqtemp.Substring(c, 1);

                x = x + Convert.ToChar(sel);
            }
            x = x % 256; //modular 256
            x = Math.Min(x, 359); // don't allow > 359
            if (x > 99)
            { FirstChar = (x / 10) + 65 - 10; }
            else
            { FirstChar = (x / 10) + 48; }

            SecondChar = (x % 10) + 48;

            crcr = Char.ConvertFromUtf32(FirstChar) + Char.ConvertFromUtf32(SecondChar);
            //     MessageBox.Show(crcr);

            string reqtempfull = "$"+ reqtemp + crcr + (char)13;
            crc.Text = reqtempfull;  //display the full sp string
            if (ComPort.IsOpen)
            {
                ComPort.Write(reqtempfull);  // send it`enter code here`
            }
</code>```

Body:
I have an Athena 16C controller that I am controlling via RS232.  Its messaging protocol requires a proprietary checksum:

"CHKSUM: This is a two character Message Code Numbering System, representing the sum of all the ASCII values of all the characters (excluding the START, CHAR, the END CHAR, and the CHKSM themselves) in the message. The sum is computed using the following formula:
CHKSM = SUM(All Message Characters)%256 where % represents the modulus operator."

An example message (from their documentation) is this:

$Ø1Ø1RØ5C1<CR>

and can be broken down as:

$ [START CHAR] 01 [ID] 01 [ZONE] R [TYPE] 05 [PARAM] C1 [CHKSM] <CR> [END CHAR]

I have sent this message to the controller and it works as expected.

I am writing my code in JS and have the following that is supposed to calculate the CHKSM to put at the end of the message:

var sum = 'Ø1Ø1RØ5'
   .split('')
   .map(function(char) {
       return char.charCodeAt(0);
   })
   .reduce(function(current, previous) {
       return previous + current;
   });

var chksm = (sum % 256);
console.log(chksm.toString(16));

The checksum should be 'C1' according to the message format.  But the calculated sum is 377 which results in a checksum of 121 which equals 79 in hex.

// 0 = 48, 1 = 49, R = 82, 5 = 53 (ASCII values)
// 48 + 49 + 48 + 49 + 82 + 48 + 53 = 377
// 377 % 256 = 121 (decimal) = 79 (hex)

An engineer from Athena sent me the following VB code but I cannot understand the logic, nor the syntax particularly.  Is there something basic I am missing with this problem in general?

' Covert the mod % 256 checksum to the 2 chars:
' Will set First and Second chars for encoded value. Pass in the value (Checksum mod 256)
' and where to return the 1st and 2nd chars to.
Public Sub EncodeIt(ByVal Value As Integer, ByRef FirstChar As Integer, ByRef SecondChar As Integer)

    If Value > 359 Then 'Z9 = 359, absolute max possible
        Value = 359
    End If

    'Note: backslash '\' means integer divide, not floating point!!
    If Value > 99 Then
        FirstChar = (Value \ 10) + 65 - 10    '65 = ascii "A"
    Else
        FirstChar = (Value \ 10) + 48          '48 = ascii "0"
    End If

    SecondChar = (Value Mod 10) + 48

End Sub

' Convert the two chars received in a message back to normal integer.
' Take the 2 chars and return a decoded integer value
Public Function DecodeIt(ByVal FirstChar As Integer, ByVal SecondChar As Integer) As Integer

    '65 = ascii "A", 48 = ascii "0"
    If FirstChar > 57 Then '57 = ascii "9"
        Return ((FirstChar - 65 + 10) * 10) + (SecondChar - 48)
    Else
        Return ((FirstChar - 48) * 10) + (SecondChar - 48)

    End If

End Function

Body:
I just went through this for C# and with the help of above, came up with this code that works (for me):
'reqtemp'  is the string that contains controller ID#, Zone, Parameter, etc. without the start and checksum characters.

   // generate checksum for Athena
            int x = 0;
            int sl = reqtemp.Length;
            int FirstChar = 0; //checksum 1st character
            int SecondChar = 0; //checksum 2nd char

            string crcr; // crc for requests

            for (int c = 0; c < sl; c++)
            {
                string sel = reqtemp.Substring(c, 1);

                x = x + Convert.ToChar(sel);
            }
            x = x % 256; //modular 256
            x = Math.Min(x, 359); // don't allow > 359
            if (x > 99)
            { FirstChar = (x / 10) + 65 - 10; }
            else
            { FirstChar = (x / 10) + 48; }

            SecondChar = (x % 10) + 48;

            crcr = Char.ConvertFromUtf32(FirstChar) + Char.ConvertFromUtf32(SecondChar);
            //     MessageBox.Show(crcr);

            string reqtempfull = "$"+ reqtemp + crcr + (char)13;
            crc.Text = reqtempfull;  //display the full sp string
            if (ComPort.IsOpen)
            {
                ComPort.Write(reqtempfull);  // send it`enter code here`
            }


问:
how to upload the datas to webserver from android mobile
how to upload the datas to  webserver from android mobile.Please provide coding </p>

答:
I think this compiles:

```<code>HttpPut request = new HttpPut(<uri>);
request.setEntity(new ByteArrayEntity(<your data>));
HttpResponse response = HttpClient.execute(httpPut);
</code>```

You might want to use the HttpPost instead of HttpPut and also specify the content type on the request.

Body:
I think this compiles:

HttpPut request = new HttpPut(<uri>);
request.setEntity(new ByteArrayEntity(<your data>));
HttpResponse response = HttpClient.execute(httpPut);

You might want to use the HttpPost instead of HttpPut and also specify the content type on the request.


问:
How do I know when multiple background workers are finished?
So right now I have a method that calls a different method three times.

```<code>List<BackgroundWorker> bgws = new List<BackgroundWorker>();
AutoResetEvent _workerCompleted = new AutoResetEvent(false);

void methodA () {
    methodB(); //bw1
    methodB(); //bw2
    methodB(); //bw3

    //wait for the background workers that were kicked off above to finish
    _workerCompleted.WaitOne();

    Console.Writeline("hey");
}

void methodB() {
    BackgroundWorker bw = new BackgroundWorker();
    bw.WorkerReportsProgress = true;
    bw.WorkerSupportsCancellation = true;
    bgws.Add(bw);

    bw.DoWork += (sender, DoWorkEventArgs) => { bwWork(sender, DoWorkEventArgs, info); };
    bw.ProgressChanged += (sender, ProgressChangedEventArgs) => { bwProgressChanged(sender, ProgressChangedEventArgs, info); };
    bw.RunWorkerCompleted += (sender, RunWorkerCompletedEventArgs) => { bwCompleted(sender, RunWorkerCompletedEventArgs, info); };

    bw.RunWorkerAsync();

}
</code>```

The bwWork and bwProgressChanged events shouldn't matter too much. The former is just processing a file, the latter is updating a progress bar and label.

```<code>private void bwCompleted(object senderr,
System.ComponentModel.RunWorkerCompletedEventArgs e, SenderInfo info)
{
    BackgroundWorker bw = (BackgroundWorker)senderr;

    Console.WriteLine(Path.GetFileName(info.path) + " : Finished.");

    bgws.Remove(bw); //remove the bw from the list
    //remove events from bw
    bw.DoWork -= (sender, DoWorkEventArgs) => { bwWork(sender, DoWorkEventArgs, info); };
    bw.ProgressChanged -= (sender, ProgressChangedEventArgs) => { bwProgressChanged(sender, ProgressChangedEventArgs, info); };
    bw.RunWorkerCompleted -= (sender, RunWorkerCompletedEventArgs) => { bwCompleted(sender, RunWorkerCompletedEventArgs, info); };
    //dispose bw
    bw.Dispose();
    Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
    if (bgws.Count == 0) //if there are no more bw's, we're good to go
    {
        MessageBox.Show("Done.");
        bgws.Clear();
        _workerCompleted.Set();
    }

}
</code>```

So in the end, I want all of the background workers to finish what they're doing before "hey" is printed out. I tried using the AutoResetEvent and ManualResetEvent, yet nothing seemed to happen when they were present. What I mean is that none of the background workers even ran when I included them.

I would invoke a thread, but I'm a little reluctant because I was told background workers were the thing to use when doing background work and updating UI. Is there any way that I can wait on the three background workers so that I can continue on with my program?

答:
I believe the issue is that the BackgroundWorker does DoWork on a separate thread, but uses the thread it is created on to run ProgressChanged and RunWorkerCompleted events so they can update the UI. But if you already have the UI thread tied up in a WaitOne or other spin, you can't execute those events.

In your bwCompleted when bgws.Count == 0 why don't you call a methodA_AfterDone to handle the read of methodA and just have methodA end after bw3?

Body:
So right now I have a method that calls a different method three times.

List<BackgroundWorker> bgws = new List<BackgroundWorker>();
AutoResetEvent _workerCompleted = new AutoResetEvent(false);

void methodA () {
    methodB(); //bw1
    methodB(); //bw2
    methodB(); //bw3

    //wait for the background workers that were kicked off above to finish
    _workerCompleted.WaitOne();

    Console.Writeline("hey");
}

void methodB() {
    BackgroundWorker bw = new BackgroundWorker();
    bw.WorkerReportsProgress = true;
    bw.WorkerSupportsCancellation = true;
    bgws.Add(bw);

    bw.DoWork += (sender, DoWorkEventArgs) => { bwWork(sender, DoWorkEventArgs, info); };
    bw.ProgressChanged += (sender, ProgressChangedEventArgs) => { bwProgressChanged(sender, ProgressChangedEventArgs, info); };
    bw.RunWorkerCompleted += (sender, RunWorkerCompletedEventArgs) => { bwCompleted(sender, RunWorkerCompletedEventArgs, info); };

    bw.RunWorkerAsync();

}

The bwWork and bwProgressChanged events shouldn't matter too much. The former is just processing a file, the latter is updating a progress bar and label.

private void bwCompleted(object senderr,
System.ComponentModel.RunWorkerCompletedEventArgs e, SenderInfo info)
{
    BackgroundWorker bw = (BackgroundWorker)senderr;

    Console.WriteLine(Path.GetFileName(info.path) + " : Finished.");

    bgws.Remove(bw); //remove the bw from the list
    //remove events from bw
    bw.DoWork -= (sender, DoWorkEventArgs) => { bwWork(sender, DoWorkEventArgs, info); };
    bw.ProgressChanged -= (sender, ProgressChangedEventArgs) => { bwProgressChanged(sender, ProgressChangedEventArgs, info); };
    bw.RunWorkerCompleted -= (sender, RunWorkerCompletedEventArgs) => { bwCompleted(sender, RunWorkerCompletedEventArgs, info); };
    //dispose bw
    bw.Dispose();
    Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
    if (bgws.Count == 0) //if there are no more bw's, we're good to go
    {
        MessageBox.Show("Done.");
        bgws.Clear();
        _workerCompleted.Set();
    }

}

So in the end, I want all of the background workers to finish what they're doing before "hey" is printed out. I tried using the AutoResetEvent and ManualResetEvent, yet nothing seemed to happen when they were present. What I mean is that none of the background workers even ran when I included them.

I would invoke a thread, but I'm a little reluctant because I was told background workers were the thing to use when doing background work and updating UI. Is there any way that I can wait on the three background workers so that I can continue on with my program?


问:
MySQL server has gone away - in exactly 60 seconds
I recently discovered that a sql query that was running fine earlier is now timing out after 60 seconds and throwing an error. The query is slow but runs as part of a nightly job so that's not a problem in itself (so please don't suggest I optimize it).

I'm able to reproduce the error consistently by running "select SLEEP(120);" from PHP as shown below. However, running the same statement from a MySQL client is successful (returns 0). I've tried adjusting wait_timeout (set to 28800), but have had no luck. I've also rebooted both the db server and machine itself.

The fact that it always times out at exactly 60 seconds suggests to me that it is likely to be a setting and not a limited resources issue.

I'm running:

Windows Server 2003

MySql 5.1.36-community

PHP 5.3

Below are my test code, the output and the results from SHOW VARIABLES

Thanks!

CODE:

```<code>set_error_handler("sqlErrorHandler");
set_time_limit(12000);

$link = mysql_connect("$MYSQL_Host","$MYSQL_User","$MYSQL_Pass");
mysql_select_db($MYSQL_db, $link);

echo "mysql_ping = " . (mysql_ping($link) ? "LIVE" : "DEAD") . "<br /><br />";

$sql = "SELECT SLEEP(120);";

$start = microtime(true);
mysql_query($sql, $link);

echo "**query done**<br />";
allDone();

function allDone(){
 global $start, $sql;

 $end = microtime(true);
 echo "sql : $sql<br />";
 echo "elapsed : " . ($end - $start) . "<br />";
 echo "<br />";
}

function sqlErrorHandler($errno, $errstr, $errfile, $errline){
 global $link;
 echo "Error : $errno<br />$errstr<br />";
 echo "mysql_ping : " . (mysql_ping($link) ? "LIVE" : "DEAD") . "<br />";
 echo "<br />";

 allDone();
}
</code>```

OUTPUT :

```<code>mysql_ping = LIVE

Error : 2
mysql_query() [function.mysql-query]: MySQL server has gone away
mysql_ping : DEAD

sql : SELECT SLEEP(120);
elapsed : 60.051116943359

Error : 2
mysql_query() [function.mysql-query]: Error reading result set's header
mysql_ping : DEAD

sql : SELECT SLEEP(120);
elapsed : 60.0511469841

**query done**
sql : SELECT SLEEP(120);
elapsed : 60.051155090332
</code>```

SHOW VARIABLES:

```<code>Variable_name=Value
auto_increment_increment=1
auto_increment_offset=1
autocommit=ON
automatic_sp_privileges=ON
back_log=50
basedir=C:\\Program Files\\MySQL\\MySQL Server 5.1\\
big_tables=OFF
binlog_cache_size=32768
binlog_format=STATEMENT
bulk_insert_buffer_size=8388608
character_set_client=utf8
character_set_connection=utf8
character_set_database=latin1
character_set_filesystem=binary
character_set_results=utf8
character_set_server=latin1
character_set_system=utf8
character_sets_dir=C:\\Program Files\\MySQL\\MySQL Server 5.1\\share\\charsets\\
collation_connection=utf8_general_ci
collation_database=latin1_swedish_ci
collation_server=latin1_swedish_ci
completion_type=0
concurrent_insert=1
connect_timeout=10
datadir=C:\\Documents and Settings\\All Users\\Application Data\\MySQL\\MySQL Server 5.1\\Data\\
date_format=%Y-%m-%d
datetime_format=%Y-%m-%d %H:%i:%s
default_week_format=0
delay_key_write=ON
delayed_insert_limit=100
delayed_insert_timeout=300
delayed_queue_size=1000
div_precision_increment=4
engine_condition_pushdown=ON
error_count=0
event_scheduler=OFF
expire_logs_days=0
flush=OFF
flush_time=1800
foreign_key_checks=ON
ft_boolean_syntax=+ -><()~*:""&|
ft_max_word_len=84
ft_min_word_len=4
ft_query_expansion_limit=20
ft_stopword_file=(built-in)
general_log=OFF
general_log_file=C:\\Documents and Settings\\All Users\\Application Data\\MySQL\\MySQL Server 5.1\\Data\\p1.log
group_concat_max_len=1024
have_community_features=YES
have_compress=YES
have_crypt=NO
have_csv=YES
have_dynamic_loading=YES
have_geometry=YES
have_innodb=YES
have_ndbcluster=NO
have_openssl=DISABLED
have_partitioning=YES
have_query_cache=YES
have_rtree_keys=YES
have_ssl=DISABLED
have_symlink=YES
identity=0
ignore_builtin_innodb=OFF
init_connect=
init_file=
init_slave=
innodb_adaptive_hash_index=ON
innodb_additional_mem_pool_size=2097152
innodb_autoextend_increment=8
innodb_autoinc_lock_mode=1
innodb_buffer_pool_size=96468992
innodb_checksums=ON
innodb_commit_concurrency=0
innodb_concurrency_tickets=500
innodb_data_file_path=ibdata1:10M:autoextend
innodb_data_home_dir=D:\\MySQL Datafiles\\
innodb_doublewrite=ON
innodb_fast_shutdown=1
innodb_file_io_threads=4
innodb_file_per_table=OFF
innodb_flush_log_at_trx_commit=1
innodb_flush_method=
innodb_force_recovery=0
innodb_lock_wait_timeout=50
innodb_locks_unsafe_for_binlog=OFF
innodb_log_buffer_size=1048576
innodb_log_file_size=19922944
innodb_log_files_in_group=2
innodb_log_group_home_dir=.\\
innodb_max_dirty_pages_pct=90
innodb_max_purge_lag=0
innodb_mirrored_log_groups=1
innodb_open_files=300
innodb_rollback_on_timeout=OFF
innodb_stats_on_metadata=ON
innodb_support_xa=ON
innodb_sync_spin_loops=20
innodb_table_locks=ON
innodb_thread_concurrency=8
innodb_thread_sleep_delay=10000
innodb_use_legacy_cardinality_algorithm=ON
insert_id=0
interactive_timeout=28800
join_buffer_size=131072
keep_files_on_create=OFF
key_buffer_size=50331648
key_cache_age_threshold=300
key_cache_block_size=1024
key_cache_division_limit=100
language=C:\\Program Files\\MySQL\\MySQL Server 5.1\\share\\english\\
large_files_support=ON
large_page_size=0
large_pages=OFF
last_insert_id=0
lc_time_names=en_US
license=GPL
local_infile=ON
log=OFF
log_bin=OFF
log_bin_trust_function_creators=OFF
log_bin_trust_routine_creators=OFF
log_error=C:\\Documents and Settings\\All Users\\Application Data\\MySQL\\MySQL Server 5.1\\Data\\p1.err
log_output=FILE
log_queries_not_using_indexes=OFF
log_slave_updates=OFF
log_slow_queries=OFF
log_warnings=1
long_query_time=10.000000
low_priority_updates=OFF
lower_case_file_system=ON
lower_case_table_names=1
max_allowed_packet=1048576
max_binlog_cache_size=4294963200
max_binlog_size=1073741824
max_connect_errors=10
max_connections=800
max_delayed_threads=20
max_error_count=64
max_heap_table_size=16777216
max_insert_delayed_threads=20
max_join_size=18446744073709551615
max_length_for_sort_data=1024
max_prepared_stmt_count=16382
max_relay_log_size=0
max_seeks_for_key=4294967295
max_sort_length=1024
max_sp_recursion_depth=0
max_tmp_tables=32
max_user_connections=0
max_write_lock_count=4294967295
min_examined_row_limit=0
multi_range_count=256
myisam_data_pointer_size=6
myisam_max_sort_file_size=107374182400
myisam_recover_options=OFF
myisam_repair_threads=1
myisam_sort_buffer_size=12582912
myisam_stats_method=nulls_unequal
myisam_use_mmap=OFF
named_pipe=OFF
net_buffer_length=16384
net_read_timeout=30
net_retry_count=10
net_write_timeout=80
new=OFF
old=OFF
old_alter_table=OFF
old_passwords=OFF
open_files_limit=2048
optimizer_prune_level=1
optimizer_search_depth=62
optimizer_switch=index_merge=on,index_merge_union=on,index_merge_sort_union=on,index_merge_intersection=on
pid_file=C:\\Documents and Settings\\All Users\\Application Data\\MySQL\\MySQL Server 5.1\\Data\\p1.pid
plugin_dir=C:\\Program Files\\MySQL\\MySQL Server 5.1\\lib/plugin
port=3306
preload_buffer_size=32768
profiling=OFF
profiling_history_size=15
protocol_version=10
pseudo_thread_id=3230
query_alloc_block_size=8192
query_cache_limit=1048576
query_cache_min_res_unit=4096
query_cache_size=33554432
query_cache_type=ON
query_cache_wlock_invalidate=OFF
query_prealloc_size=8192
rand_seed1=
rand_seed2=
range_alloc_block_size=4096
read_buffer_size=65536
read_only=OFF
read_rnd_buffer_size=262144
relay_log=
relay_log_index=
relay_log_info_file=relay-log.info
relay_log_purge=ON
relay_log_space_limit=0
report_host=
report_password=
report_port=3306
report_user=
rpl_recovery_rank=0
secure_auth=OFF
secure_file_priv=
server_id=0
shared_memory=OFF
shared_memory_base_name=MYSQL
skip_external_locking=ON
skip_networking=OFF
skip_show_database=OFF
slave_compressed_protocol=OFF
slave_exec_mode=STRICT
slave_load_tmpdir=C:\\WINDOWS\\TEMP
slave_net_timeout=3600
slave_skip_errors=OFF
slave_transaction_retries=10
slow_launch_time=2
slow_query_log=OFF
slow_query_log_file=C:\\Documents and Settings\\All Users\\Application Data\\MySQL\\MySQL Server 5.1\\Data\\p1-slow.log
sort_buffer_size=262144
sql_auto_is_null=ON
sql_big_selects=ON
sql_big_tables=OFF
sql_buffer_result=OFF
sql_log_bin=ON
sql_log_off=OFF
sql_log_update=ON
sql_low_priority_updates=OFF
sql_max_join_size=18446744073709551615
sql_mode=
sql_notes=ON
sql_quote_show_create=ON
sql_safe_updates=OFF
sql_select_limit=18446744073709551615
sql_slave_skip_counter=
sql_warnings=OFF
ssl_ca=
ssl_capath=
ssl_cert=
ssl_cipher=
ssl_key=
storage_engine=InnoDB
sync_binlog=0
sync_frm=ON
system_time_zone=Eastern Daylight Time
table_definition_cache=256
table_lock_wait_timeout=50
table_open_cache=619
table_type=InnoDB
thread_cache_size=38
thread_handling=one-thread-per-connection
thread_stack=196608
time_format=%H:%i:%s
time_zone=SYSTEM
timed_mutexes=OFF
timestamp=1256827484
tmp_table_size=16777216
tmpdir=C:\\WINDOWS\\TEMP
transaction_alloc_block_size=8192
transaction_prealloc_size=4096
tx_isolation=REPEATABLE-READ
unique_checks=ON
updatable_views_with_limit=YES
version=5.1.36-community
version_comment=MySQL Community Server (GPL)
version_compile_machine=ia32
version_compile_os=Win32
wait_timeout=28800
warning_count=0
</code>```

答:
In our case, the culprit was the global (not "local") MySQL variable "wait_timeout".

Compare the results of the following queries:

```<code>SHOW VARIABLES LIKE '%wait%';
</code>```

to

```<code>SHOW GLOBAL VARIABLES WHERE Variable_name LIKE '%wait%';
</code>```

In our case the first query showed a wait_timeout of 28800, but the 2nd query showed a value of 10 (seconds).

We verified that changing the global variable fixed the problem.  Here is a simple PHP script that reproduced our condition:

```<code><?php
$db = mysqli_connect('host', 'user', 'password', 'database');

sleep(10); // number of seconds to sleep

// MySQL server has gone away?
$obj = mysqli_query($db, 'SELECT * FROM some_table');

$results = mysqli_fetch_object($obj);

print_r($results);
</code>```

As soon as the sleep time exceeded the global wait_timeout value, we would get the error: "Warning: mysqli_query(): MySQL server has gone away".

To change the value, we had to edit the setting in our Amazon RDS dashboard.

Body:
I recently discovered that a sql query that was running fine earlier is now timing out after 60 seconds and throwing an error. The query is slow but runs as part of a nightly job so that's not a problem in itself (so please don't suggest I optimize it).

I'm able to reproduce the error consistently by running "select SLEEP(120);" from PHP as shown below. However, running the same statement from a MySQL client is successful (returns 0). I've tried adjusting wait_timeout (set to 28800), but have had no luck. I've also rebooted both the db server and machine itself.

The fact that it always times out at exactly 60 seconds suggests to me that it is likely to be a setting and not a limited resources issue.

I'm running:

Windows Server 2003

MySql 5.1.36-community

PHP 5.3

Below are my test code, the output and the results from SHOW VARIABLES

Thanks!

CODE:

set_error_handler("sqlErrorHandler");
set_time_limit(12000);

$link = mysql_connect("$MYSQL_Host","$MYSQL_User","$MYSQL_Pass");
mysql_select_db($MYSQL_db, $link);

echo "mysql_ping = " . (mysql_ping($link) ? "LIVE" : "DEAD") . "

";

$sql = "SELECT SLEEP(120);";

$start = microtime(true);
mysql_query($sql, $link);

echo "**query done**
";
allDone();

function allDone(){
 global $start, $sql;

 $end = microtime(true);
 echo "sql : $sql
";
 echo "elapsed : " . ($end - $start) . "
";
 echo "
";
}

function sqlErrorHandler($errno, $errstr, $errfile, $errline){
 global $link;
 echo "Error : $errno
$errstr
";
 echo "mysql_ping : " . (mysql_ping($link) ? "LIVE" : "DEAD") . "
";
 echo "
";

 allDone();
}

OUTPUT :

mysql_ping = LIVE

Error : 2
mysql_query() [function.mysql-query]: MySQL server has gone away
mysql_ping : DEAD

sql : SELECT SLEEP(120);
elapsed : 60.051116943359

Error : 2
mysql_query() [function.mysql-query]: Error reading result set's header
mysql_ping : DEAD

sql : SELECT SLEEP(120);
elapsed : 60.0511469841

**query done**
sql : SELECT SLEEP(120);
elapsed : 60.051155090332

SHOW VARIABLES:

Variable_name=Value
auto_increment_increment=1
auto_increment_offset=1
autocommit=ON
automatic_sp_privileges=ON
back_log=50
basedir=C:\\Program Files\\MySQL\\MySQL Server 5.1\\
big_tables=OFF
binlog_cache_size=32768
binlog_format=STATEMENT
bulk_insert_buffer_size=8388608
character_set_client=utf8
character_set_connection=utf8
character_set_database=latin1
character_set_filesystem=binary
character_set_results=utf8
character_set_server=latin1
character_set_system=utf8
character_sets_dir=C:\\Program Files\\MySQL\\MySQL Server 5.1\\share\\charsets\\
collation_connection=utf8_general_ci
collation_database=latin1_swedish_ci
collation_server=latin1_swedish_ci
completion_type=0
concurrent_insert=1
connect_timeout=10
datadir=C:\\Documents and Settings\\All Users\\Application Data\\MySQL\\MySQL Server 5.1\\Data\\
date_format=%Y-%m-%d
datetime_format=%Y-%m-%d %H:%i:%s
default_week_format=0
delay_key_write=ON
delayed_insert_limit=100
delayed_insert_timeout=300
delayed_queue_size=1000
div_precision_increment=4
engine_condition_pushdown=ON
error_count=0
event_scheduler=OFF
expire_logs_days=0
flush=OFF
flush_time=1800
foreign_key_checks=ON
ft_boolean_syntax=+ -><()~*:""&|
ft_max_word_len=84
ft_min_word_len=4
ft_query_expansion_limit=20
ft_stopword_file=(built-in)
general_log=OFF
general_log_file=C:\\Documents and Settings\\All Users\\Application Data\\MySQL\\MySQL Server 5.1\\Data\\p1.log
group_concat_max_len=1024
have_community_features=YES
have_compress=YES
have_crypt=NO
have_csv=YES
have_dynamic_loading=YES
have_geometry=YES
have_innodb=YES
have_ndbcluster=NO
have_openssl=DISABLED
have_partitioning=YES
have_query_cache=YES
have_rtree_keys=YES
have_ssl=DISABLED
have_symlink=YES
identity=0
ignore_builtin_innodb=OFF
init_connect=
init_file=
init_slave=
innodb_adaptive_hash_index=ON
innodb_additional_mem_pool_size=2097152
innodb_autoextend_increment=8
innodb_autoinc_lock_mode=1
innodb_buffer_pool_size=96468992
innodb_checksums=ON
innodb_commit_concurrency=0
innodb_concurrency_tickets=500
innodb_data_file_path=ibdata1:10M:autoextend
innodb_data_home_dir=D:\\MySQL Datafiles\\
innodb_doublewrite=ON
innodb_fast_shutdown=1
innodb_file_io_threads=4
innodb_file_per_table=OFF
innodb_flush_log_at_trx_commit=1
innodb_flush_method=
innodb_force_recovery=0
innodb_lock_wait_timeout=50
innodb_locks_unsafe_for_binlog=OFF
innodb_log_buffer_size=1048576
innodb_log_file_size=19922944
innodb_log_files_in_group=2
innodb_log_group_home_dir=.\\
innodb_max_dirty_pages_pct=90
innodb_max_purge_lag=0
innodb_mirrored_log_groups=1
innodb_open_files=300
innodb_rollback_on_timeout=OFF
innodb_stats_on_metadata=ON
innodb_support_xa=ON
innodb_sync_spin_loops=20
innodb_table_locks=ON
innodb_thread_concurrency=8
innodb_thread_sleep_delay=10000
innodb_use_legacy_cardinality_algorithm=ON
insert_id=0
interactive_timeout=28800
join_buffer_size=131072
keep_files_on_create=OFF
key_buffer_size=50331648
key_cache_age_threshold=300
key_cache_block_size=1024
key_cache_division_limit=100
language=C:\\Program Files\\MySQL\\MySQL Server 5.1\\share\\english\\
large_files_support=ON
large_page_size=0
large_pages=OFF
last_insert_id=0
lc_time_names=en_US
license=GPL
local_infile=ON
log=OFF
log_bin=OFF
log_bin_trust_function_creators=OFF
log_bin_trust_routine_creators=OFF
log_error=C:\\Documents and Settings\\All Users\\Application Data\\MySQL\\MySQL Server 5.1\\Data\\p1.err
log_output=FILE
log_queries_not_using_indexes=OFF
log_slave_updates=OFF
log_slow_queries=OFF
log_warnings=1
long_query_time=10.000000
low_priority_updates=OFF
lower_case_file_system=ON
lower_case_table_names=1
max_allowed_packet=1048576
max_binlog_cache_size=4294963200
max_binlog_size=1073741824
max_connect_errors=10
max_connections=800
max_delayed_threads=20
max_error_count=64
max_heap_table_size=16777216
max_insert_delayed_threads=20
max_join_size=18446744073709551615
max_length_for_sort_data=1024
max_prepared_stmt_count=16382
max_relay_log_size=0
max_seeks_for_key=4294967295
max_sort_length=1024
max_sp_recursion_depth=0
max_tmp_tables=32
max_user_connections=0
max_write_lock_count=4294967295
min_examined_row_limit=0
multi_range_count=256
myisam_data_pointer_size=6
myisam_max_sort_file_size=107374182400
myisam_recover_options=OFF
myisam_repair_threads=1
myisam_sort_buffer_size=12582912
myisam_stats_method=nulls_unequal
myisam_use_mmap=OFF
named_pipe=OFF
net_buffer_length=16384
net_read_timeout=30
net_retry_count=10
net_write_timeout=80
new=OFF
old=OFF
old_alter_table=OFF
old_passwords=OFF
open_files_limit=2048
optimizer_prune_level=1
optimizer_search_depth=62
optimizer_switch=index_merge=on,index_merge_union=on,index_merge_sort_union=on,index_merge_intersection=on
pid_file=C:\\Documents and Settings\\All Users\\Application Data\\MySQL\\MySQL Server 5.1\\Data\\p1.pid
plugin_dir=C:\\Program Files\\MySQL\\MySQL Server 5.1\\lib/plugin
port=3306
preload_buffer_size=32768
profiling=OFF
profiling_history_size=15
protocol_version=10
pseudo_thread_id=3230
query_alloc_block_size=8192
query_cache_limit=1048576
query_cache_min_res_unit=4096
query_cache_size=33554432
query_cache_type=ON
query_cache_wlock_invalidate=OFF
query_prealloc_size=8192
rand_seed1=
rand_seed2=
range_alloc_block_size=4096
read_buffer_size=65536
read_only=OFF
read_rnd_buffer_size=262144
relay_log=
relay_log_index=
relay_log_info_file=relay-log.info
relay_log_purge=ON
relay_log_space_limit=0
report_host=
report_password=
report_port=3306
report_user=
rpl_recovery_rank=0
secure_auth=OFF
secure_file_priv=
server_id=0
shared_memory=OFF
shared_memory_base_name=MYSQL
skip_external_locking=ON
skip_networking=OFF
skip_show_database=OFF
slave_compressed_protocol=OFF
slave_exec_mode=STRICT
slave_load_tmpdir=C:\\WINDOWS\\TEMP
slave_net_timeout=3600
slave_skip_errors=OFF
slave_transaction_retries=10
slow_launch_time=2
slow_query_log=OFF
slow_query_log_file=C:\\Documents and Settings\\All Users\\Application Data\\MySQL\\MySQL Server 5.1\\Data\\p1-slow.log
sort_buffer_size=262144
sql_auto_is_null=ON
sql_big_selects=ON
sql_big_tables=OFF
sql_buffer_result=OFF
sql_log_bin=ON
sql_log_off=OFF
sql_log_update=ON
sql_low_priority_updates=OFF
sql_max_join_size=18446744073709551615
sql_mode=
sql_notes=ON
sql_quote_show_create=ON
sql_safe_updates=OFF
sql_select_limit=18446744073709551615
sql_slave_skip_counter=
sql_warnings=OFF
ssl_ca=
ssl_capath=
ssl_cert=
ssl_cipher=
ssl_key=
storage_engine=InnoDB
sync_binlog=0
sync_frm=ON
system_time_zone=Eastern Daylight Time
table_definition_cache=256
table_lock_wait_timeout=50
table_open_cache=619
table_type=InnoDB
thread_cache_size=38
thread_handling=one-thread-per-connection
thread_stack=196608
time_format=%H:%i:%s
time_zone=SYSTEM
timed_mutexes=OFF
timestamp=1256827484
tmp_table_size=16777216
tmpdir=C:\\WINDOWS\\TEMP
transaction_alloc_block_size=8192
transaction_prealloc_size=4096
tx_isolation=REPEATABLE-READ
unique_checks=ON
updatable_views_with_limit=YES
version=5.1.36-community
version_comment=MySQL Community Server (GPL)
version_compile_machine=ia32
version_compile_os=Win32
wait_timeout=28800
warning_count=0

Body:
In our case, the culprit was the global (not "local") MySQL variable "wait_timeout".

Compare the results of the following queries:

SHOW VARIABLES LIKE '%wait%';

to

SHOW GLOBAL VARIABLES WHERE Variable_name LIKE '%wait%';

In our case the first query showed a wait_timeout of 28800, but the 2nd query showed a value of 10 (seconds).

We verified that changing the global variable fixed the problem.  Here is a simple PHP script that reproduced our condition:

<?php
$db = mysqli_connect('host', 'user', 'password', 'database');

sleep(10); // number of seconds to sleep

// MySQL server has gone away?
$obj = mysqli_query($db, 'SELECT * FROM some_table');

$results = mysqli_fetch_object($obj);

print_r($results);

As soon as the sleep time exceeded the global wait_timeout value, we would get the error: "Warning: mysqli_query(): MySQL server has gone away".

To change the value, we had to edit the setting in our Amazon RDS dashboard.


问:
Inserting Tags into Searched String/String Case
I have a script that needs some refinement.  Essentially what it does is takes a string, then attempts to search for that within another string to insert some HTML around it for the purposes of highlighting.

Currently it looks like this:

```<code>$query = $_POST['$query'];
$searched = "New York Yankees in New York";

str_ireplace($query,"<span class='hilight'>".$query."</span>", $searched);
</code>```

Now, it works, but it behaves oddly (predictably) when it comes to uppercase/lowercase.

Say $query = 'new'..  The returned string would be :

```<code><span class='hilight'>new</span> York Yankees in <span class='hilight'>new</span> York.
</code>```

How would you go about accomplishing the same thing without changing the case of the original searched string?

答:
Simple solution is using regular expressions and the preg_replace function:

```<code>$query = 'new';
$searched = "New York Yankees in New York";
$r = preg_replace("/($query)/i", "<span class='hilight'>$1</span>", $searched);
echo'r is: ',$r;
</code>```

So, main action here goes in preg_replace:

```<code>preg_replace(
    // find substring `$query`, flag `i` means case-insensitive search
    "/($query)/i",
    // replace founded occurences with this string, `$1` here means the value of the founded substring (`new` or `New` or even `NEW`)
    "<span class='hilight'>$1</span>",
    // string where to find
    $searched
);
</code>```

Body:
I have a script that needs some refinement.  Essentially what it does is takes a string, then attempts to search for that within another string to insert some HTML around it for the purposes of highlighting.

Currently it looks like this:

$query = $_POST['$query'];
$searched = "New York Yankees in New York";

str_ireplace($query,"".$query."", $searched);

Now, it works, but it behaves oddly (predictably) when it comes to uppercase/lowercase.

Say $query = 'new'..  The returned string would be :

new York Yankees in new York.

How would you go about accomplishing the same thing without changing the case of the original searched string?

Body:
Simple solution is using regular expressions and the preg_replace function:

$query = 'new';
$searched = "New York Yankees in New York";
$r = preg_replace("/($query)/i", "<span class='hilight'>$1</span>", $searched);
echo'r is: ',$r;

So, main action here goes in preg_replace:

preg_replace(
    // find substring `$query`, flag `i` means case-insensitive search
    "/($query)/i",
    // replace founded occurences with this string, `$1` here means the value of the founded substring (`new` or `New` or even `NEW`)
    "<span class='hilight'>$1</span>",
    // string where to find
    $searched
);


问:
Having trouble with react tutorial, Invariant Violation
I'm trying to follow a react tutorial but it's not working.  Here's the code:

```<code>// load react library
var React = require('react');
var ReactDOM = require('react-dom');

/*
   App
*/

var App = React.createClass({
   render: function(){
        <div className='catch-of-the-day'>
            <div className='menu'>
              <Header />
            </div>
        </div>
    }
});

var Header = React.createClass({
    render : function() {
        return(
               <p>Header</p>
            )
    }

});

//build first component
/*
   StorePicker
*/

var StorePicker = React.createClass({

    render : function(){
        var name = 'Bob';
        return (
            <form className='store-selector'>
              {/* comments go here */}
              <h2>Please Enter A Store {/* {name} */}</h2>
              <input type="text" ref='storeId' required/>
              <input type="submit"/>
            </form>
        )
    }
});

ReactDOM.render(<App/>,document.querySelector('#main'));
</code>```

Here's the html:

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Catch of the Day!</title>
   <link href='http://fonts.googleapis.com/css?family=Open+Sans+Condensed:300|Open+Sans' rel='stylesheet' type='text/css'>
  <link rel="stylesheet" href="/build/css/style.css">
  <link rel="shortcut icon" href="http://facebook.github.io/react/favicon.ico">
</head>
<body>

    <input type="checkbox" id="fold">
    <label for="fold">Fold</label>

    <div id="main">
      <!-- This is where our React app will go -->
    </div>
    <div id='new'>
    </div>

  <script src="/build/main.js"></script>

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

and here's the error message:

```<code>Uncaught Error: Invariant Violation: App.render(): A valid ReactComponent
must be returned. You may have returned undefined, an array or some other
invalid object.
</code>```

答:
Your App#render doesn't return anything. More or less what the error message says.

Contrast App#render with Header#render.

Unrelated, but you might want to follow a more-recent tutorial; createClass is deprecated.

Body:
I'm trying to follow a react tutorial but it's not working.  Here's the code:

// load react library
var React = require('react');
var ReactDOM = require('react-dom');

/*
   App
*/

var App = React.createClass({
   render: function(){

    }
});

var Header = React.createClass({
    render : function() {
        return(

Header

            )
    }

});

//build first component
/*
   StorePicker
*/

var StorePicker = React.createClass({

    render : function(){
        var name = 'Bob';
        return (
            <form className='store-selector'>
              {/* comments go here */}

Please Enter A Store {/* {name} */}

              <input type="text" ref='storeId' required/>
              <input type="submit"/>
            </form>
        )
    }
});

ReactDOM.render(<App/>,document.querySelector('#main'));

Here's the html:

<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Catch of the Day!</title>
   <link href='http://fonts.googleapis.com/css?family=Open+Sans+Condensed:300|Open+Sans' rel='stylesheet' type='text/css'>
  <link rel="stylesheet" href="/build/css/style.css">
  <link rel="shortcut icon" href="http://facebook.github.io/react/favicon.ico">

    <input type="checkbox" id="fold">
    Fold

and here's the error message:

Uncaught Error: Invariant Violation: App.render(): A valid ReactComponent
must be returned. You may have returned undefined, an array or some other
invalid object.


问:
Error Using WebSocket in JavaScript
I am currently working on a mobile app created with Cordova. It uses sockets to connect to another device of ours to communicate with it. We currently use chrome.sockets.tcp with this plugin.

It connects fine, however on Android devices has a problem disconnecting. It's not a timeout issue as the disconnect can happen anywhere from 20 to 30 seconds up to 10 to 15 minutes. It will even disconnect while I am downloading data making 2 to 3 requests every second. There are no errors and nothing in the log to indicate what happened. It appears that chrome.sockets.tcp does not have much in the way of connection status reporting so I can figure out why its dropping the connection.

So I tried to make the switch to JavaScript's WebSocket to see if it helps with the disconnect issue. Or at least it appears to provide more connection status information. But I can't get it to connect. I get Error during WebSocket handshake: net::ERR_INVALID_HTTP_RESPONSE. Here is my code:

```<code>var socket = new WebSocket("ws://" + IP + ":" + port);
socket.protocol = "soap";

socket.onclose = function(event) {
    console.log(event);
};
socket.onerror = function(event) {
    console.log(event);
};
socket.onmessage = function(event) {
    console.log(event);
};
socket.onopen = function(event) {
    console.log(event);
};
</code>```

I've done some research and it seems that I might have to set a protocol using socket.protocol = "aProtocol"; but after I set the protocol and set a break point socket.protocol is still "" even after calling socket.protocol = "soap";. It also does not work to set the protocol using the constructor.

Can anyone provide me with either some reasons why chrome.sockets.tcp has such a disconnect problem on Android but not iOS OR any reasons why using JavaScript's native WebSocket fails to connect? Any help is greatly appreciated.

答:
Try passing the sub protocol in the constructor:</p>

```<code>var socket = new WebSocket("ws://" + SSID + ":" + port, "soap");
</code>```

Title: Error Using WebSocket in JavaScript

Body:
I am currently working on a mobile app created with Cordova. It uses sockets to connect to another device of ours to communicate with it. We currently use chrome.sockets.tcp with this plugin.

It connects fine, however on Android devices has a problem disconnecting. It's not a timeout issue as the disconnect can happen anywhere from 20 to 30 seconds up to 10 to 15 minutes. It will even disconnect while I am downloading data making 2 to 3 requests every second. There are no errors and nothing in the log to indicate what happened. It appears that chrome.sockets.tcp does not have much in the way of connection status reporting so I can figure out why its dropping the connection.

So I tried to make the switch to JavaScript's WebSocket to see if it helps with the disconnect issue. Or at least it appears to provide more connection status information. But I can't get it to connect. I get Error during WebSocket handshake: net::ERR_INVALID_HTTP_RESPONSE. Here is my code:

var socket = new WebSocket("ws://" + IP + ":" + port);
socket.protocol = "soap";

socket.onclose = function(event) {
    console.log(event);
};
socket.onerror = function(event) {
    console.log(event);
};
socket.onmessage = function(event) {
    console.log(event);
};
socket.onopen = function(event) {
    console.log(event);
};

I've done some research and it seems that I might have to set a protocol using socket.protocol = "aProtocol"; but after I set the protocol and set a break point socket.protocol is still "" even after calling socket.protocol = "soap";. It also does not work to set the protocol using the constructor.

Can anyone provide me with either some reasons why chrome.sockets.tcp has such a disconnect problem on Android but not iOS OR any reasons why using JavaScript's native WebSocket fails to connect? Any help is greatly appreciated.

Body:
Try passing the sub protocol in the constructor:

var socket = new WebSocket("ws://" + SSID + ":" + port, "soap");


问:
What is a dynamic linking failure in the JVM?
In Oracle's Java - Essential Classes Trail I found the following statement:

Error Class

When a dynamic linking failure or other hard failure in the Java
  virtual machine occurs, the virtual machine throws an Error. [...]

What exactly is meant by dynamic linking failure in the context of Java and the JVM? Is this related to issues the classloader might encounter at runtime?

答:
In Java you can load Class object dynamically and the logic that verifies if that Class and its instances are compatible with currently loaded classes is called a dynamic linkage.

Here are examples when you can get linkage failures in form of java.lang.LinkageError:

1) You have class and interface. You later modify that interface method signatures and start VM with that new interface. Now if you go and dynamically try to load your class you will get linkage failure since the class is compiled with old version of interface method signatures and wont be able to work with new interface method signature.

2) You load same class from class loader CL1 and CL2. You then create object o1 from that class loaded by CL1 and use that object in the code that is is loaded by CL2.


问:
Can I make a class with an `__exit__` method but not an `__enter__` method?
I have a class that needs to run a TensorFlow session for each instance of the class, as long as that instance exists.

TensorFlow sessions use context managers, but I don't want to force anyone who uses my class to put my class into a context manager.

Is there any way to auto-close the session once the instance is no longer in use without using a context manager?

Can I just put in an __exit__ method and not an __enter__ method and start the session without the context manager and just close the session in the exit?

答:
You must define an __enter__ method, but you can just define it as:

```<code>def __enter__(self):
    return self
</code>```

and have the session defined in the init. Then, define __exit__ like so:

```<code>def __exit__(self, *exc):
    self.close()
</code>```

Then, define a close method that closes whatever resources were opened in __init__. (In my case, it's a TensorFlow session.)

This way, if the user decides to use the context manager, it will close it for them, and if they don't, they'll have to close it on their own.

Body:
You must define an __enter__ method, but you can just define it as:

def __enter__(self):
    return self

and have the session defined in the init. Then, define __exit__ like so:

def __exit__(self, *exc):
    self.close()

Then, define a close method that closes whatever resources were opened in __init__. (In my case, it's a TensorFlow session.)

This way, if the user decides to use the context manager, it will close it for them, and if they don't, they'll have to close it on their own.