问:
text-overflow in span element not cutting texta outside element width
I'm trying to make a div with 3 spans inside where the middle one should "compress", ie cut the extra text when the size of the div is small.

The result I'm looking for is

```<code>A Very lon... A
          ^ here it should get cut with "text-overflow: ellipsis;"
</code>```

Somehow the text-overflow: ellipsis; is not being applied to the span.

Any idea what I am missing?

Tried with width, display, overflow and nothing seems to work... tested both Chrome and Firefox.

div {
  border-radius: 5px;
  border: 1px solid #333;
  padding: 10px 20px;
  width: 100px;
}

div span {
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}

#long-text {
  width: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <span>A</span>
  <span id="long-text">Very long text here....</span>
  <span>A</span>
</div></code>```

答:
What you are missing is giving span block display

div {
  border-radius: 5px;
  border: 1px solid #333;
  padding: 10px 20px;
  width: 100px;
}

div span {
  display: inline-block;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}

#long-text {
  width: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <span>A</span>
  <span id="long-text">Very long text here....</span>
  <span>A</span>
</div></code>```

Body:
I'm trying to make a div with 3 spans inside where the middle one should "compress", ie cut the extra text when the size of the div is small.

The result I'm looking for is

A Very lon... A
          ^ here it should get cut with "text-overflow: ellipsis;"

Somehow the text-overflow: ellipsis; is not being applied to the span.

Any idea what I am missing?

Tried with width, display, overflow and nothing seems to work... tested both Chrome and Firefox.

div {
  border-radius: 5px;
  border: 1px solid #333;
  padding: 10px 20px;
  width: 100px;
}

div span {
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}

#long-text {
  width: 20px;
}

  A
  Very long text here....
  A

Body:
What you are missing is giving span block display

div {
  border-radius: 5px;
  border: 1px solid #333;
  padding: 10px 20px;
  width: 100px;
}

div span {
  display: inline-block;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}

#long-text {
  width: 20px;
}

<div>
  <span>A</span>
  <span id="long-text">Very long text here....</span>
  <span>A</span>
</div>


来源: stackexchange

问:
Unable to load an iframe on my site
I'm inserting an iframe on my webpage with the following code.

```<code><iframe src="[url]" width="400" height="700">
</code>```

But in the browser I only see a blank box. In the browser console I'm seeing the following message.

```<code>Load denied by X-Frame-Options: [url] does not permit cross-origin framing.
</code>```

[url] is an https url. Accessing the [url] directly in the browser is working.

Can anyone tell me why it is not displaying?

答:
The site that you want to display in the iframe has blocked the ability to be shown in an iframe.

Try to get in contact with the website administrator to ask for permission or an alternative.

ContentLicense: CC BY-SA 3.0

Title: Unable to load an iframe on my site

Body:
I'm inserting an iframe on my webpage with the following code.

But in the browser I only see a blank box. In the browser console I'm seeing the following message.

Load denied by X-Frame-Options: [url] does not permit cross-origin framing.

[url] is an https url. Accessing the [url] directly in the browser is working.

Can anyone tell me why it is not displaying?


问:
php JSON_DECODE for different data length
From mysql, I have a data BLOB data type which has two different scenarios (Please see below). I am trying to put them into a string. Below is the process that I am doing:

1. Query:

```<code>$names= $results[0]->name;
print_r($names);
</code>```

First scenario:

```<code>[{"Name":"Mike"},{"Name":"Sean"}]
</code>```

Second scenario:

```<code>{"Name":"Mike Smith","Spaces":"1"}
</code>```

2. JSON_DECODE

```<code>$data =  json_decode(stripslashes($names),true);
print_r($data);
</code>```

First scenario:

```<code>    Array
        (
            [0] => Array
                (
                    [Name] => Mike
                )

            [1] => Array
                (
                    [Name] => Smith
                )
        )
</code>```

Second scenario:

```<code>    Array
        (
            [Name] => Mike Smith
            [Spaces] => 1
        )
</code>```

3. What I am trying to do: To put them into a string

```<code>$string = '';

for ($i=0; $i <sizeof($data) ; $i++){
    $row = $data[$i];
    $name = $row -> Name;

    if(isset($row -> Spaces)){
        $number = '(' . $row -> Spaces . ')';

    }else{
        $number = '';

    };
    $string .=  $name . $number . ', ';

};

//Remove last comma
$refined = rtrim($string,', ');

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

4. ISSUE

The issue I am having is that because the data can have two different scenarios like shown in the "1.Query", I can't predict or generalize it and getting errors like "Trying to get property of non-object".

How can I fix this?

答:
Since you're passing true to the $assoc parameter of json_decode, $row->Name will never be the right syntax, since you have an array, and that's syntax for accessing objects; you want $row['Name'] instead. (It's unusual to put space around the -> by the way.)

However, you have basically the right idea on this line:

```<code>if(isset($row -> Spaces)){
</code>```

For an array, that would instead by:

```<code>if(isset($row['Spaces'])){
</code>```

You can do the same thing to see if you've got a name, or a list of names:

```<code>if(isset($row['Name'])) {
    // In scenario B
    echo $row['Name'];
    // check for 'Spaces' etc
} else {
    // In scenario A
    foreach ( $row as $item ) {
        echo $item['Name'];
    }
}
</code>```

Note my use of a foreach loop here, which is much neater than your for loop for this kind of thing.

Body:
From mysql, I have a data BLOB data type which has two different scenarios (Please see below). I am trying to put them into a string. Below is the process that I am doing:

1. Query:

$names= $results[0]->name;
print_r($names);

First scenario:

[{"Name":"Mike"},{"Name":"Sean"}]

Second scenario:

{"Name":"Mike Smith","Spaces":"1"}

2. JSON_DECODE

$data =  json_decode(stripslashes($names),true);
print_r($data);

First scenario:

    Array
        (
            [0] => Array
                (
                    [Name] => Mike
                )

            [1] => Array
                (
                    [Name] => Smith
                )
        )

Second scenario:

    Array
        (
            [Name] => Mike Smith
            [Spaces] => 1
        )

3. What I am trying to do: To put them into a string

$string = '';

for ($i=0; $i <sizeof($data) ; $i++){
    $row = $data[$i];
    $name = $row -> Name;

    if(isset($row -> Spaces)){
        $number = '(' . $row -> Spaces . ')';

    }else{
        $number = '';

    };
    $string .=  $name . $number . ', ';

};

//Remove last comma
$refined = rtrim($string,', ');

print_r($refined);

4. ISSUE

The issue I am having is that because the data can have two different scenarios like shown in the "1.Query", I can't predict or generalize it and getting errors like "Trying to get property of non-object".

How can I fix this?

Body:
Since you're passing true to the $assoc parameter of json_decode, $row->Name will never be the right syntax, since you have an array, and that's syntax for accessing objects; you want $row['Name'] instead. (It's unusual to put space around the -> by the way.)

However, you have basically the right idea on this line:

if(isset($row -> Spaces)){

For an array, that would instead by:

if(isset($row['Spaces'])){

You can do the same thing to see if you've got a name, or a list of names:

if(isset($row['Name'])) {
    // In scenario B
    echo $row['Name'];
    // check for 'Spaces' etc
} else {
    // In scenario A
    foreach ( $row as $item ) {
        echo $item['Name'];
    }
}

Note my use of a foreach loop here, which is much neater than your for loop for this kind of thing.


问:
Browser can't find my CKEditor
I am working on an web application which uses jsf and richFaces. I am trying to use the latest version of CKEditor. It works properly in other projects but in that one, the CKEditor is replaced by RichFaces's CKEditor and I don't want that. If I find any CKEditor (latest version)file in the server directory, I can find it but in the development mode of my browser that folder doesnt appear and I think that is the problem.
Thanks in advance.</p>

答:
You can tell RichFaces to use your files instead of the ones it comes with, create "META-INF/richfaces/static-resource-mappings.properties" and put something like this in there:

```<code>org.richfaces.ckeditor\:ckeditor.js=myCKEditor/ckeditor.js
</code>```

But bear in mind that the rich:editor might not work with newer versions of CKEditor (although currently the newest is 4.7 compared to 4.5.8 so it should work).

Title: Browser can't find my CKEditor

Body:
You can tell RichFaces to use your files instead of the ones it comes with, create "META-INF/richfaces/static-resource-mappings.properties" and put something like this in there:

org.richfaces.ckeditor\:ckeditor.js=myCKEditor/ckeditor.js

But bear in mind that the rich:editor might not work with newer versions of CKEditor (although currently the newest is 4.7 compared to 4.5.8 so it should work).


问:
KeyError in pandas
I'm trying to make out one example of time series. Here is the link

I have an error in this piece of code:

```<code>dta.index = pd.Index(sm.tsa.datetools.dates_from_range('1700', '2008'))
del dta["YEAR"]
</code>```

The error looks like this:

```<code>KeyError                                  Traceback (most recent call last)
C:\ProgramData\Anaconda3\lib\site-packages\pandas\indexes\base.py in
get_loc(self, key, method, tolerance)
   2133             try:
-> 2134                 return self._engine.get_loc(key)
   2135             except KeyError:

pandas\index.pyx in pandas.index.IndexEngine.get_loc (pandas\index.c:4433)()

pandas\index.pyx in pandas.index.IndexEngine.get_loc (pandas\index.c:4279)()

pandas\src\hashtable_class_helper.pxi in
pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:13742)()

pandas\src\hashtable_class_helper.pxi in
pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:13696)()

KeyError: 'YEAR'

During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)
<ipython-input-22-5287e8e754f5> in <module>()
      1 dta.index = pd.Index(sm.tsa.datetools.dates_from_range('1700', '2008'))
----> 2 del dta["YEAR"]

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\generic.py in
__delitem__(self, key)
   1640             # there was no match, this call should raise the appropriate
   1641             # exception:
-> 1642             self._data.delete(key)
   1643
   1644         # delete from the caches

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\internals.py in
delete(self, item)
   3600         Delete selected item (items if non-unique) in-place.
   3601         """
-> 3602         indexer = self.items.get_loc(item)
   3603
   3604         is_deleted = np.zeros(self.shape[0], dtype=np.bool_)

C:\ProgramData\Anaconda3\lib\site-packages\pandas\indexes\base.py in
get_loc(self, key, method, tolerance)
   2134                 return self._engine.get_loc(key)
   2135             except KeyError:
-> 2136                 return
self._engine.get_loc(self._maybe_cast_indexer(key))
   2137
   2138         indexer = self.get_indexer([key], method=method, tolerance=tolerance)

pandas\index.pyx in pandas.index.IndexEngine.get_loc (pandas\index.c:4433)()

pandas\index.pyx in pandas.index.IndexEngine.get_loc (pandas\index.c:4279)()

pandas\src\hashtable_class_helper.pxi in
pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:13742)()

pandas\src\hashtable_class_helper.pxi in
pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:13696)()

KeyError: 'YEAR'
</code>```

Any suggestions why it does not work?

The reference to the original data does not work, but I found all the source data. Example of input data:

```<code>    Date       Yearly Mean     Yearly Mean    Number of     Definitive/
               Total Sunspot    Standard     Observations   Provisional
                  Number        Deviation                    Indicator
0   2008-12-31     4.2             2.5          6644.0          1.0
1   2007-12-31    12.6             2.7          6841.0          1.0
2   2006-12-31    24.7             3.5          6370.0          1.0
3   2005-12-31    45.8             4.7          7084.0          1.0
4   2004-12-31    65.3             5.9          6882.0          1.0
...
</code>```

答:
It seems you need remove column Date by drop:

```<code>dta = dta.drop('Date', axis=1, level=0)
</code>```

Or:

```<code>dta = dta.drop('Date', axis=1)
</code>```

Or maybe:

```<code>del dta["Date"]
</code>```

Title: KeyError in pandas

Body:
I'm trying to make out one example of time series. Here is the link

I have an error in this piece of code:

dta.index = pd.Index(sm.tsa.datetools.dates_from_range('1700', '2008'))
del dta["YEAR"]

The error looks like this:

KeyError                                  Traceback (most recent call last)
C:\ProgramData\Anaconda3\lib\site-packages\pandas\indexes\base.py in
get_loc(self, key, method, tolerance)
   2133             try:
-> 2134                 return self._engine.get_loc(key)
   2135             except KeyError:

pandas\index.pyx in pandas.index.IndexEngine.get_loc (pandas\index.c:4433)()

pandas\index.pyx in pandas.index.IndexEngine.get_loc (pandas\index.c:4279)()

pandas\src\hashtable_class_helper.pxi in
pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:13742)()

pandas\src\hashtable_class_helper.pxi in
pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:13696)()

KeyError: 'YEAR'

During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)
<ipython-input-22-5287e8e754f5> in <module>()
      1 dta.index = pd.Index(sm.tsa.datetools.dates_from_range('1700', '2008'))
----> 2 del dta["YEAR"]

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\generic.py in
__delitem__(self, key)
   1640             # there was no match, this call should raise the appropriate
   1641             # exception:
-> 1642             self._data.delete(key)
   1643
   1644         # delete from the caches

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\internals.py in
delete(self, item)
   3600         Delete selected item (items if non-unique) in-place.
   3601         """
-> 3602         indexer = self.items.get_loc(item)
   3603
   3604         is_deleted = np.zeros(self.shape[0], dtype=np.bool_)

C:\ProgramData\Anaconda3\lib\site-packages\pandas\indexes\base.py in
get_loc(self, key, method, tolerance)
   2134                 return self._engine.get_loc(key)
   2135             except KeyError:
-> 2136                 return
self._engine.get_loc(self._maybe_cast_indexer(key))
   2137
   2138         indexer = self.get_indexer([key], method=method, tolerance=tolerance)

pandas\index.pyx in pandas.index.IndexEngine.get_loc (pandas\index.c:4433)()

pandas\index.pyx in pandas.index.IndexEngine.get_loc (pandas\index.c:4279)()

pandas\src\hashtable_class_helper.pxi in
pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:13742)()

pandas\src\hashtable_class_helper.pxi in
pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:13696)()

KeyError: 'YEAR'

Any suggestions why it does not work?

The reference to the original data does not work, but I found all the source data. Example of input data:

    Date       Yearly Mean     Yearly Mean    Number of     Definitive/
               Total Sunspot    Standard     Observations   Provisional
                  Number        Deviation                    Indicator
0   2008-12-31     4.2             2.5          6644.0          1.0
1   2007-12-31    12.6             2.7          6841.0          1.0
2   2006-12-31    24.7             3.5          6370.0          1.0
3   2005-12-31    45.8             4.7          7084.0          1.0
4   2004-12-31    65.3             5.9          6882.0          1.0
...

Body:
It seems you need remove column Date by drop:

dta = dta.drop('Date', axis=1, level=0)

Or:

dta = dta.drop('Date', axis=1)

Or maybe:

del dta["Date"]


问:
Where will Angular-cli be installed?
Where will Angular-cli be installed?can I run Angular-cli expression without install it globaly?</p>

答:
Its is Installed globally

This is a step you only have to do once. Once it's installed globally with "-g", you can skip this step when creating new Angular 2 projects. Also it's important to note, you need Nodejs and NPM installed before you can proceed with this step.

Its is installed in Nodejs Modules Globally

```<code>npm install -g @angular/cli
</code>```

a dummy location -> usr/local/lib/node_modules/@angular/cli/node_modules/

Then use the following Commands to create a new project

```<code>ng new PROJECT_NAME
cd PROJECT_NAME
ng serve
</code>```

for more info on cli check the wiki

ContentLicense: CC BY-SA 4.0

Title: Where will Angular-cli be installed?

Body:
Its is Installed globally

This is a step you only have to do once. Once it's installed globally with "-g", you can skip this step when creating new Angular 2 projects. Also it's important to note, you need Nodejs and NPM installed before you can proceed with this step.

Its is installed in Nodejs Modules Globally

npm install -g @angular/cli

a dummy location -> usr/local/lib/node_modules/@angular/cli/node_modules/

Then use the following Commands to create a new project

ng new PROJECT_NAME
cd PROJECT_NAME
ng serve

for more info on cli check the wiki


问:
Jquery popup for images
there are three or more images in a single html page and need to show same image in popup after clicking on particular image. Is there anything which I can use for this?</p>

```<code><img class="wp-image-4596 size-medium" src="img1.jpg" alt="img1" width="232" height="300">
<img class="wp-image-4596 size-medium" src="img2.jpg" alt="img2" width="232" height="300">
<img class="wp-image-4596 size-medium" src="img3.jpg" alt="img3" width="232" height="300">
</code>```

答: You can do it using bootstrap modal. Check this for my answer on the same.</p>

Title: Jquery popup for images


问:
Check the box automatically or disable it using knockout
So I am trying to do either of the two things:

1) When all three boxes are checked (payments, picked up and returned), I want the fourth one(completed) to be checked automatically.

OR

2) I want the fourth box (completed) to be disabled until all the other boxes are checked.

I can't figure out either one using knockout js. Here is my code:

```<code><div class="center">
    <h2> Grad Apparels </h2>
    <table>
        <thead>
            <tr>
                <th></th>
                <th> ID Number </th>
                <th> Full Name </th>
                <th> Payments </th>
                <th> Picked Up </th>
                <th> Returned </th>
                <th> Completed </th>
                <th></th>
            </tr>
        </thead>
        <tbody data-bind="foreach: apparels">
            <tr>
                <td data-bind="text: ($index() + 1)"> </td>
                <th data-bind="text: id"></th>
                <th data-bind="text: name"></th>
                <th> <input type="checkbox"> </th>
                <th> <input type="checkbox"> </th>
                <th> <input type="checkbox"> </th>
                <th> <input type="checkbox"> </th>
                <td> <a href="#" data-bind="click: $parent.remove">Remove</a></td>
            </tr>
        </tbody>
    </table>
    <br>
    <p> ID: <input data-bind="value: id"> </p>

    <p> Full Name: <input data-bind="value: name"></p>
    <button data-bind="click: add">ADD</button>
</div>
</code>```

JavaScript:

```<code>function apparel(id, name){
    var self = this;
    self.id = ko.observable(id);
    self.name = ko.observable(name);
};

function viewModel(){
    var self = this;
    self.id = ko.observable('');
    self.name = ko.observable('');
    self.apparels = ko.observableArray([
        new apparel(915486876, 'Shajia'),
        new apparel(915123456, 'John Doe'),
        new apparel(948037466, 'Katherine'),
        new apparel(958480376, 'Samuel'),
        new apparel(984803976, 'Jane Doe')
    ]);

this.add = function(){
    self.apparels.push(new apparel(self.id(), self.name()))
}

this.remove = function(){
    self.apparels.remove(this)
}

}

ko.applyBindings(new viewModel());
</code>```

答:
You could add three observables (payments, pickedUp and returned) and a computed (allChecked) to the apparel object:

```<code>    function apparel(id, name){
        var self = this;

        self.id = ko.observable(id);
        self.name = ko.observable(name);

        self.payments = ko.observable();
        self.pickedUp = ko.observable();
        self.returned = ko.observable();

        self.allChecked = ko.computed(function() {
            return self.ch1() && self.ch2() && self.ch3();
        });
    };
</code>```

And then use them in your table:

```<code>    <div class="center">
        <h2> Grad Apparels </h2>
        <table>
            <thead>
                <tr>
                    <th></th>
                    <th> ID Number </th>
                    <th> Full Name </th>
                    <th> Payments </th>
                    <th> Picked Up </th>
                    <th> Returned </th>
                    <th> Completed </th>
                    <th></th>
                </tr>
            </thead>
            <tbody data-bind="foreach: apparels">
                <tr>
                    <td data-bind="text: ($index() + 1)"> </td>
                    <th data-bind="text: id"></th>
                    <th data-bind="text: name"></th>

                    <th> <input type="checkbox" data-bind="checked: payments"></th>
                    <th> <input type="checkbox" data-bind="checked: pickedUp"></th>
                    <th> <input type="checkbox" data-bind="checked: returned"></th>
                    <th> <input type="checkbox" disabled data-bind="checked: allChecked "> </th>
                    <td> <a href="#" data-bind="click: $parent.remove">Remove</a></td>
                </tr>
            </tbody>
        </table>
        <br>
        <p> ID: <input data-bind="value: id"> </p>

        <p> Full Name: <input data-bind="value: name"></p>
        <button data-bind="click: add">ADD</button>
    </div>
</code>```

Body:
So I am trying to do either of the two things:

1) When all three boxes are checked (payments, picked up and returned), I want the fourth one(completed) to be checked automatically.

OR

2) I want the fourth box (completed) to be disabled until all the other boxes are checked.

I can't figure out either one using knockout js. Here is my code:

 Grad Apparels

                 ID Number
                 Full Name
                 Payments
                 Picked Up
                 Returned
                 Completed

                 <input type="checkbox">
                 <input type="checkbox">
                 <input type="checkbox">
                 <input type="checkbox">
                 Remove

 ID: <input data-bind="value: id">

 Full Name: <input data-bind="value: name">

    <button data-bind="click: add">ADD</button>

JavaScript:

function apparel(id, name){
    var self = this;
    self.id = ko.observable(id);
    self.name = ko.observable(name);
};

function viewModel(){
    var self = this;
    self.id = ko.observable('');
    self.name = ko.observable('');
    self.apparels = ko.observableArray([
        new apparel(915486876, 'Shajia'),
        new apparel(915123456, 'John Doe'),
        new apparel(948037466, 'Katherine'),
        new apparel(958480376, 'Samuel'),
        new apparel(984803976, 'Jane Doe')
    ]);

this.add = function(){
    self.apparels.push(new apparel(self.id(), self.name()))
}

this.remove = function(){
    self.apparels.remove(this)
}

}

ko.applyBindings(new viewModel());

Body:
You could add three observables (payments, pickedUp and returned) and a computed (allChecked) to the apparel object:

    function apparel(id, name){
        var self = this;

        self.id = ko.observable(id);
        self.name = ko.observable(name);

        self.payments = ko.observable();
        self.pickedUp = ko.observable();
        self.returned = ko.observable();

        self.allChecked = ko.computed(function() {
            return self.ch1() && self.ch2() && self.ch3();
        });
    };

And then use them in your table:

    <div class="center">
        <h2> Grad Apparels </h2>
        <table>
            <thead>
                <tr>
                    <th></th>
                    <th> ID Number </th>
                    <th> Full Name </th>
                    <th> Payments </th>
                    <th> Picked Up </th>
                    <th> Returned </th>
                    <th> Completed </th>
                    <th></th>
                </tr>
            </thead>
            <tbody data-bind="foreach: apparels">
                <tr>
                    <td data-bind="text: ($index() + 1)"> </td>
                    <th data-bind="text: id"></th>
                    <th data-bind="text: name"></th>

                    <th> <input type="checkbox" data-bind="checked: payments"></th>
                    <th> <input type="checkbox" data-bind="checked: pickedUp"></th>
                    <th> <input type="checkbox" data-bind="checked: returned"></th>
                    <th> <input type="checkbox" disabled data-bind="checked: allChecked "> </th>
                    <td> <a href="#" data-bind="click: $parent.remove">Remove</a></td>
                </tr>
            </tbody>
        </table>
        <br>
        <p> ID: <input data-bind="value: id"> </p>

        <p> Full Name: <input data-bind="value: name"></p>
        <button data-bind="click: add">ADD</button>
    </div>


问:
How can I access from network newly deployed pod in kubernetes?
I am a newbie in kubernetes and i know i am missing something small but cannot see what.
I am creating a pod with file: kubectl create -f mysql.yaml

```<code>apiVersion: v1
kind: Pod
metadata:
  name: mysql
  labels:
    name: mysql
spec:
  containers:
    - resources:
        limits :
          cpu: 2
      image: mysql
      name: mysql
      env:
        - name: MYSQL_ROOT_PASSWORD
          # change this
          value: TestingDB1
      ports:
        - containerPort: 3306
          name: mysql
</code>```

and a service with: kubectl create -f mysql_service.yaml

```<code>apiVersion: v1
kind: Service
metadata:
  labels:
    name: mysql
  name: mysql
spec:
  externalIPs:
    - 10.19.13.127
  ports:
    - port: 3306
  selector:
    name: mysql
</code>```

Output of "kubectl version"

```<code>Client Version: version.Info{Major:"1", Minor:"5", GitVersion:"v1.5.2", GitCommit:"d33fd89e399396658aed4e48dfe7d5d8d50ac6e8", GitTreeState:"clean", BuildDate:"2017-05-26T17:08:24Z", GoVersion:"go1.7.4", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"5", GitVersion:"v1.5.2", GitCommit:"d33fd89e399396658aed4e48dfe7d5d8d50ac6e8", GitTreeState:"clean", BuildDate:"2017-05-26T17:08:24Z", GoVersion:"go1.7.4", Compiler:"gc", Platform:"linux/amd64"}
</code>```

Output of "kubectl cluster-info"

```<code>Kubernetes master is running at http://localhost:8080
</code>```

Output of "kubectl get pods"

```<code>NAME                    READY     STATUS    RESTARTS   AGE
mysql                   1/1       Running   0          20m
</code>```

Output of  "kubectl get svc"

```<code>NAME         CLUSTER-IP       EXTERNAL-IP    PORT(S)    AGE
kubernetes   10.254.0.1       <none>         443/TCP    18h
mysql        10.254.129.206   10.19.13.127   3306/TCP   1h
</code>```

Output of "kubectl get no"

```<code>NAME           STATUS    AGE
10.19.13.127   Ready     19h
</code>```

Output of  "docker ps"

```<code>CONTAINER ID        IMAGE                                      COMMAND                  CREATED             STATUS              PORTS               NAMES
74ea1fb2b383        mysql                                      "docker-entrypoint.sh"   3 minutes ago       Up 3 minutes                            k8s_mysql.ae7893ad_mysql_default_e58d1c09-4a8e-11e7-9baf-fa163ee3f5d9_793d8d7c
</code>```

I can see the pod is being created normally. Even when i connect to the container I am able to log in to mysql with credentials.

My question is:
How can i access/expose port running on my kubernetes node from my network ? For example I want to do a telnet from my PC to the kubernetes node where the mysql pod is running.

Thank you !

答:
Below command verifies that the Redis server is running in the pod and listening on which port (generally it run on 6379 port) :

kubectl get pods redis-master --template='{{(index (index .spec.containers 0).ports 0).containerPort}}{{"\n"}}'

Output : 6739

Body:
I am a newbie in kubernetes and i know i am missing something small but cannot see what.
I am creating a pod with file: kubectl create -f mysql.yaml

apiVersion: v1
kind: Pod
metadata:
  name: mysql
  labels:
    name: mysql
spec:
  containers:
    - resources:
        limits :
          cpu: 2
      image: mysql
      name: mysql
      env:
        - name: MYSQL_ROOT_PASSWORD
          # change this
          value: TestingDB1
      ports:
        - containerPort: 3306
          name: mysql

and a service with: kubectl create -f mysql_service.yaml

apiVersion: v1
kind: Service
metadata:
  labels:
    name: mysql
  name: mysql
spec:
  externalIPs:
    - 10.19.13.127
  ports:
    - port: 3306
  selector:
    name: mysql

Output of "kubectl version"

Client Version: version.Info{Major:"1", Minor:"5", GitVersion:"v1.5.2", GitCommit:"d33fd89e399396658aed4e48dfe7d5d8d50ac6e8", GitTreeState:"clean", BuildDate:"2017-05-26T17:08:24Z", GoVersion:"go1.7.4", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"5", GitVersion:"v1.5.2", GitCommit:"d33fd89e399396658aed4e48dfe7d5d8d50ac6e8", GitTreeState:"clean", BuildDate:"2017-05-26T17:08:24Z", GoVersion:"go1.7.4", Compiler:"gc", Platform:"linux/amd64"}

Output of "kubectl cluster-info"

Kubernetes master is running at http://localhost:8080

Output of "kubectl get pods"

NAME                    READY     STATUS    RESTARTS   AGE
mysql                   1/1       Running   0          20m

Output of  "kubectl get svc"

NAME         CLUSTER-IP       EXTERNAL-IP    PORT(S)    AGE
kubernetes   10.254.0.1       <none>         443/TCP    18h
mysql        10.254.129.206   10.19.13.127   3306/TCP   1h

Output of "kubectl get no"

NAME           STATUS    AGE
10.19.13.127   Ready     19h

Output of  "docker ps"

CONTAINER ID        IMAGE                                      COMMAND                  CREATED             STATUS              PORTS               NAMES
74ea1fb2b383        mysql                                      "docker-entrypoint.sh"   3 minutes ago       Up 3 minutes                            k8s_mysql.ae7893ad_mysql_default_e58d1c09-4a8e-11e7-9baf-fa163ee3f5d9_793d8d7c

I can see the pod is being created normally. Even when i connect to the container I am able to log in to mysql with credentials.

My question is:
How can i access/expose port running on my kubernetes node from my network ? For example I want to do a telnet from my PC to the kubernetes node where the mysql pod is running.

Thank you !


问:
Cleaning up a database in django before every test method
By default when Django runs against sqlite backend it creates a new in memory database for a test. That means for every class that derives from unittest.TestCase, I get a new database. Can this be changed so that it is cleared before every test method is run?

Example: I am testing a manager class that provides additional abstraction on top of Django persistent objects. The code looks more-less like that

```<code>class TestForManager(unittest.TestCase):
  def testAddingBlah(self):
    manager = Manager()
    self.assertEquals(manager.getBlahs(), 0)
    manager.addBlah(...)
    self.assertEquals(manager.getBlahs(), 1)

  def testAddingBlahInDifferentWay(self):
    manager = Manager()
    self.assertEquals(manager.getBlahs(), 0)
    manager.addBlahInDifferentWay(...)
    self.assertEquals(manager.getBlahs(), 1)
</code>```

Now, the first assertion of second test fails, because the state of the database is preserved between test calls and there already is an instance of Blah in the database.

答: You can use the tearDown method. It will be called after your test is run. You can delete all Blahs there.

OwnerDisplayName: Marcin

ContentLicense: CC BY-SA 2.5

Body:
By default when Django runs against sqlite backend it creates a new in memory database for a test. That means for every class that derives from unittest.TestCase, I get a new database. Can this be changed so that it is cleared before every test method is run?

Example: I am testing a manager class that provides additional abstraction on top of Django persistent objects. The code looks more-less like that

class TestForManager(unittest.TestCase):
  def testAddingBlah(self):
    manager = Manager()
    self.assertEquals(manager.getBlahs(), 0)
    manager.addBlah(...)
    self.assertEquals(manager.getBlahs(), 1)

  def testAddingBlahInDifferentWay(self):
    manager = Manager()
    self.assertEquals(manager.getBlahs(), 0)
    manager.addBlahInDifferentWay(...)
    self.assertEquals(manager.getBlahs(), 1)

Now, the first assertion of second test fails, because the state of the database is preserved between test calls and there already is an instance of Blah in the database.


问:
Attempting two pass two objects through @PathVariable in thymeleaf/spring-boot
I'm attempting to pull two parameters with the @PathVariable annotation but have been unsuccessful due to java throwing me an error about it referencing the item id (which I currently has as an Long) as a String.

Controller:

```<code>@PostMapping("/purchaseToner/{tid}/{bid}")
    public String buyToner(Model model, @PathVariable("tid") Long tid,
                           @PathVariable("bid") Long bid){

        //Grab info
        Buyer mBuyer = buyerService.findOne(bid);
        Toner mToner = tonerService.findOneToner(tid);

        //Updating qualities
        mToner.setTonerQuantity(mToner.getTonerQuantity() - 1);
        mBuyer.setBalance(mBuyer.getBalance() - mToner.getTonerPrice());

        Buyer iBuyer = new Buyer();
        iBuyer.getToners().add(mToner);

        return "redirect:/";
    }
</code>```

View:

```<code> <form th:action="@{/purchaseToner/{tid}(tid=${toner.id})/{bid}(bid=${buyer.buyerId})}" th:object="${buyer}" method="post">
                       <select th:object="${toner}">
                            <option>Select a Toner</option>
                            <option th:each="toner : ${toners}"
                                    th:text="${toner.tonerName}"
                                    th:value="${toner.id}">
                            </option>
                       </select>
                        <input type="hidden" name="buyerId"/>
                        <input type="submit" value="Purchase" onclick="return confirm('Are you sure you want to make this purchase?')"/>
                    </form>
</code>```

Print Trace:

```<code>2017-06-05 21:10:59.418  INFO 788 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2017-06-05 21:10:59.517  INFO 788 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-06-05 21:10:59.527  INFO 788 --- [           main] com.ronone.Application                   : Started Application in 18.596 seconds (JVM running for 19.548)
2017-06-05 21:11:06.438  INFO 788 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring FrameworkServlet 'dispatcherServlet'
2017-06-05 21:11:06.439  INFO 788 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization started
2017-06-05 21:11:06.470  INFO 788 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 31 ms
2017-06-05 21:11:09.673  INFO 788 --- [nio-8080-exec-2] o.h.h.i.QueryTranslatorFactoryInitiator  : HHH000397: Using ASTQueryTranslatorFactory
2017-06-05 21:11:15.837  WARN 788 --- [nio-8080-exec-3] .w.s.m.s.DefaultHandlerExceptionResolver : Failed to bind request element: org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.lang.Long'; nested exception is java.lang.NumberFormatException: For input string: "{tid}(tid=${toner.id})"
</code>```

答:
Try to change this:

```<code>@PostMapping("/purchaseToner/{tid}/{bid}")
    public String buyToner(Model model, @PathVariable("tid") Long tid,
                           @PathVariable("bid") Long bid){
...
    }
</code>```

into this:

```<code>@PostMapping("/purchaseToner/{tid}/{bid}")
    public String buyToner(Model model, @PathVariable("tid") String tid,
                           @PathVariable("bid") String bid){

        long bidlong = Long.parseLong(bid)
        long tidlong = Long.parseLong(tid)

        //Grab info
        Buyer mBuyer = buyerService.findOne(bid);
        Toner mToner = tonerService.findOneToner(tid);

        ...
    }
</code>```

In other words, change your controller's parameters into String types, then convert them into Long.

Body:
I'm attempting to pull two parameters with the @PathVariable annotation but have been unsuccessful due to java throwing me an error about it referencing the item id (which I currently has as an Long) as a String.

Controller:

@PostMapping("/purchaseToner/{tid}/{bid}")
    public String buyToner(Model model, @PathVariable("tid") Long tid,
                           @PathVariable("bid") Long bid){

        //Grab info
        Buyer mBuyer = buyerService.findOne(bid);
        Toner mToner = tonerService.findOneToner(tid);

        //Updating qualities
        mToner.setTonerQuantity(mToner.getTonerQuantity() - 1);
        mBuyer.setBalance(mBuyer.getBalance() - mToner.getTonerPrice());

        Buyer iBuyer = new Buyer();
        iBuyer.getToners().add(mToner);

        return "redirect:/";
    }

View:

 <form th:action="@{/purchaseToner/{tid}(tid=${toner.id})/{bid}(bid=${buyer.buyerId})}" th:object="${buyer}" method="post">
                       <select th:object="${toner}">
                            <option>Select a Toner</option>
                            <option th:each="toner : ${toners}"
                                    th:text="${toner.tonerName}"
                                    th:value="${toner.id}">
                            </option>
                       </select>
                        <input type="hidden" name="buyerId"/>
                        <input type="submit" value="Purchase" onclick="return confirm('Are you sure you want to make this purchase?')"/>
                    </form>

Print Trace:

2017-06-05 21:10:59.418  INFO 788 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2017-06-05 21:10:59.517  INFO 788 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-06-05 21:10:59.527  INFO 788 --- [           main] com.ronone.Application                   : Started Application in 18.596 seconds (JVM running for 19.548)
2017-06-05 21:11:06.438  INFO 788 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring FrameworkServlet 'dispatcherServlet'
2017-06-05 21:11:06.439  INFO 788 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization started
2017-06-05 21:11:06.470  INFO 788 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 31 ms
2017-06-05 21:11:09.673  INFO 788 --- [nio-8080-exec-2] o.h.h.i.QueryTranslatorFactoryInitiator  : HHH000397: Using ASTQueryTranslatorFactory
2017-06-05 21:11:15.837  WARN 788 --- [nio-8080-exec-3] .w.s.m.s.DefaultHandlerExceptionResolver : Failed to bind request element: org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.lang.Long'; nested exception is java.lang.NumberFormatException: For input string: "{tid}(tid=${toner.id})"

Body:
Try to change this:

@PostMapping("/purchaseToner/{tid}/{bid}")
    public String buyToner(Model model, @PathVariable("tid") Long tid,
                           @PathVariable("bid") Long bid){
...
    }

into this:

@PostMapping("/purchaseToner/{tid}/{bid}")
    public String buyToner(Model model, @PathVariable("tid") String tid,
                           @PathVariable("bid") String bid){

        long bidlong = Long.parseLong(bid)
        long tidlong = Long.parseLong(tid)

        //Grab info
        Buyer mBuyer = buyerService.findOne(bid);
        Toner mToner = tonerService.findOneToner(tid);

        ...
    }

In other words, change your controller's parameters into String types, then convert them into Long.


问:
It shows error after using geck V0.16.1
It shows error after using geckodriver V0.16.1 Browser is getting opened and also URL is opened, but shows below error while opening browser:

1496729301597 geckodriver INFO    Listening on 127.0.0.1:26189

1496729302267 geckodriver::marionette INFO    Starting browser
  \?\C:\Program Files\Mozilla Firefox\firefox.exe with args
  ["-marionette"]

1496729302562 addons.manager  ERROR   startup failed: [ExceptioJavaScript
  error: resource://gre/modules/AddonManager.jsm, line 1657:
  NS_ERROR_NOT_INITIALIZED: AddonManager is not initialized

n... "Component returned failure code: 0x80070057
  (NS_ERROR_ILLEGAL_VALUE) [nsIFile.create]"  nsresult: "0x80070057
  (NS_ERROR_ILLEGAL_VALUE)"  location: "JS frame ::
  resource://gre/modules/FileUtils.jsm :: FileUtils_getDir :: line 70"
  data: no] Stack trace:
  FileUtils_getDir()@resource://gre/modules/FileUtils.jsm:70 <
  FileUtils_getFile()@resource://gre/modules/FileUtils.jsm:42 <
  validateBlocklist()@resource://gre/modules/AddonManager.jsm:671 <
  startup()@resource://gre/modules/AddonManager.jsm:834 <
  startup()@resource://gre/modules/AddonManager.jsm:3129 <
  observe()@resource://gre/components/addonManager.js:65

JavaScript error: resource://gre/components/SanityTest.js, line 65:
  NS_ERROR_FILE_ACCESS_DENIED: Component returned failure code:
  0x80520015 (NS_ERROR_FILE_ACCESS_DENIED) [nsIPrefService.savePrefFile]

JavaScript error: resource://gre/modules/AddonManager.jsm, line 2570:
  NS_ERROR_NOT_INITIALIZED: AddonManager is not initialized

1496729310139 Marionette  INFO    Listening on port 50194

Jun 06, 2017 11:38:30 AM org.openqa.selenium.remote.ProtocolHandshake
  createSession

INFO: Detected dialect: W3C

My code is as given below:

```<code>public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub
 WebDriver driver ;
 System.setProperty("webdriver.gecko.driver","D:\\geckodriver-v0.16.1-win64\\geckodriver.exe");
        driver = new FirefoxDriver();
        driver.get("http://google.co.in");

}
</code>```

答: May I know which selenium standalone server version you are using? It should work fine with 3.4.0</p>

Title: It shows error after using geck V0.16.1

Body:
It shows error after using geckodriver V0.16.1 Browser is getting opened and also URL is opened, but shows below error while opening browser:

1496729301597 geckodriver INFO    Listening on 127.0.0.1:26189

1496729302267 geckodriver::marionette INFO    Starting browser
  \?\C:\Program Files\Mozilla Firefox\firefox.exe with args
  ["-marionette"]

1496729302562 addons.manager  ERROR   startup failed: [ExceptioJavaScript
  error: resource://gre/modules/AddonManager.jsm, line 1657:
  NS_ERROR_NOT_INITIALIZED: AddonManager is not initialized

n... "Component returned failure code: 0x80070057
  (NS_ERROR_ILLEGAL_VALUE) [nsIFile.create]"  nsresult: "0x80070057
  (NS_ERROR_ILLEGAL_VALUE)"  location: "JS frame ::
  resource://gre/modules/FileUtils.jsm :: FileUtils_getDir :: line 70"
  data: no] Stack trace:
  FileUtils_getDir()@resource://gre/modules/FileUtils.jsm:70 <
  FileUtils_getFile()@resource://gre/modules/FileUtils.jsm:42 <
  validateBlocklist()@resource://gre/modules/AddonManager.jsm:671 <
  startup()@resource://gre/modules/AddonManager.jsm:834 <
  startup()@resource://gre/modules/AddonManager.jsm:3129 <
  observe()@resource://gre/components/addonManager.js:65

JavaScript error: resource://gre/components/SanityTest.js, line 65:
  NS_ERROR_FILE_ACCESS_DENIED: Component returned failure code:
  0x80520015 (NS_ERROR_FILE_ACCESS_DENIED) [nsIPrefService.savePrefFile]

JavaScript error: resource://gre/modules/AddonManager.jsm, line 2570:
  NS_ERROR_NOT_INITIALIZED: AddonManager is not initialized

1496729310139 Marionette  INFO    Listening on port 50194

Jun 06, 2017 11:38:30 AM org.openqa.selenium.remote.ProtocolHandshake
  createSession

INFO: Detected dialect: W3C

My code is as given below:

public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub
 WebDriver driver ;
 System.setProperty("webdriver.gecko.driver","D:\\geckodriver-v0.16.1-win64\\geckodriver.exe");
        driver = new FirefoxDriver();
        driver.get("http://google.co.in");

}


问:
Count of islands of negative and positive numbers in a NumPy array
I have an array containing chunks of negative and chunks of positive elements. A much simplified example of it would be an array a looking like: array([-3, -2, -1,  1,  2,  3,  4,  5,  6, -5, -4])

(a<0).sum() and (a>0).sum() give me the total number of negative and positive elements but how do I count these in order? By this I mean I want to know that my array contains first 3 negative elements, 6 positive and 2 negative.

This sounds like a topic that have been addressed somewhere, and there may be a duplicate out there, but I can't find one.

A method is to use numpy.roll(a,1) in a loop over the whole array and count the number of elements of a given sign appearing in e.g. the first element of the array as it rolls, but it doesn't look much numpyic (or pythonic) nor very efficient to me.

答:
Here's one vectorized approach -

```<code>def pos_neg_counts(a):
    mask = a>0
    idx = np.flatnonzero(mask[1:] != mask[:-1])
    count = np.concatenate(( [idx[0]+1], idx[1:] - idx[:-1], [a.size-1-idx[-1]] ))
    if a[0]<0:
        return count[1::2], count[::2] # pos, neg counts
    else:
        return count[::2], count[1::2] # pos, neg counts
</code>```

Sample runs -

```<code>In [155]: a
Out[155]: array([-3, -2, -1,  1,  2,  3,  4,  5,  6, -5, -4])

In [156]: pos_neg_counts(a)
Out[156]: (array([6]), array([3, 2]))

In [157]: a[0] = 3

In [158]: a
Out[158]: array([ 3, -2, -1,  1,  2,  3,  4,  5,  6, -5, -4])

In [159]: pos_neg_counts(a)
Out[159]: (array([1, 6]), array([2, 2]))

In [160]: a[-1] = 7

In [161]: a
Out[161]: array([ 3, -2, -1,  1,  2,  3,  4,  5,  6, -5,  7])

In [162]: pos_neg_counts(a)
Out[162]: (array([1, 6, 1]), array([2, 1]))
</code>```

Runtime test

Other approach(es) -

```<code># @Franz's soln
def split_app(my_array):
    negative_index = my_array<0
    splits = np.split(negative_index, np.where(np.diff(negative_index))[0]+1)
    len_list = [len(i) for i in splits]
    return len_list
</code>```

Timings on bigger dataset -

```<code>In [20]: # Setup input array
    ...: reps = np.random.randint(3,10,(100000))
    ...: signs = np.ones(len(reps),dtype=int)
    ...: signs[::2] = -1
    ...: a = np.repeat(signs, reps)*np.random.randint(1,9,reps.sum())
    ...:

In [21]: %timeit split_app(a)
10 loops, best of 3: 90.4 ms per loop

In [22]: %timeit pos_neg_counts(a)
100 loops, best of 3: 2.21 ms per loop
</code>```

Body:
Here's one vectorized approach -

def pos_neg_counts(a):
    mask = a>0
    idx = np.flatnonzero(mask[1:] != mask[:-1])
    count = np.concatenate(( [idx[0]+1], idx[1:] - idx[:-1], [a.size-1-idx[-1]] ))
    if a[0]<0:
        return count[1::2], count[::2] # pos, neg counts
    else:
        return count[::2], count[1::2] # pos, neg counts

Sample runs -

In [155]: a
Out[155]: array([-3, -2, -1,  1,  2,  3,  4,  5,  6, -5, -4])

In [156]: pos_neg_counts(a)
Out[156]: (array([6]), array([3, 2]))

In [157]: a[0] = 3

In [158]: a
Out[158]: array([ 3, -2, -1,  1,  2,  3,  4,  5,  6, -5, -4])

In [159]: pos_neg_counts(a)
Out[159]: (array([1, 6]), array([2, 2]))

In [160]: a[-1] = 7

In [161]: a
Out[161]: array([ 3, -2, -1,  1,  2,  3,  4,  5,  6, -5,  7])

In [162]: pos_neg_counts(a)
Out[162]: (array([1, 6, 1]), array([2, 1]))

Runtime test

Other approach(es) -

# @Franz's soln
def split_app(my_array):
    negative_index = my_array<0
    splits = np.split(negative_index, np.where(np.diff(negative_index))[0]+1)
    len_list = [len(i) for i in splits]
    return len_list

Timings on bigger dataset -

In [20]: # Setup input array
    ...: reps = np.random.randint(3,10,(100000))
    ...: signs = np.ones(len(reps),dtype=int)
    ...: signs[::2] = -1
    ...: a = np.repeat(signs, reps)*np.random.randint(1,9,reps.sum())
    ...:

In [21]: %timeit split_app(a)
10 loops, best of 3: 90.4 ms per loop

In [22]: %timeit pos_neg_counts(a)
100 loops, best of 3: 2.21 ms per loop


问:
PHPUnit - Assert two XMLs are not equal
I have just started introduction some PHPUnit tests to my application and want to compare two XML files that get generated. The positive test is not an issue, since there is a dedicated method to do so:

```<code>$this->assertEqualXMLStructure(
  $expectedResultXml->firstChild,
  $generatedResultXml->firstChild
);
</code>```

Now, I have been looking to write a negative test where I purposely create an invalid XML so they no longer match. I have been googling for some time now, but I can't seem to find a good solution (something like a method called assertNotEqualXMLStructure();). I am really new to PHP so this might be a noob question; sorry if that is the case here.

How can I test that two XML files are not equal based on their structure?

答:
Have you considered comparing their values in PHP? You can convert XML to PHP using this:

$xml = simplexml_load_string($xml_string);
 $json = json_encode($xml);
 $array = json_decode($json,TRUE);

Then you can compare the structure that is returned in the array (the attributes are split up as well in the result)

Title: PHPUnit - Assert two XMLs are not equal

Body:
I have just started introduction some PHPUnit tests to my application and want to compare two XML files that get generated. The positive test is not an issue, since there is a dedicated method to do so:

$this->assertEqualXMLStructure(
  $expectedResultXml->firstChild,
  $generatedResultXml->firstChild
);

Now, I have been looking to write a negative test where I purposely create an invalid XML so they no longer match. I have been googling for some time now, but I can't seem to find a good solution (something like a method called assertNotEqualXMLStructure();). I am really new to PHP so this might be a noob question; sorry if that is the case here.

How can I test that two XML files are not equal based on their structure?


问:
running bazel remote executor test on separate machines
The remote worker guide of bazel (here) explains how to start the remote-worker locally and then run bazel against it.

I tried it and indeed that worked (with bugs that reported in GH)

Another attempt was to create run the remote worker on a virtual separate machine, by running it inside docker container and running bazel against it. But it failed in a different way - and I think this time I'm using it wrong.

Here's my docker file:

```<code>FROM openjdk:8

# install release bazel from apt
RUN echo "deb [arch=amd64] http://storage.googleapis.com/bazel-apt stable jdk1.8" | tee /etc/apt/sources.list.d/bazel.list
RUN curl https://bazel.build/bazel-release.pub.gpg |  apt-key add -
RUN apt-get update && apt-get install -y zip bazel

# compile dev bazel from sources
RUN mkdir -p /usr/src/bazel
# "bazel" has the latest development code of bazel from github
COPY bazel /usr/src/bazel
WORKDIR /usr/src/bazel
RUN bazel build src/bazel

# compile remote_worker using latest development bazel
RUN bazel-bin/src/bazel build //src/tools/remote_worker

# prepare cache folder
RUN mkdir -p /tmp/test

# Run remote-worker
CMD ["bazel-bin/src/tools/remote_worker/remote_worker","--work_path=/tmp/test","--listen_port=3030"]
</code>```

After building it I simply ran the docker binding the port to the localhost:

```<code>$ docker build -t bazel-worker .
$ docker run -p 3030:3030 bazel-worker
</code>```

Then ran bazel java test to run using the remote worker:
(Can check out my test repo here)

```<code>$ bazel --host_jvm_args=-Dbazel.DigestFunction=SHA1 test \
      --spawn_strategy=remote \
      --remote_executor=localhost:3030 \
      --remote_cache=localhost:3030 \
      --strategy=Javac=remote \
      --remote_local_fallback=false \
      --remote_timeout=600 \
      //src/main/java/com/example/...
</code>```

But I got this weird error message:

```<code>____Loading package: src/main/java/com/example
____Loading package: @bazel_tools//tools/cpp
____Loading package: @local_jdk//
____Loading package: @local_config_xcode//
____Loading package: @local_config_cc//
____Loading complete.  Analyzing...
____Loading package: tools/defaults
____Loading package: @bazel_tools//third_party/java/jdk/langtools
____Loading package: @junit//jar
____Found 1 test target...
____Building...
____[0 / 2] BazelWorkspaceStatusAction stable-status.txt
____[2 / 4] Creating source manifest for //src/main/java/com/example:my_test
____From Extracting interface @junit//jar:jar:
/tmp/test/build-80057300-ffd2-49ea-a20b-3f234d9963db/external/bazel_tools/tools/jdk/ijar/ijar: 1: /tmp/test/build-80057300-ffd2-49ea-a20b-3f234d9963db/external/bazel_tools/tools/jdk/ijar/ijar: �����0��!H__PAGEZEROx__TEXTpp__text__TEXT/��__stubs__TEXT0p�__stub_helper__TEXT���__gcc_except_tab__TEXT�: not found
/tmp/test/build-80057300-ffd2-49ea-a20b-3f234d9963db/external/bazel_tools/tools/jdk/ijar/ijar: 2: /tmp/test/build-80057300-ffd2-49ea-a20b-3f234d9963db/external/bazel_tools/tools/jdk/ijar/ijar: Syntax error: word unexpected (expecting ")")
ERROR: /private/var/tmp/_bazel_ors/719f891d5db9fd5e73ade25b0c847fd1/external/junit/jar/BUILD.bazel:2:1: output 'external/junit/jar/_ijar/jar/external/junit/jar/junit-4.12-ijar.jar' was not created.
ERROR: /private/var/tmp/_bazel_ors/719f891d5db9fd5e73ade25b0c847fd1/external/junit/jar/BUILD.bazel:2:1: not all outputs were created or valid.
____Building complete.
Target //src/main/java/com/example:my_test failed to build
Use --verbose_failures to see the command lines of failed build steps.
____Elapsed time: 13.614s, Critical Path: 0.21s
</code>```

Am I doing anything wrong? Do I need to run it differently when running the remote worker on an actual (or virtual) remote machine (vs. just running it locally)?

Important to mention: my machine is mac osx sierra. , I believe that docker openjdk:8 is ubuntu based, I'm running locally bazel development version (sha 956810b6ee24289e457a4b8d0a84ff56eb32c264).

答:
Running the remote worker on a different architecture / OS combination than Bazel itself isn't working yet. We still have a couple of places in Bazel where we inspect the local machine - they were added as temporary measures, but haven't been fixed yet.

Edit: It may work in some cases, especially for platform-independent code (e.g., Java or Scala).

If your build is test-heavy, you could try only running tests remotely with --test_strategy=remote; I'm not sure if the default Jvm configuration will work, though.

If you want to run the entire build remotely, then you need to tell Bazel what kind of machines / OS it's executing on. Right now, that'd require setting --host_cpu, and probably --crosstool_top / --host_crosstool_top to configure a C++ compiler for that platform.

Also, some combinations of platforms are more and some less likely to work. In particular, combining MacOS and Linux or different flavors of Linux are much more likely to work than Windows in any combination.

Body:
The remote worker guide of bazel (here) explains how to start the remote-worker locally and then run bazel against it.

I tried it and indeed that worked (with bugs that reported in GH)

Another attempt was to create run the remote worker on a virtual separate machine, by running it inside docker container and running bazel against it. But it failed in a different way - and I think this time I'm using it wrong.

Here's my docker file:

FROM openjdk:8

# install release bazel from apt
RUN echo "deb [arch=amd64] http://storage.googleapis.com/bazel-apt stable jdk1.8" | tee /etc/apt/sources.list.d/bazel.list
RUN curl https://bazel.build/bazel-release.pub.gpg |  apt-key add -
RUN apt-get update && apt-get install -y zip bazel

# compile dev bazel from sources
RUN mkdir -p /usr/src/bazel
# "bazel" has the latest development code of bazel from github
COPY bazel /usr/src/bazel
WORKDIR /usr/src/bazel
RUN bazel build src/bazel

# compile remote_worker using latest development bazel
RUN bazel-bin/src/bazel build //src/tools/remote_worker

# prepare cache folder
RUN mkdir -p /tmp/test

# Run remote-worker
CMD ["bazel-bin/src/tools/remote_worker/remote_worker","--work_path=/tmp/test","--listen_port=3030"]

After building it I simply ran the docker binding the port to the localhost:

$ docker build -t bazel-worker .
$ docker run -p 3030:3030 bazel-worker

Then ran bazel java test to run using the remote worker:
(Can check out my test repo here)

$ bazel --host_jvm_args=-Dbazel.DigestFunction=SHA1 test \
      --spawn_strategy=remote \
      --remote_executor=localhost:3030 \
      --remote_cache=localhost:3030 \
      --strategy=Javac=remote \
      --remote_local_fallback=false \
      --remote_timeout=600 \
      //src/main/java/com/example/...

But I got this weird error message:

____Loading package: src/main/java/com/example
____Loading package: @bazel_tools//tools/cpp
____Loading package: @local_jdk//
____Loading package: @local_config_xcode//
____Loading package: @local_config_cc//
____Loading complete.  Analyzing...
____Loading package: tools/defaults
____Loading package: @bazel_tools//third_party/java/jdk/langtools
____Loading package: @junit//jar
____Found 1 test target...
____Building...
____[0 / 2] BazelWorkspaceStatusAction stable-status.txt
____[2 / 4] Creating source manifest for //src/main/java/com/example:my_test
____From Extracting interface @junit//jar:jar:
/tmp/test/build-80057300-ffd2-49ea-a20b-3f234d9963db/external/bazel_tools/tools/jdk/ijar/ijar: 1: /tmp/test/build-80057300-ffd2-49ea-a20b-3f234d9963db/external/bazel_tools/tools/jdk/ijar/ijar: �����0��!H__PAGEZEROx__TEXTpp__text__TEXT/��__stubs__TEXT0p�__stub_helper__TEXT���__gcc_except_tab__TEXT�: not found
/tmp/test/build-80057300-ffd2-49ea-a20b-3f234d9963db/external/bazel_tools/tools/jdk/ijar/ijar: 2: /tmp/test/build-80057300-ffd2-49ea-a20b-3f234d9963db/external/bazel_tools/tools/jdk/ijar/ijar: Syntax error: word unexpected (expecting ")")
ERROR: /private/var/tmp/_bazel_ors/719f891d5db9fd5e73ade25b0c847fd1/external/junit/jar/BUILD.bazel:2:1: output 'external/junit/jar/_ijar/jar/external/junit/jar/junit-4.12-ijar.jar' was not created.
ERROR: /private/var/tmp/_bazel_ors/719f891d5db9fd5e73ade25b0c847fd1/external/junit/jar/BUILD.bazel:2:1: not all outputs were created or valid.
____Building complete.
Target //src/main/java/com/example:my_test failed to build
Use --verbose_failures to see the command lines of failed build steps.
____Elapsed time: 13.614s, Critical Path: 0.21s

Am I doing anything wrong? Do I need to run it differently when running the remote worker on an actual (or virtual) remote machine (vs. just running it locally)?

Important to mention: my machine is mac osx sierra. , I believe that docker openjdk:8 is ubuntu based, I'm running locally bazel development version (sha 956810b6ee24289e457a4b8d0a84ff56eb32c264).


问:
set up Date with Calendar or DateTime
I want to set the hour and the minute of a date-instance. I have 3 solutions.

Which should I take and why? :

version 1:

```<code>Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 8);
calendar.set(Calendar.HOUR, 30);

return calendar.getTime();
</code>```

version 2:

```<code>ZonedDateTime i = date.toInstant()
.atZone(ZoneId.systemDefault())
.withHour(8)
.withMinute(30);

return Date.from(i.toInstant());
</code>```

version 3:

```<code>ZonedDateTime i = date.toInstant()
.atZone(ZoneId.systemDefault())
.withHour(8)
.withMinute(30);

return new Date(i.toEpochSecond());
</code>```

答:
if i pick version 1

ZonedDateTime is new api  i not commonly used

Title: set up Date with Calendar or DateTime

Body:
I want to set the hour and the minute of a date-instance. I have 3 solutions.

Which should I take and why? :

version 1:

Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 8);
calendar.set(Calendar.HOUR, 30);

return calendar.getTime();

version 2:

ZonedDateTime i = date.toInstant()
.atZone(ZoneId.systemDefault())
.withHour(8)
.withMinute(30);

return Date.from(i.toInstant());

version 3:

ZonedDateTime i = date.toInstant()
.atZone(ZoneId.systemDefault())
.withHour(8)
.withMinute(30);

return new Date(i.toEpochSecond());


问:
Running XQuery on the command line
It sounds like I need some type of XML processor

It looks like theres a program called Saxon which I can use to run XQuery

When I try this websites example I get

```<code>Error: Could not find or load main class net.sf.saxon.Query
</code>```

I don't know how to set up the java package from the saxon package I downloaded.

Id like to know if there is an easier option to be able to run XQuery from the command line other than this java package? All I want to do is process an xml file with commands like "Select  where type="something"".

答:
It sounds like you're not familiar with running Java applications from the command line. There are two ways forward: learn how to do it, or avoid the problem by finding a way of running XQuery without use of the command line. Let's try to help you with both, and you can choose.

(A) Using the command line

There's basic information on installing and runnning Saxon here:

http://www.saxonica.com/documentation/index.html#!about/gettingstarted/gettingstartedjava

You somehow found a very old version of this page.

Once you've got through the first 4 steps, you're in business. You've done step (1) (Installing Java) - we know that, because otherwise you wouldn't get this error message. You tell us you've done step (2) (downloading the software). It's not clear whether you did step (3) (unzipping it). And you're clearly attempting step (4) - running XQuery from the command line, but it's failing. The message tells us that it's failing because Java is running, but can't find Saxon on the classpath (which is the place where Java looks to find the Saxon entry point, net.sf.saxon.Query

If that doesn't help you, tell us exactly what you did: exactly what files are found where, exactly what you typed on the command line, and exactly what messages you got.

When you've got past that stage, there's more information about the XQuery command line at

http://www.saxonica.com/documentation/index.html#!using-xquery/commandline

(B) Tools that avoid the command line

Saxon doesn't itself provide any graphical user interfaces for running XSLT or XQuery, but there are plenty of tools that do, both commercial and open source, and most of them have Saxon as the underlying XSLT/XQuery engine (or at least offer Saxon as an option). They may not always support the latest version, but initially that's probably not a concern.

The best of these tools are commercial software: two products from vendors that work closely with Saxonica to integrate the product (e.g. by adding debugging capability) are oXygen and Stylus Studio. A cheaper product with less capability is Editix. Most of these probably have free evaluation licenses, so try them out.

The only open source GUI for Saxon that I know of is KernowforSaxon from Andrew Welch. It's great for doing simple things but I think it hasn't been updated for a while.

Title: Running XQuery on the command line

Body:
It sounds like I need some type of XML processor

It looks like theres a program called Saxon which I can use to run XQuery

When I try this websites example I get

Error: Could not find or load main class net.sf.saxon.Query

I don't know how to set up the java package from the saxon package I downloaded.

Id like to know if there is an easier option to be able to run XQuery from the command line other than this java package? All I want to do is process an xml file with commands like "Select  where type="something"".


问:
Getting Gmail API access and ID token, but refresh token is NULL
Following https://developers.google.com/identity/sign-in/web/server-side-flow After getting the authorization code from JavaScript, and passing it to the server side, we indeed get an access token (and an ID token), but not the required refresh token.

There are many posts around but could not solve it yet.

Any suggestion how to get the refresh token?

thanks!

```<code>    private String getResponseToken(GoogleClientSecrets clientSecrets,
                                                 String authCode) throws IOException {
        try {
            GoogleTokenResponse tokenResponse =
                    new GoogleAuthorizationCodeTokenRequest(
                            new NetHttpTransport(),
                            JacksonFactory.getDefaultInstance(),
                            "https://www.googleapis.com/oauth2/v4/token",
//                        "https://accounts.google.com/o/oauth2/token",
                            clientSecrets.getDetails().getClientId(),
                            clientSecrets.getDetails().getClientSecret(),

                            authCode, //NOTE: was received from JavaScript client

                            "postmessage" //TODO: what's this?
                            ).execute();
            String accessToken = tokenResponse.getAccessToken();
            String idToken = tokenResponse.getIdToken();

            //TODO: not getting a refresh token... why?!
            String refreshToken = tokenResponse.getRefreshToken();
            Boolean hasRefreshToken = new Boolean(!(refreshToken == null));
            LOGGER.warn("received refresh token: {}", hasRefreshToken);

            LOGGER.debug("accessToken: {}, refreshToken: {}, idToken: {}", accessToken, refreshToken, idToken);
            return accessToken;
        }catch (TokenResponseException tre){...}
</code>```

答:
you should add the

AccessType = "offline"

You need to call the function

```<code>new GoogleAuthorizationCodeRequestUrl(...).setAccessType("offline")
</code>```

or another syntax:

```<code>var authReq = new GoogleAuthorizationCodeRequestUrl(new Uri(GoogleAuthConsts.AuthorizationUrl)) {
    RedirectUri = Callback,
    ClientId = ClientId,
    AccessType = "offline",
    Scope = string.Join(" ", new[] { Scopes... }),
    ApprovalPrompt = "force"
};
</code>```

in Fiddler you should see the following request:

https://accounts.google.com/o/oauth2/auth?scope=https://www.googleapis.com/auth/webmasters&redirect_uri=http://mywebsite.com/google/scapi/callback/&response_type=code&client_id=xxx&access_type=offline

see also here

More details about setAccessType can be found here

Body:
Following https://developers.google.com/identity/sign-in/web/server-side-flow After getting the authorization code from JavaScript, and passing it to the server side, we indeed get an access token (and an ID token), but not the required refresh token.

There are many posts around but could not solve it yet.

Any suggestion how to get the refresh token?

thanks!

    private String getResponseToken(GoogleClientSecrets clientSecrets,
                                                 String authCode) throws IOException {
        try {
            GoogleTokenResponse tokenResponse =
                    new GoogleAuthorizationCodeTokenRequest(
                            new NetHttpTransport(),
                            JacksonFactory.getDefaultInstance(),
                            "https://www.googleapis.com/oauth2/v4/token",
//                        "https://accounts.google.com/o/oauth2/token",
                            clientSecrets.getDetails().getClientId(),
                            clientSecrets.getDetails().getClientSecret(),

                            authCode, //NOTE: was received from JavaScript client

                            "postmessage" //TODO: what's this?
                            ).execute();
            String accessToken = tokenResponse.getAccessToken();
            String idToken = tokenResponse.getIdToken();

            //TODO: not getting a refresh token... why?!
            String refreshToken = tokenResponse.getRefreshToken();
            Boolean hasRefreshToken = new Boolean(!(refreshToken == null));
            LOGGER.warn("received refresh token: {}", hasRefreshToken);

            LOGGER.debug("accessToken: {}, refreshToken: {}, idToken: {}", accessToken, refreshToken, idToken);
            return accessToken;
        }catch (TokenResponseException tre){...}

Body:
you should add the

AccessType = "offline"

You need to call the function

new GoogleAuthorizationCodeRequestUrl(...).setAccessType("offline")

or another syntax:

var authReq = new GoogleAuthorizationCodeRequestUrl(new Uri(GoogleAuthConsts.AuthorizationUrl)) {
    RedirectUri = Callback,
    ClientId = ClientId,
    AccessType = "offline",
    Scope = string.Join(" ", new[] { Scopes... }),
    ApprovalPrompt = "force"
};

in Fiddler you should see the following request:

https://accounts.google.com/o/oauth2/auth?scope=https://www.googleapis.com/auth/webmasters&redirect_uri=http://mywebsite.com/google/scapi/callback/&response_type=code&client_id=xxx&access_type=offline

see also here

More details about setAccessType can be found here


问:
Split string into array in Python
I have a string with the following structure.

string = "[abcd, abc, a, b, abc]"

I would like to convert that into an array. I keep using the split function in Python but I get spaces and the brackets on the start and the end of my new array. I tried working around it with some if statements but I keep missing letters in the end from some words.

Keep in mind that I don't know the length of the elements in the string. It could be 1, 2, 3 etc.

答:
another way to solve this problem

```<code>string = "[abcd, abc, a, b, abc]"
result = string[1:len(string)-1].split(", ")
print(result)
</code>```

Hope this helps

Title: Split string into array in Python

Body:
another way to solve this problem

string = "[abcd, abc, a, b, abc]"
result = string[1:len(string)-1].split(", ")
print(result)

Hope this helps


问:
Parsing key values pairs from text as dictionary
I'm still quite new to Python and I was wondering how would I convert something that is already in key:value form in a text file into a Python dictionary?

Eg.

```<code>2:red
3:orange
5:yellow
6:green
</code>```

(each key:value on a separate line)

I've looked at other posts but none of them seem to work and I know I'm doing something wrong. So far, I have:

```<code>def create_colours_dictionary(filename):
    colours_dict = {}
    file = open(filename,'r')
    contents = file.read()

    for key in contents:
        #???
    return colours_dict
</code>```

答:
Assuming the textfile has the stated 'key:value' and the name of the file is contained in the variable fname you could write a function that will read the file and return a dict or just use a simple with statment.

A function is probably a better choice if this opertion is performed in several places in your code.  If only done once a 2-liner will do fine.

```<code>    # Example with fname being the path to the textfile
    def dict_from(fname):
        return dict(line.strip().split(':') for line in open(fname))

    fname = '...'
    # ...
    d1 = dict_from(fname)

    # Alternative solution
    with open(fname) as fd:
       d2 = dict(line.strip().split(':') for line in fd)
</code>```

Both suggested solutions uses a built-in dictconstructor and a generator expression to parse each line. Use strip to remove white space at both start and end of the line.  Use split create a (key, value) pair from each line.

Body:
I'm still quite new to Python and I was wondering how would I convert something that is already in key:value form in a text file into a Python dictionary?

Eg.

2:red
3:orange
5:yellow
6:green

(each key:value on a separate line)

I've looked at other posts but none of them seem to work and I know I'm doing something wrong. So far, I have:

def create_colours_dictionary(filename):
    colours_dict = {}
    file = open(filename,'r')
    contents = file.read()

    for key in contents:
        #???
    return colours_dict

Body:
Assuming the textfile has the stated 'key:value' and the name of the file is contained in the variable fname you could write a function that will read the file and return a dict or just use a simple with statment.

A function is probably a better choice if this opertion is performed in several places in your code.  If only done once a 2-liner will do fine.

    # Example with fname being the path to the textfile
    def dict_from(fname):
        return dict(line.strip().split(':') for line in open(fname))

    fname = '...'
    # ...
    d1 = dict_from(fname)

    # Alternative solution
    with open(fname) as fd:
       d2 = dict(line.strip().split(':') for line in fd)

Both suggested solutions uses a built-in dictconstructor and a generator expression to parse each line. Use strip to remove white space at both start and end of the line.  Use split create a (key, value) pair from each line.


问:
Why is selfregistration bad?
Assuming self-registration is used to install components as part of a larger installer program, why is self-registration bad? E.g. self-registering vb custom controls or capicom or whatever.  I acknowledge that self-registration is probably not as safe in the case of a dll you wrote yourself, but I'm not discussing those.

The MSDN lists several reasons why self-registration is bad, reproduced here:

 Rollback won't work properly.

OK, this reason makes sense.

 Advertisement will not work as well.

Ignoring the fact that advertisement is only important for certain types of software clients, I don't understand why this is an issue.  Only the main application needs to be advertised, not its components.

Self-registration does not support per-user keys properly.

So what? Giving every user access to "common" components is not a bad thing unless you have a lot of users on the machine, in which case it's still not world-ending.

 Self-registration is more susceptible to coding errors.

I can definitely believe this, except in the case of dlls which were written by Microsoft (they may have errors, but I don't think trusting them is unreasonable).  And in the case of tlbs and ocxs which were generated by software, coding errors seem pretty unlikely.

 Self-registering dlls may link to other dlls.

In the case of dlls generated by programs, it doesn't seem likely that self-registration will fail due to this but adding the registration keys manually would have worked.  I'd rather have my self-registration return an error that I'm missing the dlls.

I'm sure this will draw flames :/

Edit: Crossed out arguments that I think actually matter (based on user responses and my own).

答:
As far as this item:

Self-registration does not support per-user keys properly.

So what? Giving every user access
  to "common" components is not a bad
  thing unless you have a lot of users
  on the machine, in which case it's
  still not world-ending.

It's not just a matter of how many users are on a machine, but also what permissions they have.  If not an administrator, the user will be unlikely to have permission to update the HKEY_LOCAL_MACHINE portion of the registry.

OwnerDisplayName: Brian

Title: Why is selfregistration bad?

LastEditorDisplayName: Brian

OwnerDisplayName: Michael Burr


答:
You can do it, but you need to be quite careful to make sure that two simultaneous inserts don't get given the same gkey. I'd design it with these two design points:

In the GoodsCategory table, have a counter which helps to generate the next gkey.

Use locks so that only one process can generate a new key at any one time.

Here's the details:

1. Add a couple of columns to the GoodsCategory table:

```<code>+----------------------+---------------+------+-----+---------+-------+
| Field                | Type          | Null | Key | Default | Extra |
+----------------------+---------------+------+-----+---------+-------+
| ID                   | TINYINT       | NO   | PRI |         |       |
| NAME                 | VARCHAR(80)   | NO   |     |         |       |
| KeyCode              | CHAR(5)       | NO   |     |         |       |
| NextID               | INT           | NO   |     | 0       |       |
+----------------------+---------------+------+-----+---------+-------+
</code>```

The KeyCode has 'BOOK' or 'PHONE', and the NextID field stores an int which is used to generate the next key of that type i.e. if the table looks like this:

```<code>+----------------+------------+---------+--------+
| ID             | NAME       | KeyCode | NextID |
+----------------+------------+---------+--------+
| 1              | book       | BOOK    | 3      |
| 2              | phone      | PHONE   | 7      |
+----------------+------------+---------+--------+
</code>```

Then the next time you add a book, it should be given gkey 'BOOK-3', and NextID is incremented to 4.

2: The locking will need to be done in a stored routine, because it involves multiple statements in a transaction and uses local variables too. The core of it should look something like this:

```<code>START TRANSACTION;
SELECT KeyCode, NextID INTO v_kc, v_int FROM GoodsCategory WHERE ID = 2 FOR UPDATE;
SET v_newgkey = v_kc + '-' + CAST(v_int AS CHAR);
INSERT INTO goods (gkey, goods, ...) VALUES (v_newgkey, 2, etc);
UPDATE GoodsCategory SET NextID = NextID + 1 WHERE ID = 2;
COMMIT;
</code>```

The FOR UPDATE bit is crucial; have a look at the Usage Examples in the mysql manual where it discusses how to use locks to generate an ID without interference from another process.

Title: MYSQL - how to a second unique string key?

Body:
Here is my goods table.

+----------------------+---------------+------+-----+---------+-------+
| Field                | Type          | Null | Key | Default | Extra |
+----------------------+---------------+------+-----+---------+-------+
| ID                   | decimal(18,0) | NO   | PRI |         |       |
| gkey                 | varchar(255)  | YES  | MUL | NULL    |       |
| GOODS                | decimal(18,0) | YES  | MUL | NULL    |       |

Column ID is auto-increment.
GOODS is the id of a goods category.
Here is the goods category table.

+-------+---------------------+
| ID    | NAME                |
+-------+---------------------+
| 1     | book                |
| 2     | phone               |
+-------+---------------------+

My question is in goods table I need the gkey is also an unique key with prefix-id(here id is started from 1.) Like BOOK-1,BOOK-2....PHONE-1,PHONE-2... when insert a new goods record into goods table.
Like that:

+--------------------+---------------+------+-----+---------+-------+
| ID                 | GKEY          |GOODS | PRI | COUNTRY | Extra |
+--------------------+---------------+------+-----+---------+-------+
| 1                  | BOOK-1        | 1    | 10  |         |       |
| 2                  | PHONE-1       | 2    | 12  |         |       |
| 3                  | BOOK-2        | 1    | 13  |         |       |
| 4                  | BOOK-3        | 1    | 10  |         |       |
| 5                  | PHONE-2       | 2    | 10  |         |       |
| 6                  | PHONE-3       | 2    | 20  |         |       |
+--------------------+---------------+------+-----+---------+-------+

How to get that GKEY in PHP+MYSQL?

thanks.

Body:
You can do it, but you need to be quite careful to make sure that two simultaneous inserts don't get given the same gkey. I'd design it with these two design points:

In the GoodsCategory table, have a counter which helps to generate the next gkey.

Use locks so that only one process can generate a new key at any one time.

Here's the details:

1. Add a couple of columns to the GoodsCategory table:

+----------------------+---------------+------+-----+---------+-------+
| Field                | Type          | Null | Key | Default | Extra |
+----------------------+---------------+------+-----+---------+-------+
| ID                   | TINYINT       | NO   | PRI |         |       |
| NAME                 | VARCHAR(80)   | NO   |     |         |       |
| KeyCode              | CHAR(5)       | NO   |     |         |       |
| NextID               | INT           | NO   |     | 0       |       |
+----------------------+---------------+------+-----+---------+-------+

The KeyCode has 'BOOK' or 'PHONE', and the NextID field stores an int which is used to generate the next key of that type i.e. if the table looks like this:

+----------------+------------+---------+--------+
| ID             | NAME       | KeyCode | NextID |
+----------------+------------+---------+--------+
| 1              | book       | BOOK    | 3      |
| 2              | phone      | PHONE   | 7      |
+----------------+------------+---------+--------+

Then the next time you add a book, it should be given gkey 'BOOK-3', and NextID is incremented to 4.

2: The locking will need to be done in a stored routine, because it involves multiple statements in a transaction and uses local variables too. The core of it should look something like this:

START TRANSACTION;
SELECT KeyCode, NextID INTO v_kc, v_int FROM GoodsCategory WHERE ID = 2 FOR UPDATE;
SET v_newgkey = v_kc + '-' + CAST(v_int AS CHAR);
INSERT INTO goods (gkey, goods, ...) VALUES (v_newgkey, 2, etc);
UPDATE GoodsCategory SET NextID = NextID + 1 WHERE ID = 2;
COMMIT;

The FOR UPDATE bit is crucial; have a look at the Usage Examples in the mysql manual where it discusses how to use locks to generate an ID without interference from another process.


答:
Angular CLI github

you will use NPM to install angularCLI

```<code>npm install -g @angular/cli
</code>```

notice -g parameter it will install cli globally and you can you it in any new project from now on.

CLI is installed in NPM.

Title: Where will Angular-cli be installed?

Body: Where will Angular-cli be installed?can I run Angular-cli expression without install it globaly?

Body:
Angular CLI github

you will use NPM to install angularCLI

npm install -g @angular/cli

notice -g parameter it will install cli globally and you can you it in any new project from now on.

CLI is installed in NPM.


问:
How to "Unlock Jenkins"?
I am installing Jenkins 2 on windows,after installing,a page is opened,URL is:

http://localhost:8080/login?from=%2F

content of the page is like this:

Question:

How to "Unlock Jenkins"?

PS:I have looked for the answer in documentation and google.

答:
Check https://wiki.jenkins-ci.org/display/JENKINS/Logging to see where Jenkins is logging its files.

e.g. for Linux, use the command: less /var/log/jenkins/jenkins.log

And scroll down to the part: "Jenkins initial setup is required. An admin user has been created ... to proceed to installation:

[randompasswordhere] <--- Copy and paste

Linux

By default logs should be made available in /var/log/jenkins/jenkins.log, unless customized in /etc/default/jenkins (for *.deb) or via /etc/sysconfig/jenkins (for */rpm)

Windows

By default logs should be at %JENKINS_HOME%/jenkins.out and %JENKINS_HOME%/jenkins.err, unless customized in %JENKINS_HOME%/jenkins.xml

Mac OS X

Log files should be at /var/log/jenkins/jenkins.log, unless customized in org.jenkins-ci.plist

Title: How to "Unlock Jenkins"?


问:
Android - Layout doesn't appear on the device as it appears on the preview
This is the code of the XML file of the layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.barda.wikirace.MainActivity"
    android:background="@drawable/backgroundmain"
    android:orientation="vertical"
    android:weightSum="1"
    android:id="@+id/activity_main"
    >

    <ImageView
        android:id="@+id/wikiRaceTop"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:background="@android:color/transparent"
        app:srcCompat="@drawable/wikiracetop" />

    <TextView
        android:id="@+id/emptyView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
         />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="1"
        >
        <View
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="0.25"/>

        <Button
            android:layout_marginBottom="7dp"
            android:id="@+id/twoPlayersBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/twoplayersbutton"
            />

        <View
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="0.5"/>

        <Button
            android:layout_marginBottom="7dp"
            android:id="@+id/singlePlayerBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/playbutton"
            android:onClick="startSinglePlayerMenuActivity"/>
        <View
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="0.25"/>

    </LinearLayout>

</LinearLayout>
</code>```

This is how it looks in the preview:

And this is how it appears on the device (LG G4):

What can cause the problem?
As you can see, I want the buttons to be on the right color for them.

答:
why don't just use the constraint layout?
if you want to do it in the way you're doing it, you will have to setup the width with a fixed value or match_parent why? because when you say wrap_content and the image is big is going to be over the other views as is happening also you can setup a android:layout_weight for the button if you want to use the weight as "control" for your layout, be coherent with the method that you use to adapt the views.</p>

Body:
This is the code of the XML file of the layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.barda.wikirace.MainActivity"
    android:background="@drawable/backgroundmain"
    android:orientation="vertical"
    android:weightSum="1"
    android:id="@+id/activity_main"
    >

    <ImageView
        android:id="@+id/wikiRaceTop"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:background="@android:color/transparent"
        app:srcCompat="@drawable/wikiracetop" />

    <TextView
        android:id="@+id/emptyView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
         />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="1"
        >
        <View
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="0.25"/>

        <Button
            android:layout_marginBottom="7dp"
            android:id="@+id/twoPlayersBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/twoplayersbutton"
            />

        <View
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="0.5"/>

        <Button
            android:layout_marginBottom="7dp"
            android:id="@+id/singlePlayerBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/playbutton"
            android:onClick="startSinglePlayerMenuActivity"/>
        <View
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="0.25"/>

    </LinearLayout>

</LinearLayout>

This is how it looks in the preview:

And this is how it appears on the device (LG G4):

What can cause the problem?
As you can see, I want the buttons to be on the right color for them.


问:
How to pass an integer to a parameter through HashMap?
Am new to java and have a query.Please suggest me a solution :

Am doing API level testing and need to pass the request body parameters of a service like below :

答: Java is strongly typed language, so your Map can't store Integer values, as String is defined as both key and value. If you want to store any object - changed map to Map<String, Object>


问:
Parent Child Relationship With A Single Entity In Doctrine 2
I have database table that looks like this:

```
+----+--------+--------------------+
| id | parent | description        |
+----+--------+--------------------+
|  1 | null   | P Cat 1            |
|  2 | 1      | Child 1 of P Cat 1 |
|  3 | 1      | Child 2 of P Cat 1 |
|  4 | null   | P Cat 2            |
|  5 | 4      | Child 1 of P Cat 2 |
|  6 | 4      | Child 2 of P Cat 2 |
+----+--------+--------------------+
```

How can I create a doctrine 2 entity that has these columns, but I need the parent column to reference the "id" column as a parent. Of course, a parent record has a null "parent" column value.

So fair I have

```<code><?php
namespace MyNamespace;
use Doctrine\ORM\Mapping AS ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
 * @ORM\Entity
 * @ORM\Table(name="category")
 **/
class Category
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer", name="id")
     * @ORM\GeneratedValue
     */
    protected $id;

    /**
     * Creates a parent / child relationship on this entity.
     *
     * @ORM\ManyToOne(targetEntity="MyNamespace\Category",inversedBy="id")
     * @ORM\JoinColumn(name="FK_parent_id", referencedColumnName="id", nullable=true)
     */
    protected $parent = null;

    /**
     * @ORM\Column(type="string", name="description", length=250)
     *
     * @var string
     */
    protected $description;

    /**
     * Gets the Primary key value.
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Sets another category ID as the parent of this category.
     */
    public function setParent(Category $category)
    {
        $this->parent = $category;
    }

    /**
     * Clears the parent id and makes it null.
     */
    public function clearParent()
    {
        $this->parent = null;
    }

    /**
     * Sets the description.
     *
     * @param string $description
     * @return Category
     */
    public function setDescription($description)
    {
        $this->description = $description;
        return $this;
    }

    /**
     * Gets the description value.
     *
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }
}
</code>```

Needless to say, this doesn't appear to work. The questions are:

The setParent() method doesn't appear to work as expected when another entity is added as a parent.

I need a getChildren() method on this entity. How can I achieve that?

答:
If you're using XML, the configuration would look like this :</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping"
                  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                  xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
    <entity repository-class="AppBundle\Repository\CategoryRepository" name="AppBundle\Entity\Category">
        <id name="id" type="integer" column="id">
            <generator strategy="AUTO"/>
        </id>
        <field name="description" type="string" column="description" length="255"/>
        <many-to-one target-entity="Category" inversed-by="children" field="parent">
            <join-column name="parent" referenced-column-name="id"/>
        </many-to-one>
        <one-to-many target-entity="Category" mapped-by="parent" field="child"/>
    </entity>
</doctrine-mapping>
</code>```

Body:
I have database table that looks like this:

+----+--------+--------------------+
| id | parent | description        |
+----+--------+--------------------+
|  1 | null   | P Cat 1            |
|  2 | 1      | Child 1 of P Cat 1 |
|  3 | 1      | Child 2 of P Cat 1 |
|  4 | null   | P Cat 2            |
|  5 | 4      | Child 1 of P Cat 2 |
|  6 | 4      | Child 2 of P Cat 2 |
+----+--------+--------------------+

How can I create a doctrine 2 entity that has these columns, but I need the parent column to reference the "id" column as a parent. Of course, a parent record has a null "parent" column value.

So fair I have

<?php
namespace MyNamespace;
use Doctrine\ORM\Mapping AS ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
 * @ORM\Entity
 * @ORM\Table(name="category")
 **/
class Category
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer", name="id")
     * @ORM\GeneratedValue
     */
    protected $id;

    /**
     * Creates a parent / child relationship on this entity.
     *
     * @ORM\ManyToOne(targetEntity="MyNamespace\Category",inversedBy="id")
     * @ORM\JoinColumn(name="FK_parent_id", referencedColumnName="id", nullable=true)
     */
    protected $parent = null;

    /**
     * @ORM\Column(type="string", name="description", length=250)
     *
     * @var string
     */
    protected $description;

    /**
     * Gets the Primary key value.
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Sets another category ID as the parent of this category.
     */
    public function setParent(Category $category)
    {
        $this->parent = $category;
    }

    /**
     * Clears the parent id and makes it null.
     */
    public function clearParent()
    {
        $this->parent = null;
    }

    /**
     * Sets the description.
     *
     * @param string $description
     * @return Category
     */
    public function setDescription($description)
    {
        $this->description = $description;
        return $this;
    }

    /**
     * Gets the description value.
     *
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }
}

Needless to say, this doesn't appear to work. The questions are:

The setParent() method doesn't appear to work as expected when another entity is added as a parent.

I need a getChildren() method on this entity. How can I achieve that?

Body:
If you're using XML, the configuration would look like this :

<?xml version="1.0" encoding="utf-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping"
                  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                  xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
    <entity repository-class="AppBundle\Repository\CategoryRepository" name="AppBundle\Entity\Category">
        <id name="id" type="integer" column="id">
            <generator strategy="AUTO"/>
        </id>
        <field name="description" type="string" column="description" length="255"/>
        <many-to-one target-entity="Category" inversed-by="children" field="parent">
            <join-column name="parent" referenced-column-name="id"/>
        </many-to-one>
        <one-to-many target-entity="Category" mapped-by="parent" field="child"/>
    </entity>
</doctrine-mapping>