问:
Using an ngFor to traverse a 2 dimensional array
I've been beating my head up against the wall on this one for a while but I finally feel close. What I'm trying to do is read my test data, which goes to a two dimensional array, and print its contents to a table in the html, but I can't figure out how to use an ngfor to loop though that dataset

Here is my typescript file

```<code>import { Component } from '@angular/core';
import { Http } from '@angular/http';

@Component({
    selector: 'fetchdata',
    template: require('./fetchdata.component.html')
})
export class FetchDataComponent {
    public tableData: any[][];

    constructor(http: Http) {

        http.get('/api/SampleData/DatatableData').subscribe(result => {
            //This is test data only, could dynamically change
            var arr = [
                { ID: 1, Name: "foo", Email: "foo@foo.com" },
                { ID: 2, Name: "bar", Email: "bar@bar.com" },
                { ID: 3, Name: "bar", Email: "bar@bar.com" }
            ]
            var res = arr.map(function (obj) {
                return Object.keys(obj).map(function (key) {
                    return obj[key];
                });
            });

            this.tableData = res;
            console.log("Table Data")
            console.log(this.tableData)
        });
    }
}
</code>```

Here is my html which does not work at the moment

```<code><p *ngIf="!tableData"><em>Loading...</em></p>

<table class='table' *ngIf="tableData">
    <tbody>
        <tr *ngFor="let data of tableData; let i = index">
            <td>
            {{ tableData[data][i] }}
            </td>

        </tr>
    </tbody>
</table>
</code>```

Here is the output from my console.log(this.tableData)

My goal is to have it formatted like this in the table

```<code>1 | foo | bar@foo.com
2 | bar | foo@bar.com
</code>```

Preferably I'd like to not use a model or an interface because the data is dynamic, it could change at any time. Does anyone know how to use the ngfor to loop through a two dimensional array and print its contents in the table?

答:
Like Marco Luzzara said, you have to use another *ngFor for the nested arrays.

I answer this just to give you a code example:

```<code><table class='table' *ngIf="tableData">
    <tbody>
        <tr *ngFor="let data of tableData; let i = index">
            <td *ngFor="let cell of data">
              {{ cell }}
            </td>
        </tr>
    </tbody>
</table>
</code>```

Body:
I've been beating my head up against the wall on this one for a while but I finally feel close. What I'm trying to do is read my test data, which goes to a two dimensional array, and print its contents to a table in the html, but I can't figure out how to use an ngfor to loop though that dataset

Here is my typescript file

import { Component } from '@angular/core';
import { Http } from '@angular/http';

@Component({
    selector: 'fetchdata',
    template: require('./fetchdata.component.html')
})
export class FetchDataComponent {
    public tableData: any[][];

    constructor(http: Http) {

        http.get('/api/SampleData/DatatableData').subscribe(result => {
            //This is test data only, could dynamically change
            var arr = [
                { ID: 1, Name: "foo", Email: "foo@foo.com" },
                { ID: 2, Name: "bar", Email: "bar@bar.com" },
                { ID: 3, Name: "bar", Email: "bar@bar.com" }
            ]
            var res = arr.map(function (obj) {
                return Object.keys(obj).map(function (key) {
                    return obj[key];
                });
            });

            this.tableData = res;
            console.log("Table Data")
            console.log(this.tableData)
        });
    }
}

Here is my html which does not work at the moment

Loading...

            {{ tableData[data][i] }}

Here is the output from my console.log(this.tableData)

My goal is to have it formatted like this in the table

1 | foo | bar@foo.com
2 | bar | foo@bar.com

Preferably I'd like to not use a model or an interface because the data is dynamic, it could change at any time. Does anyone know how to use the ngfor to loop through a two dimensional array and print its contents in the table?

Body:
Like Marco Luzzara said, you have to use another *ngFor for the nested arrays.

I answer this just to give you a code example:

<table class='table' *ngIf="tableData">
    <tbody>
        <tr *ngFor="let data of tableData; let i = index">
            <td *ngFor="let cell of data">
              {{ cell }}
            </td>
        </tr>
    </tbody>
</table>


来源: stackexchange

问:
how to convert Thu Apr 06 14:30:00 IST 2017 for to this format 2017-07-05T16:50:22.490 in N1QL query
how to convert "Thu Apr 06 14:30:00 IST 2017" for to this format
"2017-07-05T16:50:22.490" in N1QL query</p>

答:
Before inserting it into Couchbase, when you get the date from the other services, you have to first convert it into milliseconds. Once you do this then you can use the MILLIS_TO_STR date function to convert it to the format you want. The list of formats and the date function description is given in </p>

<p>https://developer.couchbase.com/documentation/server/current/n1ql/n1ql-language-reference/datefun.html </p>

ContentLicense: CC BY-SA 3.0

Body:
Before inserting it into Couchbase, when you get the date from the other services, you have to first convert it into milliseconds. Once you do this then you can use the MILLIS_TO_STR date function to convert it to the format you want. The list of formats and the date function description is given in

https://developer.couchbase.com/documentation/server/current/n1ql/n1ql-language-reference/datefun.html


问:
Node Express Server Cannot GET "/"
I am writing some code for my node server and everything is working fine locally. However, when I deploy it, I get the infamous "Cannot GET /" 404 error. All of the other routes which I have written work successfully (Both locally and in the cloud).

I have included the code below. I've checked my environment variables and all of them properly align. If any of you have any theories concerning the cause of this, it would be much appreciated.

//Use this route to make the entire app secure.  This forces login for any path in the entire app.
  app.use('/', passport.authenticate('main', {
    noredirect: false //Don't redirect a user to the authentication page, just show an error
  }),
    express.static(path.join(__dirname, '../public'))
  );```

答:
To clarify @aprouja1

```<code>// You usually want to declare statics separately for code organisation
app.use(express.static(path.join(__dirname, '../public')))

app.use('/',
  passport.authenticate('main', {
    noredirect: false
  }),
  function(req, res) {
    res.sendFile('index.html')
  }
);
</code>```

For an index page apart of an application of any complexity, it's probably better to use a rendering engine, e.g. pug.

  ```<code>app.set('views', __dirname + '/views'); // Not required. Set by default. Being explicit.
app.engine('pug', require('pug').__express); // Not required. Automatically loaded by express. Again, being explicit.
app.set('view engine', 'pug'); // Required, see: https://expressjs.com/en/guide/using-template-engines.html

app.use('/',
  passport.authenticate('main', {
    noredirect: false
  }),
  function(req, res) {
    res.render('index') // Renders `/views/index.pug`
  }
);
</code>```

Title: Node Express Server Cannot GET "/"

Body:
To clarify @aprouja1

// You usually want to declare statics separately for code organisation
app.use(express.static(path.join(__dirname, '../public')))

app.use('/',
  passport.authenticate('main', {
    noredirect: false
  }),
  function(req, res) {
    res.sendFile('index.html')
  }
);

For an index page apart of an application of any complexity, it's probably better to use a rendering engine, e.g. pug.

app.set('views', __dirname + '/views'); // Not required. Set by default. Being explicit.
app.engine('pug', require('pug').__express); // Not required. Automatically loaded by express. Again, being explicit.
app.set('view engine', 'pug'); // Required, see: https://expressjs.com/en/guide/using-template-engines.html

app.use('/',
  passport.authenticate('main', {
    noredirect: false
  }),
  function(req, res) {
    res.render('index') // Renders `/views/index.pug`
  }
);


问:
check radiobutton 1, when radiobutton 3 is checked
i have html page like this

```<code><br>Q1A Making decisions after finding out what others think <br>
                        <input name="q1a" id="0" value="0" onclick="MyAlert()" type="radio" required>
                        <input name="q1a" id="1" value="1" onclick="MyAlert()" type="radio" required>
                        <input name="q1a" id="2" value="2" onclick="MyAlert()" type="radio" required>
                        <input name="q1a" id="3" value="3" onclick="MyAlert()" type="radio" required>
                        <input name="q1a" id="4" value="4" onclick="MyAlert()" type="radio" required>
                        <input name="q1a" id="5" value="5" onclick="MyAlert()" type="radio" required>

                        <br>Q1B Making decisions without consulting others <br>
                        <input name="q1b" id="6" value="0" onclick="MyAlert()" type="radio" required>
                        <input name="q1b" id="7" value="1" onclick="MyAlert()" type="radio" required>
                        <input name="q1b" id="8" value="2" onclick="MyAlert()" type="radio" required>
                        <input name="q1b" id="9" value="3" onclick="MyAlert()" type="radio" required>
                        <input name="q1b" id="10" value="4" onclick="MyAlert()" type="radio" required>
                        <input name="q1b" id="11" value="5" onclick="MyAlert()" type="radio" required>
</code>```

if Q1A's value 1 is checked by user, at that moment i want to check Q1B's value 4. analogy is, Q1A's value + Q1B's value = 5.

how can i do this ?
my rough idea is:

```<code><script>
    function MyAlert()
    {
      var q1a = document.getElementByName("q1a").value();
      if(q1a == 0){
        $('#5[name="q1b"]').attr('checked', true);
      }
    }
</script>
</code>```

but this is not working.

```<code>    <a href="https://jsfiddle.net/zLgmc5be/"> My Code Example </a>
</code>```

Thank you for help.

答:
You have duplicate IDs, that won't work. getElementById() just returns the first element with that ID.

Instead of finding the element by its ID, find it by its value, a [value=] selector.

function MyAlert(button) {
  if (button.name == 'q19a') {
    var otherName = 'q19b';
    var otherVal = 5 - button.value;
    $(":radio[name=" + otherName + "][value=" + otherVal + "]").prop("checked", true);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<br>Q19A Using common sense and conviction to make decisions <br>
<input name="q19a" value="0" onclick="MyAlert(this)" type="radio" required>
<input name="q19a" value="1" onclick="MyAlert(this)" type="radio" required>
<input name="q19a" value="2" onclick="MyAlert(this)" type="radio" required>
<input name="q19a" value="3" onclick="MyAlert(this)" type="radio" required>
<input name="q19a" value="4" onclick="MyAlert(this)" type="radio" required>
<input name="q19a" value="5" onclick="MyAlert(this)" type="radio" required>

<br>Q19B Using data, analysis, and reason to make decisions <br>
<input name="q19b" value="0" onclick="MyAlert(this)" type="radio" required>
<input name="q19b" value="1" onclick="MyAlert(this)" type="radio" required>
<input name="q19b" value="2" onclick="MyAlert(this)" type="radio" required>
<input name="q19b" value="3" onclick="MyAlert(this)" type="radio" required>
<input name="q19b" value="4" onclick="MyAlert(this)" type="radio" required>
<input name="q19b" value="5" onclick="MyAlert(this)" type="radio" required>

<br>Q20A Planning ahead based on projections <br>
<input name="q20a" value="0" onclick="MyAlert(this)" type="radio" required>
<input name="q20a" value="1" onclick="MyAlert(this)" type="radio" required>
<input name="q20a" value="2" onclick="MyAlert(this)" type="radio" required>
<input name="q20a" value="3" onclick="MyAlert(this)" type="radio" required>
<input name="q20a" value="4" onclick="MyAlert(this)" type="radio" required>
<input name="q20a" value="5" onclick="MyAlert(this)" type="radio" required>

<br>Q20B Planning as necessities arise, just before carrying out the plans <br>
<input name="q20b" value="0" onclick="MyAlert(this)" type="radio" required>
<input name="q20b" value="1" onclick="MyAlert(this)" type="radio" required>
<input name="q20b" value="2" onclick="MyAlert(this)" type="radio" required>
<input name="q20b" value="3" onclick="MyAlert(this)" type="radio" required>
<input name="q20b" value="4" onclick="MyAlert(this)" type="radio" required>
<input name="q20b" value="5" onclick="MyAlert(this)" type="radio" required></code>```

Body:
i have html page like this

Q1A Making decisions after finding out what others think

                        <input name="q1a" id="0" value="0" onclick="MyAlert()" type="radio" required>
                        <input name="q1a" id="1" value="1" onclick="MyAlert()" type="radio" required>
                        <input name="q1a" id="2" value="2" onclick="MyAlert()" type="radio" required>
                        <input name="q1a" id="3" value="3" onclick="MyAlert()" type="radio" required>
                        <input name="q1a" id="4" value="4" onclick="MyAlert()" type="radio" required>
                        <input name="q1a" id="5" value="5" onclick="MyAlert()" type="radio" required>

Q1B Making decisions without consulting others

                        <input name="q1b" id="6" value="0" onclick="MyAlert()" type="radio" required>
                        <input name="q1b" id="7" value="1" onclick="MyAlert()" type="radio" required>
                        <input name="q1b" id="8" value="2" onclick="MyAlert()" type="radio" required>
                        <input name="q1b" id="9" value="3" onclick="MyAlert()" type="radio" required>
                        <input name="q1b" id="10" value="4" onclick="MyAlert()" type="radio" required>
                        <input name="q1b" id="11" value="5" onclick="MyAlert()" type="radio" required>

if Q1A's value 1 is checked by user, at that moment i want to check Q1B's value 4. analogy is, Q1A's value + Q1B's value = 5.

how can i do this ?
my rough idea is:

but this is not working.

     My Code Example

Thank you for help.

Body:
You have duplicate IDs, that won't work. getElementById() just returns the first element with that ID.

Instead of finding the element by its ID, find it by its value, a [value=] selector.

function MyAlert(button) {
  if (button.name == 'q19a') {
    var otherName = 'q19b';
    var otherVal = 5 - button.value;
    $(":radio[name=" + otherName + "][value=" + otherVal + "]").prop("checked", true);
  }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<br>Q19A Using common sense and conviction to make decisions <br>
<input name="q19a" value="0" onclick="MyAlert(this)" type="radio" required>
<input name="q19a" value="1" onclick="MyAlert(this)" type="radio" required>
<input name="q19a" value="2" onclick="MyAlert(this)" type="radio" required>
<input name="q19a" value="3" onclick="MyAlert(this)" type="radio" required>
<input name="q19a" value="4" onclick="MyAlert(this)" type="radio" required>
<input name="q19a" value="5" onclick="MyAlert(this)" type="radio" required>

<br>Q19B Using data, analysis, and reason to make decisions <br>
<input name="q19b" value="0" onclick="MyAlert(this)" type="radio" required>
<input name="q19b" value="1" onclick="MyAlert(this)" type="radio" required>
<input name="q19b" value="2" onclick="MyAlert(this)" type="radio" required>
<input name="q19b" value="3" onclick="MyAlert(this)" type="radio" required>
<input name="q19b" value="4" onclick="MyAlert(this)" type="radio" required>
<input name="q19b" value="5" onclick="MyAlert(this)" type="radio" required>

<br>Q20A Planning ahead based on projections <br>
<input name="q20a" value="0" onclick="MyAlert(this)" type="radio" required>
<input name="q20a" value="1" onclick="MyAlert(this)" type="radio" required>
<input name="q20a" value="2" onclick="MyAlert(this)" type="radio" required>
<input name="q20a" value="3" onclick="MyAlert(this)" type="radio" required>
<input name="q20a" value="4" onclick="MyAlert(this)" type="radio" required>
<input name="q20a" value="5" onclick="MyAlert(this)" type="radio" required>

<br>Q20B Planning as necessities arise, just before carrying out the plans <br>
<input name="q20b" value="0" onclick="MyAlert(this)" type="radio" required>
<input name="q20b" value="1" onclick="MyAlert(this)" type="radio" required>
<input name="q20b" value="2" onclick="MyAlert(this)" type="radio" required>
<input name="q20b" value="3" onclick="MyAlert(this)" type="radio" required>
<input name="q20b" value="4" onclick="MyAlert(this)" type="radio" required>
<input name="q20b" value="5" onclick="MyAlert(this)" type="radio" required>


问:
Simple VBA: Calling a Module from Command Button Produces ComboBox Object Required Error 424
I have a command button which is duplicated across 20 sheets, so I want to edit the code in 1 place (a module). My buttons are set up like this:

```<code>Private Sub CommandButton1_Click()
    Call Main
End Sub
</code>```

But when I click on my button, I get an object error 424 with ComboBox1:

```<code>Public Sub Main()
Set ws = ThisWorkbook.ActiveSheet
sourceFolder = "C:\MyDirectory\" & Month(DateValue("01-" & ComboBox1.Value & "-1900")) & ". " & ComboBox1.Value & " " & Year(Date) & "\"
</code>```

答:
It turns out I had to reference it as an object:

```<code>Combox1.Value
</code>```

changed to:

```<code>ws.OLEObjects("ComboBox1").Object.Value
</code>```

Everything works and I can call this module from other worksheets/buttons

Body:
I have a command button which is duplicated across 20 sheets, so I want to edit the code in 1 place (a module). My buttons are set up like this:

Private Sub CommandButton1_Click()
    Call Main
End Sub

But when I click on my button, I get an object error 424 with ComboBox1:

Public Sub Main()
Set ws = ThisWorkbook.ActiveSheet
sourceFolder = "C:\MyDirectory\" & Month(DateValue("01-" & ComboBox1.Value & "-1900")) & ". " & ComboBox1.Value & " " & Year(Date) & "\"

Body:
It turns out I had to reference it as an object:

Combox1.Value

changed to:

ws.OLEObjects("ComboBox1").Object.Value

Everything works and I can call this module from other worksheets/buttons


问:
Event handling in component based game engine design
I imagine this question or variations of it get passed around a lot, so if what I'm saying is a duplicate, and the answers lie elsewhere, please inform me.

I have been researching game engine designs and have come across the component-based entity model.  It sounds promising, but I'm still working out its implementation.

I'm considering a system where the engine is arranged of several "subsystems," which manage some aspect, like rendering, sound, health, AI, etc.  Each subsystem has a component type associated with it, like a health component for the health subsystem.  An "entity," for example an NPC, a door, some visual effect, or the player, is simply composed of one or more components, that when together give the entity its functionality.

I identified four main channels of information passing:  a component can broadcast to all components in its current entity, a component can broadcast to its subsystem, a subsystem can broadcast to its components, and a subsystem can broadcast to other subsystems.

For example, if the user wanted to move their characters, they would press a key.  This key press would be picked up by input subsystem, which then broadcasts the event and would be picked up by the player subsystem.  The player subsystem then sends this event to all player components (and thus the entities those components compose), and those player components would communicate to its own entity's position component to go ahead and move.

All of this for a key press seems a bit winded, and I am certainly open to improvements to this architecture.  But anyway, my main question still follows.

As for the events themselves, I considered where an event behaves as in the visitor pattern.  The importance of what I want is that if an event comes across a component it doesn't support (as in a move event has nothing directly to do with AI or health), it would ignore the component.  If an event doesn't find the component it's going after, it doesn't matter.

The visitor pattern almost works.  However, it would require that I have virtual functions for every type of component (i.e. visitHealthComponent, visitPositionComponent, etc.) even if it doesn't have anything to do with them.  I could leave these functions empty (so if it did come across those components, it would be ignored), but I would have to add another function every time I add a component.

My hopes were that I would be able to add a component without necessarily adding stuff to other places, and add an event without messing with other stuff.

So, my two questions:

Are there any improvements my design could allow, in terms of efficiency, flexibility, etc.?

What would be the optimal way to handle events?

答:
Use an event bus, aka event aggregator. What you want is an event mechanism that requires no coupling between subsystems, and an event bus will do just that.

http://martinfowler.com/eaaDev/EventAggregator.html
http://stackoverflow.com/questions/2343980/event-aggregator-implementation-sample-best-practices

etc

ContentLicense: CC BY-SA 2.5


问:
How to set the outline of the elements on tab only and not on click?
I am doing some tasks for accessibility(ADA) and the team asked me to set a visual pointer on tab only and not on click.

Right now I may see the light-blue outline when I click on the anchors and also when I tab over them.
I need that outline to appear only on tab.

Any suggestions?

答:
So this will handle both clicks or tabkey events. They display differently, but then both call the same function. Hope it helps!

/*********
 * function that simply toggles the pane.
 *  doesn't care what calls it, simply that
 *  it gets the proper data. We can call it
 *  in the click handler (as in the HTML) or
 *  in the keyup handler (as below).
 *  either has the same functionality, but
 *  can have their own processing.
 *********/
openCity = function openCity(evt, cityName) {
  // Declare all variables
  var i, tabcontent, tablinks;

  // Get all elements with class="tabcontent" and hide them
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }

  // Get all elements with class="tablinks" and remove the class "active"
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }

  // Show the current tab, and add an "active" class to the button that opened the tab
  document.getElementById(cityName).style.display = "block";
  evt.currentTarget.className += " active";
}

/********
 * Handler for the tab key functionality.
 *  Processes separately from the click
 *  function, as is shown by the different
 *  coloring. However, either click or tab
 *  key can trigger the same tab display
 *  function.
 *********/

var tabIndex;
var tabEls = $(".tab button");
$(document).ready(function() {
  $(document).on("keyup", function(evt) {
    // Prevent the tab key from propagating
    evt.preventDefault();
    evt.stopPropagation();

    // tab has been pressed
    if (evt.which == 9) {
      // Currently, no tab has been chosen, so we select the first
      if ($(".tabbedActive").length == 0) {
        tabEls.eq(0).addClass("tabbedActive");
      } else {
        // we have a selected tab. So we either choose the next, or
        //  the first if we need to rotate through.
        tabIndex = tabEls.parent().find('.tabbedActive').index();

        // Remove the class from all tab els
        tabEls.removeClass('tabbedActive');
        if (tabIndex == tabEls.length - 1) {
          tabEls.eq(0).addClass("tabbedActive");
        } else {
          tabEls.eq(tabIndex + 1).addClass("tabbedActive");
        }
      }

      // Now that we have a selected tab, use that to toggle the pane
      openCity(evt, tabEls.parent().find('.tabbedActive').text() )

    }
  })
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>a
/* Style the tab */

div.tab {
  overflow: hidden;
  border: 1px solid #ccc;
}

/* Style the buttons inside the tab */

div.tab button {
  float: left;
  border: none;
  outline: none;
  cursor: pointer;
  padding: 14px 16px;
  transition: 0.3s;
}

/* Change background color of buttons on hover */

div.tab button:hover {
  background-color: #ddd;
}

/* Create an active/current tablink class */

div.tab button.active {
  background-color: #ccc;
}

.tabbedActive {
  border: 1px solid yellow;
  background-color: #cc0;
}

/* Style the tab content */

.tabcontent {
  display: none;
  padding: 6px 12px;
  border: 1px solid #ccc;
  border-top: none;
}</code>```

  <button class="tablinks" onclick="openCity(event, 'London')">London</button>
  <button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button>
  <button class="tablinks" onclick="openCity(event, 'Tokyo')">Tokyo</button>

London

London is the capital city of England.

Paris

Paris is the capital of France.

Tokyo

Tokyo is the capital of Japan.

```

Body:
So this will handle both clicks or tabkey events. They display differently, but then both call the same function. Hope it helps!

/*********
 * function that simply toggles the pane.
 *  doesn't care what calls it, simply that
 *  it gets the proper data. We can call it
 *  in the click handler (as in the HTML) or
 *  in the keyup handler (as below).
 *  either has the same functionality, but
 *  can have their own processing.
 *********/
openCity = function openCity(evt, cityName) {
  // Declare all variables
  var i, tabcontent, tablinks;

  // Get all elements with class="tabcontent" and hide them
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }

  // Get all elements with class="tablinks" and remove the class "active"
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }

  // Show the current tab, and add an "active" class to the button that opened the tab
  document.getElementById(cityName).style.display = "block";
  evt.currentTarget.className += " active";
}

/********
 * Handler for the tab key functionality.
 *  Processes separately from the click
 *  function, as is shown by the different
 *  coloring. However, either click or tab
 *  key can trigger the same tab display
 *  function.
 *********/

var tabIndex;
var tabEls = $(".tab button");
$(document).ready(function() {
  $(document).on("keyup", function(evt) {
    // Prevent the tab key from propagating
    evt.preventDefault();
    evt.stopPropagation();

    // tab has been pressed
    if (evt.which == 9) {
      // Currently, no tab has been chosen, so we select the first
      if ($(".tabbedActive").length == 0) {
        tabEls.eq(0).addClass("tabbedActive");
      } else {
        // we have a selected tab. So we either choose the next, or
        //  the first if we need to rotate through.
        tabIndex = tabEls.parent().find('.tabbedActive').index();

        // Remove the class from all tab els
        tabEls.removeClass('tabbedActive');
        if (tabIndex == tabEls.length - 1) {
          tabEls.eq(0).addClass("tabbedActive");
        } else {
          tabEls.eq(tabIndex + 1).addClass("tabbedActive");
        }
      }

      // Now that we have a selected tab, use that to toggle the pane
      openCity(evt, tabEls.parent().find('.tabbedActive').text() )

    }
  })
});

a
/* Style the tab */

div.tab {
  overflow: hidden;
  border: 1px solid #ccc;
}

/* Style the buttons inside the tab */

div.tab button {
  float: left;
  border: none;
  outline: none;
  cursor: pointer;
  padding: 14px 16px;
  transition: 0.3s;
}

/* Change background color of buttons on hover */

div.tab button:hover {
  background-color: #ddd;
}

/* Create an active/current tablink class */

div.tab button.active {
  background-color: #ccc;
}

.tabbedActive {
  border: 1px solid yellow;
  background-color: #cc0;
}

/* Style the tab content */

.tabcontent {
  display: none;
  padding: 6px 12px;
  border: 1px solid #ccc;
  border-top: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="tab">
  <button class="tablinks" onclick="openCity(event, 'London')">London</button>
  <button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button>
  <button class="tablinks" onclick="openCity(event, 'Tokyo')">Tokyo</button>
</div>

<div id="London" class="tabcontent">
  <h3>London</h3>
  <p>London is the capital city of England.</p>
</div>

<div id="Paris" class="tabcontent">
  <h3>Paris</h3>
  <p>Paris is the capital of France.</p>
</div>

<div id="Tokyo" class="tabcontent">
  <h3>Tokyo</h3>
  <p>Tokyo is the capital of Japan.</p>
</div>


问:
HMAC-SHA1 Swift 3 - 403 Forbidden
I'm trying to perform an HMAC-SHA1 signature from Swift 3 to a kong server which inreturn redirects to Twitter host( To enable HMAC on Kong - followed https://getkong.org/plugins/hmac-authentication/ )

I use the same secret key, username in my swift. Performing HMAC-SHA1 on current date with the secret key and sending request to http://localhost:8000/@foo

Swift 3 code:

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    let date = Date()
    let currentDateF = DateFormatter()
    let localeF = Locale(identifier: "en_US")
    let tzone = TimeZone(identifier: "UTC")
    currentDateF.dateFormat = "EEE, dd MMM yyyy HH:mm:ss z"
    currentDateF.timeZone = tzone
    currentDateF.locale = localeF
    let currentDate = currentDateF.string(from: date)
    let dat = "date: \(currentDate)"
    let username = "bar"
    let hmacResult: String = dat.getHmac(algorithm: .SHA1, key: "foo")
    HTTPrequest(Datestr: currentDate, hmacAuth: hmacResult, username: username)
}

func HTTPrequest(Datestr: String, hmacAuth: String, username: String) {
    let url = URL(string: "http://localhost:8000/@foo")
    var request = URLRequest(url: url!)
    request.addValue(Datestr, forHTTPHeaderField: "date")
    request.addValue("twitter.com", forHTTPHeaderField: "Host")
    request.setValue("hmac username='\(username)', algorithm='hmac-sha1', headers='date', signature='\(hmacAuth)'", forHTTPHeaderField: "Authorization")
    let dataTask = URLSession.shared.dataTask(with: request) {
        (data,response,error) in
        if error != nil {
            print(error!)
        }
        print("DATA RETURNED: \(data!)")
        let str = String(data: data!, encoding: .utf8)
        print("VALUE: \(str!)")
        print("RESPONSE: \(response!)")
    }
    dataTask.resume()
}

enum hmacAlgo {
    case SHA1
    func  toHMACAlgorithm() -> CCHmacAlgorithm {
        var result: Int = 0
        switch self {
        case .SHA1:
            result = kCCHmacAlgSHA1
        }
        return CCHmacAlgorithm(result)
    }

    func digestLength() -> Int {
        var result: CInt = 0
        switch self {
        case .SHA1:
            result = CC_SHA1_DIGEST_LENGTH
        }
        return Int(result)
    }
}

extension String  {
    func getHmac(algorithm: hmacAlgo, key: String) -> String {
        let stringData = self.cString(using: String.Encoding.ascii)
        let keyData = key.cString(using: String.Encoding.ascii)
        var result = [CUnsignedChar](repeating: 0, count: Int(algorithm.digestLength()))
        CCHmac(algorithm.toHMACAlgorithm(), keyData!, Int(strlen(keyData!)), stringData!, Int(strlen(stringData!)), &result)
        let hmacData: NSData = NSData(bytes: result, length: (Int(algorithm.digestLength())))
        let hmacb64 = hmacData.base64EncodedString(options: NSData.Base64EncodingOptions.lineLength76Characters)
        return hmacb64
    }
}
</code>```

But I get 403 Status Code - Forbidden with message stating HMAC signature cannot be verified

答:
Solved,

```<code>request.setValue("hmac username=\"\(username)\", algorithm=\"hmac-sha1\", headers=\"date\", signature=\"\(hmacAuth)\"", forHTTPHeaderField: "Authorization")
</code>```

I just wrapped the strings in the authorization header with double quotes and sent the request.
Thank you.

Title: HMAC-SHA1 Swift 3 - 403 Forbidden

Body:
I'm trying to perform an HMAC-SHA1 signature from Swift 3 to a kong server which inreturn redirects to Twitter host( To enable HMAC on Kong - followed https://getkong.org/plugins/hmac-authentication/ )

I use the same secret key, username in my swift. Performing HMAC-SHA1 on current date with the secret key and sending request to http://localhost:8000/@foo

Swift 3 code:

override func viewDidLoad() {
    super.viewDidLoad()
    let date = Date()
    let currentDateF = DateFormatter()
    let localeF = Locale(identifier: "en_US")
    let tzone = TimeZone(identifier: "UTC")
    currentDateF.dateFormat = "EEE, dd MMM yyyy HH:mm:ss z"
    currentDateF.timeZone = tzone
    currentDateF.locale = localeF
    let currentDate = currentDateF.string(from: date)
    let dat = "date: \(currentDate)"
    let username = "bar"
    let hmacResult: String = dat.getHmac(algorithm: .SHA1, key: "foo")
    HTTPrequest(Datestr: currentDate, hmacAuth: hmacResult, username: username)
}

func HTTPrequest(Datestr: String, hmacAuth: String, username: String) {
    let url = URL(string: "http://localhost:8000/@foo")
    var request = URLRequest(url: url!)
    request.addValue(Datestr, forHTTPHeaderField: "date")
    request.addValue("twitter.com", forHTTPHeaderField: "Host")
    request.setValue("hmac username='\(username)', algorithm='hmac-sha1', headers='date', signature='\(hmacAuth)'", forHTTPHeaderField: "Authorization")
    let dataTask = URLSession.shared.dataTask(with: request) {
        (data,response,error) in
        if error != nil {
            print(error!)
        }
        print("DATA RETURNED: \(data!)")
        let str = String(data: data!, encoding: .utf8)
        print("VALUE: \(str!)")
        print("RESPONSE: \(response!)")
    }
    dataTask.resume()
}

enum hmacAlgo {
    case SHA1
    func  toHMACAlgorithm() -> CCHmacAlgorithm {
        var result: Int = 0
        switch self {
        case .SHA1:
            result = kCCHmacAlgSHA1
        }
        return CCHmacAlgorithm(result)
    }

    func digestLength() -> Int {
        var result: CInt = 0
        switch self {
        case .SHA1:
            result = CC_SHA1_DIGEST_LENGTH
        }
        return Int(result)
    }
}

extension String  {
    func getHmac(algorithm: hmacAlgo, key: String) -> String {
        let stringData = self.cString(using: String.Encoding.ascii)
        let keyData = key.cString(using: String.Encoding.ascii)
        var result = [CUnsignedChar](repeating: 0, count: Int(algorithm.digestLength()))
        CCHmac(algorithm.toHMACAlgorithm(), keyData!, Int(strlen(keyData!)), stringData!, Int(strlen(stringData!)), &result)
        let hmacData: NSData = NSData(bytes: result, length: (Int(algorithm.digestLength())))
        let hmacb64 = hmacData.base64EncodedString(options: NSData.Base64EncodingOptions.lineLength76Characters)
        return hmacb64
    }
}

But I get 403 Status Code - Forbidden with message stating HMAC signature cannot be verified

Body:
Solved,

request.setValue("hmac username=\"\(username)\", algorithm=\"hmac-sha1\", headers=\"date\", signature=\"\(hmacAuth)\"", forHTTPHeaderField: "Authorization")

I just wrapped the strings in the authorization header with double quotes and sent the request.
Thank you.


问:
Is it possible to relay access_token from one web api to another in IdentityServer4
Scenario : I have a client, two web apis and IdentityServer4 Token server. Client has both  web apis in his scope and can call them individually. But lets say when client calls one web api and that api needs to call the other by passing access token it received. In coming token is authorized for both services. Is this possible?</p>

答:
UPDATED ANSWER

I just came across Extension Grants which supports non standard token delegation. Check official docs...might be helpful!


问:
Regular expression to extract file name?
I want to remove last three character of filenames.  To rename any files, i'm using:

```<code>String str = ""; // Here set File name, i.e. listFile.getName();
String[] tempFile = str.split("[$^txt]");
</code>```

This regex remove last three character it's OK, but when passing any file name containing "t OR x" the regex remove it. For example:

```<code>1) fileName.txt   -> result after split -> fileName -> OK.
2) textfile.txt   -> result after split -> efile. -> remove any t OR x in file name.
</code>```

My Q is : How i can remove only last three char.

Thank you

答: You could simply just use substring. String.substring is used for this purpose. In your case, you could simply use str.substring(0, str.length - 3) to get everything but the last 3 characters from the string. Besides this, you could use str.split.

Body:
I want to remove last three character of filenames.  To rename any files, i'm using:

String str = ""; // Here set File name, i.e. listFile.getName();
String[] tempFile = str.split("[$^txt]");

This regex remove last three character it's OK, but when passing any file name containing "t OR x" the regex remove it. For example:

1) fileName.txt   -> result after split -> fileName -> OK.
2) textfile.txt   -> result after split -> efile. -> remove any t OR x in file name.

My Q is : How i can remove only last three char.

Thank you


问:
How to reduce the current directory path in Windows command prompt
What is the command to reduce the current path in the windows command prompt?

For example when I work in a subfolder I don't want to see the entire path from the root

I don't want to see:
C:\Users\myuser\AppData\Local\conda\conda\pkgs>
but just:
>
or
pkgs>

答:
while you can't change the command prompt to only show the current directory, you can change it to only be the greater than symbol > by using the following command at the prompt

```<code>prompt = $G
</code>```

for more information you can use the command prompt /? or check https://technet.microsoft.com/en-us/library/bb490977.aspx

Body:
while you can't change the command prompt to only show the current directory, you can change it to only be the greater than symbol > by using the following command at the prompt

prompt = $G

for more information you can use the command prompt /? or check https://technet.microsoft.com/en-us/library/bb490977.aspx


问:
Rails deep nesting with index of parent
I have the following routes

```<code>  resources :continent do
    resources :countries do
        resource :cities do
            resource :streets
        end
    end
  end
</code>```

To select a country I would have to do

```<code>/continents/:continent_id/countries/:country_id
</code>```

and so on.

My question is how can I get all streets for a specific country or continent. Or all countries for a specific continent.

for example is there a way to do

```<code>/continents/:continent_id/countries/cities
</code>```

which will return all cities under :continent_id

答:
You can use the following model relation

```<code>class Country < ActiveRecord::Base
   has_many :streets, :through => : cities
end
</code>```

So, you can use for example in the code

```<code>Country.find(1).streets
</code>```

Title: Rails deep nesting with index of parent

Body:
I have the following routes

  resources :continent do
    resources :countries do
        resource :cities do
            resource :streets
        end
    end
  end

To select a country I would have to do

/continents/:continent_id/countries/:country_id

and so on.

My question is how can I get all streets for a specific country or continent. Or all countries for a specific continent.

for example is there a way to do

/continents/:continent_id/countries/cities

which will return all cities under :continent_id

Body:
You can use the following model relation

class Country < ActiveRecord::Base
   has_many :streets, :through => : cities
end

So, you can use for example in the code

Country.find(1).streets


问:
Duplicating an element of a list back into the list in Python
Copying an element back into the list:

```<code>>> a = [[1,2],[3,4]]
>> b = []
>> b = a[1]
>> a.insert(1,b)
>> a
[[1,2],[3,4],[3,4]]
>> a[2][0] = 0
>> a
???
</code>```

What do you expect list 'a' to be? It comes out to be as [[1,2],[0,4],[0,4]] which was very surprising to me whereas I expected [[1,2],[1,4],[0,4]]

I kind of know the answer but still, the idea is not very clear. Kindly tell in more detail why does this happen and how to get rid of it?

答:
```<code>b = a[1]
a.insert(1,b)
</code>```

b is a reference to a[1] so when you modify the reference after inserting it, it appears in both places since it is essentially pointing to the same data.

if you want to avoid such a scenario, use deepcopy

```<code>from copy import deepcopy

a = [[1,2],[3,4]]
b = []
b = deepcopy(a[1])
a.insert(1,b)
print(a) # prints [[1, 2], [3, 4], [3, 4]]
a[2][0] = 0
print(a) # prints [[1, 2], [3, 4], [0, 4]]
</code>```

Body:
Copying an element back into the list:

>> a = [[1,2],[3,4]]
>> b = []
>> b = a[1]
>> a.insert(1,b)
>> a
[[1,2],[3,4],[3,4]]
>> a[2][0] = 0
>> a
???

What do you expect list 'a' to be? It comes out to be as [[1,2],[0,4],[0,4]] which was very surprising to me whereas I expected [[1,2],[1,4],[0,4]]

I kind of know the answer but still, the idea is not very clear. Kindly tell in more detail why does this happen and how to get rid of it?

Body:
b = a[1]
a.insert(1,b)

b is a reference to a[1] so when you modify the reference after inserting it, it appears in both places since it is essentially pointing to the same data.

if you want to avoid such a scenario, use deepcopy

from copy import deepcopy

a = [[1,2],[3,4]]
b = []
b = deepcopy(a[1])
a.insert(1,b)
print(a) # prints [[1, 2], [3, 4], [3, 4]]
a[2][0] = 0
print(a) # prints [[1, 2], [3, 4], [0, 4]]


问:
Deserialize a JSON from Google Translation API using C#
I'm using Google Translation API to detect a language of a string. The API is returning this JSON:

```<code>{
    "data": {
        "detections": [
            [
                {
                    "confidence": 0.37890625,
                    "isReliable": false,
                    "language": "ro"
                }
            ]
        ]
    }
}
</code>```

I still haven't found the way of deserialize it. I'm using System.Runtime.Serialization and this is my code:

```<code>[DataContract]
public class GoogleTranslationResponse
{
    [DataMember(Name = "data")]
    public Data Data { get; set; }
}
[DataContract]
public class Data
{
    [DataMember(Name = "detections")]
    public List<Detection> Detections { get; set; }
}

[DataContract]
public class Detection
{
    [DataMember(Name = "confidence")]
    public decimal Confidence { get; set; }

    [DataMember(Name = "isReliable")]
    public bool IsReliable { get; set; }

    [DataMember(Name = "language")]
    public string Language { get; set; }
}
// ...
var jsonSerializer = new DataContractJsonSerializer(typeof(GoogleTranslationResponse));
result = (GoogleTranslationResponse)jsonSerializer.ReadObject( new MemoryStream(Encoding.Unicode.GetBytes(responseData)));
</code>```

I'm getting this as a result:

```<code>Confidence: 0
IsReliable:false
Language:null
</code>```

答:
In your JSON, the value of "detections" is a 2d jagged array:

```<code>"detections": [ [  { ... } ] ]
</code>```

Therefore your model needs to reflect this by using nested collections:

```<code>[DataContract]
public class Data
{
    [DataMember(Name = "detections")]
    public List<List<Detection>> Detections { get; set; }
}
</code>```

Body:
I'm using Google Translation API to detect a language of a string. The API is returning this JSON:

{
    "data": {
        "detections": [
            [
                {
                    "confidence": 0.37890625,
                    "isReliable": false,
                    "language": "ro"
                }
            ]
        ]
    }
}

I still haven't found the way of deserialize it. I'm using System.Runtime.Serialization and this is my code:

[DataContract]
public class GoogleTranslationResponse
{
    [DataMember(Name = "data")]
    public Data Data { get; set; }
}
[DataContract]
public class Data
{
    [DataMember(Name = "detections")]
    public List<Detection> Detections { get; set; }
}

[DataContract]
public class Detection
{
    [DataMember(Name = "confidence")]
    public decimal Confidence { get; set; }

    [DataMember(Name = "isReliable")]
    public bool IsReliable { get; set; }

    [DataMember(Name = "language")]
    public string Language { get; set; }
}
// ...
var jsonSerializer = new DataContractJsonSerializer(typeof(GoogleTranslationResponse));
result = (GoogleTranslationResponse)jsonSerializer.ReadObject( new MemoryStream(Encoding.Unicode.GetBytes(responseData)));

I'm getting this as a result:

Confidence: 0
IsReliable:false
Language:null

Body:
In your JSON, the value of "detections" is a 2d jagged array:

"detections": [ [  { ... } ] ]

Therefore your model needs to reflect this by using nested collections:

[DataContract]
public class Data
{
    [DataMember(Name = "detections")]
    public List<List<Detection>> Detections { get; set; }
}


问:
Number of online people in django
I have a website and i want to find number of online users in my website(All of users logged to their account or not):
And when they get offline or close page the number of online users get update:
How can i do that?is there any library to do that?

答:
You can add an is_online BooleanField to your User model and create your own custom authenticate backends for your User model that after authentication sets the is_online to true.

When a user goes to close the web page you can have a event listener to make an Ajax request where you will then set that users is_online column to false in DB and logs the user out.

If you don't want to remove the user from sessions you might need additional logic in other places to turn that attribute to true when they come back to the website.

```<code>// OR
window.addEventListener("beforeunload", function(e){
   // Do something
}, false);
</code>```

You can then find your online users by either doing a model.objects.filter(is_online=True) or you can create a custom method on the Model itself that can contain other business logic and or potentially send a email or something.

Title: Number of online people in django

Body:
You can add an is_online BooleanField to your User model and create your own custom authenticate backends for your User model that after authentication sets the is_online to true.

When a user goes to close the web page you can have a event listener to make an Ajax request where you will then set that users is_online column to false in DB and logs the user out.

If you don't want to remove the user from sessions you might need additional logic in other places to turn that attribute to true when they come back to the website.

// OR
window.addEventListener("beforeunload", function(e){
   // Do something
}, false);

You can then find your online users by either doing a model.objects.filter(is_online=True) or you can create a custom method on the Model itself that can contain other business logic and or potentially send a email or something.


问:
Ignore parent divs width
I have had issues with modify a navigation bar for mobile. I want the navigation bar to ignore its parent div inner-wrapper width of 80% and use a full width of 100%.

The most logical solution I can think of is to set header: relative, width: 100% and header li to absolute with a width of 100%. However, this doesn't seem to work.

I want each navigation to have a full width of the screen rather than a full width of its parent wrapper.

.header {
  background-color: #FFB6C1;
  color: black;
  overflow: hidden;
  position: relative;
}

.inner-wrapper {
  width: 80%;
  margin: 0 auto;
  margin-top: 30px;
  margin-bottom: 20px;
}

.header h2 {
  float: left;
  font-family: 'Pacifico', sans-serif;
  font-size: 30px;
}

.header h3 {
  padding-top: 5px;
  font-family: 'Petit Formal Script';
  clear: both;
  font-weight: 700;
}

.header span {
  font-weight: bolder;
}

.header ul {
  float: right;
  margin-right: 10%
}

.header ul li {
  list-style: none;
  display: inline-block;
  font-family: 'Podkova', sans-serif;
  margin-right: 20px;
  font-weight: bold;
}
/* Navigation Menu click for mobile */

.mobile-menu {
  padding: 0;
  margin: 0;
  display: none;
}
/* Smartphones (portrait) ----------- */

@media only screen and (max-width: 414px) {
  /* Styles */
  /* Display flex to change the ordering of HTML elemtns*/
  .inner-wrapper {
    display: flex;
    flex-direction: column;
    margin-bottom: 0px;
  }
  .header-title {
    order: 1;
  }
  .header-description {
    order: 2;
  }
  .dropdown {
    order: 3;
  }
  .header-li {
    display: none;
    position: absolute;
    width: 100%;
  }
  .header ul {
    float: none;
    margin-right: 0%;
  }
  .mobile-menu {
    padding: 0;
    margin: 0;
    display: initial;
    cursor: pointer;
  }
  .header ul li {
    width: 100%;
    background-color: green;
    padding-top: 20px;
  }
  .header {
    position: relative;
    width: 100%;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- Header and Navigation -->
<div class="header">
  <div class="inner-wrapper">
    <h2 class="header-title">text</h2>
    <div class="dropdown">
      <div class="mobile-menu">
        <p align="right">Menu</p>
      </div>
      <ul class="header-li">
        <li>About me</li>
        <li>Progress</li>
        <li>Food</li>
        <li>Contact</li>
      </ul>
    </div>
    <h3 class="header-description">text</span></h3>
  </div>
</div></code>```

答: If you want the navigation to have full width of the screen use width: 100vw; on the child. That means 100% of the view width

Title: Ignore parent divs width

Body:
I have had issues with modify a navigation bar for mobile. I want the navigation bar to ignore its parent div inner-wrapper width of 80% and use a full width of 100%.

The most logical solution I can think of is to set header: relative, width: 100% and header li to absolute with a width of 100%. However, this doesn't seem to work.

I want each navigation to have a full width of the screen rather than a full width of its parent wrapper.

.header {
  background-color: #FFB6C1;
  color: black;
  overflow: hidden;
  position: relative;
}

.inner-wrapper {
  width: 80%;
  margin: 0 auto;
  margin-top: 30px;
  margin-bottom: 20px;
}

.header h2 {
  float: left;
  font-family: 'Pacifico', sans-serif;
  font-size: 30px;
}

.header h3 {
  padding-top: 5px;
  font-family: 'Petit Formal Script';
  clear: both;
  font-weight: 700;
}

.header span {
  font-weight: bolder;
}

.header ul {
  float: right;
  margin-right: 10%
}

.header ul li {
  list-style: none;
  display: inline-block;
  font-family: 'Podkova', sans-serif;
  margin-right: 20px;
  font-weight: bold;
}
/* Navigation Menu click for mobile */

.mobile-menu {
  padding: 0;
  margin: 0;
  display: none;
}
/* Smartphones (portrait) ----------- */

@media only screen and (max-width: 414px) {
  /* Styles */
  /* Display flex to change the ordering of HTML elemtns*/
  .inner-wrapper {
    display: flex;
    flex-direction: column;
    margin-bottom: 0px;
  }
  .header-title {
    order: 1;
  }
  .header-description {
    order: 2;
  }
  .dropdown {
    order: 3;
  }
  .header-li {
    display: none;
    position: absolute;
    width: 100%;
  }
  .header ul {
    float: none;
    margin-right: 0%;
  }
  .mobile-menu {
    padding: 0;
    margin: 0;
    display: initial;
    cursor: pointer;
  }
  .header ul li {
    width: 100%;
    background-color: green;
    padding-top: 20px;
  }
  .header {
    position: relative;
    width: 100%;
  }
}

text

Menu

About me

Progress

Food

Contact

text


问:
Converting KML to Array in PHP
I've got stuck when i'm trying to convert a *.kml file to array using PHP language.

kml file >> path.kml

code

```<code>    $dom = new \DOMDocument();
    $dom->loadXml($file);
    $xpath = new \DOMXPath($dom);
    $xpath->registerNamespace('kml', 'http://www.opengis.net/kml/2.2');

    $result = array();
    $places = $xpath->evaluate('//kml:Placemark', NULL, FALSE);
    foreach ($places as $place) {
        $coord = $xpath->evaluate('string(kml:LineString/kml:coordinates)',$place, FALSE);
        $i = explode("\n", $coord);
        $result = array(
            'name' => $xpath->evaluate('string(kml:name)', $place, FALSE),
            'coords' => explode("\n", $coord, count($i)
            )
        );
    }

    var_dump($result);
</code>```

the problem is when i'm trying to explode the string using newLine delimeter, and the result is always like this

whereas i want the result like this

could anyone to help me for solve my problem ? Thank You!

Title: Converting KML to Array in PHP

Body:
I've got stuck when i'm trying to convert a *.kml file to array using PHP language.

kml file >> path.kml

code

    $dom = new \DOMDocument();
    $dom->loadXml($file);
    $xpath = new \DOMXPath($dom);
    $xpath->registerNamespace('kml', 'http://www.opengis.net/kml/2.2');

    $result = array();
    $places = $xpath->evaluate('//kml:Placemark', NULL, FALSE);
    foreach ($places as $place) {
        $coord = $xpath->evaluate('string(kml:LineString/kml:coordinates)',$place, FALSE);
        $i = explode("\n", $coord);
        $result = array(
            'name' => $xpath->evaluate('string(kml:name)', $place, FALSE),
            'coords' => explode("\n", $coord, count($i)
            )
        );
    }

    var_dump($result);

the problem is when i'm trying to explode the string using newLine delimeter, and the result is always like this

whereas i want the result like this

could anyone to help me for solve my problem ? Thank You!

Body:
You can trim the coords array:

<?php

function itemTrim(&$item) {
    $item = trim($item);
}

$r = "
     115.09031667,-8.81930500,64.500
     115.09031500,-8.81925667,64.400
     115.09033000,-8.81920167,64.300
     115.09038167,-8.81911333,64.100
     115.09042333,-8.81904000,64.000
     115.09048000,-8.81896833,63.900
     115.09053333,-8.81889167,63.800
     115.09056167,-8.81882333,63.800
     115.09059500,-8.81876667,63.800
     115.09063500,-8.81872500,63.900
     115.09067333,-8.81870167,63.800
    ";

$a = preg_split("/\r\n|\n|\r/", $r);
$b = array_walk($a, "itemTrim");

var_dump($a);

But the considerations on the other answers about the line terminator is true, i used an regular expression from other SO question.


问:
Jupyter: can't create new notebook?
I have some existing Python code that I want to convert to a Jupyter notebook. I have run:

```<code>jupyter notebook
</code>```

Now I can see this in my browser:

But how do I create a new notebook? The Notebook link in the menu is greyed out, and I can't see any other options to create a new notebook.

I've noticed this on the command line while Jupyter is running:

```<code>[W 22:30:08.128 NotebookApp] Native kernel (python2) is not available
</code>```

答:
I was also getting the same error. My error snapshot is here. Following below solved my problem:

sudo apt-get -y install ipython ipython-notebook

sudo -H pip install jupyter

It was not working because I was getting 0 active kernel message and this came because I installed jupyter using step2 only (skipped step1).

Title: Jupyter: can't create new notebook?

Body:
I have some existing Python code that I want to convert to a Jupyter notebook. I have run:

jupyter notebook

Now I can see this in my browser:

But how do I create a new notebook? The Notebook link in the menu is greyed out, and I can't see any other options to create a new notebook.

I've noticed this on the command line while Jupyter is running:

[W 22:30:08.128 NotebookApp] Native kernel (python2) is not available


问:
Searching Xml Document with linq doesn't return anything
I'm trying to learn how to save and extract data with XML in C#, and even though I've read various answers to similar questions on here, I cannot get a hold of why my statement isn't returning anything.
The program I'm writing is just a test, in which I've saved data about a couple movies in the xml document and now I'm trying to retrieve some of them based on their cost.

This is the class that I've written for searching:

```<code> class ExtractData
{
    private XDocument _xdoc;
    public List<string> SearchByCost(double cost)
    {
        _xdoc = XDocument.Load(FileLocation.XmlFileLocation);
        List<string> list = new List<string>();

        var movies = from movie in _xdoc.Root.Elements("Name")
                where Convert.ToDouble(movie.Element("Cost").Value) < cost
                select movie;

        foreach (var item in movies)
        {
            list.Add(item.Value);
        }

        return list;
    }

}
</code>```

This is how I'm trying to make it print it in the console:

```<code>        eData = new ExtractData();
        foreach (var movie in eData.SearchByCost(9))
        {
            Console.WriteLine(movie);
        }
</code>```

And this is the content of the XML document:

```<code><?xml version="1.0" encoding="utf-8"?>
<Movies>
  <Movie>
    <Id>1</Id>
    <Name>Shawshank Redemption</Name>
    <Director>Frank Darabont</Director>
    <Year>1994</Year>
    <Cost>9.95</Cost>
  </Movie>
  <Movie>
    <Id>2</Id>
    <Name>Pulp Fiction</Name>
    <Director>Quentin Tarantino</Director>
    <Year>1995</Year>
    <Cost>8.95</Cost>
  </Movie>
  <Movie>
    <Id>3</Id>
    <Name>Sharknado</Name>
    <Director>Anthony Ferrante</Director>
    <Year>2013</Year>
    <Cost>5.95</Cost>
  </Movie>
</Movies>
</code>```

I hope this is enough information to try and help me out, and thanks in advance! :)

答:
In plain English, you seem to be trying to find movies cheaper than 9 (of some arbitrary currency).

You can write this as:

public IReadOnlyCollection<string> SearchByCost(XDocument xdoc, double cost)
{
    return xdoc.Root.Elements("Movie")
        .Where(movie => (double)movie.Element("Cost") < cost)
        .Select(movie => movie.Element("Name").Value)
        .ToList();
}
```

Body:
I'm trying to learn how to save and extract data with XML in C#, and even though I've read various answers to similar questions on here, I cannot get a hold of why my statement isn't returning anything.
The program I'm writing is just a test, in which I've saved data about a couple movies in the xml document and now I'm trying to retrieve some of them based on their cost.

This is the class that I've written for searching:

 class ExtractData
{
    private XDocument _xdoc;
    public List<string> SearchByCost(double cost)
    {
        _xdoc = XDocument.Load(FileLocation.XmlFileLocation);
        List<string> list = new List<string>();

        var movies = from movie in _xdoc.Root.Elements("Name")
                where Convert.ToDouble(movie.Element("Cost").Value) < cost
                select movie;

        foreach (var item in movies)
        {
            list.Add(item.Value);
        }

        return list;
    }

}

This is how I'm trying to make it print it in the console:

        eData = new ExtractData();
        foreach (var movie in eData.SearchByCost(9))
        {
            Console.WriteLine(movie);
        }

And this is the content of the XML document:

<?xml version="1.0" encoding="utf-8"?>
<Movies>
  <Movie>
    <Id>1</Id>
    <Name>Shawshank Redemption</Name>
    <Director>Frank Darabont</Director>
    <Year>1994</Year>
    <Cost>9.95</Cost>
  </Movie>
  <Movie>
    <Id>2</Id>
    <Name>Pulp Fiction</Name>
    <Director>Quentin Tarantino</Director>
    <Year>1995</Year>
    <Cost>8.95</Cost>
  </Movie>
  <Movie>
    <Id>3</Id>
    <Name>Sharknado</Name>
    <Director>Anthony Ferrante</Director>
    <Year>2013</Year>
    <Cost>5.95</Cost>
  </Movie>
</Movies>

I hope this is enough information to try and help me out, and thanks in advance! :)


问:
injecting a bean as a value to a property of another bean
How would some inject a bean as a value to a property of another bean?

For example

```<code>        public class FileNameGenerator
    {
        private String name;
        private String type;

        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getType() {
            return type;
        }
        public void setType(String type) {
            this.type = type;
        }
    }

<bean id="FileNameGenerator" class="FileNameGenerator">
        <property name="name">
            <value>value1</value>
        </property>
        <property name="type">
            <value>value2</value>
        </property>
    </bean>
</code>```

Instead I am trying to inject a factory method bean in value1

```<code><bean id="FileNameGenerator" class="FileNameGenerator">
                <property name="name">
                    <value>
<bean class="SomeOtherClass" factory-method="staticMethodThatReturnsString">
</value>
                </property>
                <property name="type">
                    <value>value2</value>
                </property>
            </bean>
</code>```

How would I do this?

答:
you need use SpEL :

```<code>   <bean id="FileNameGenerator" class="org....path....FileNameGenerator">
      <property name="name">
         <value>#{T(org....path....SomeOtherClass).staticMethodThatReturnsString()}</value>
      </property>
      <property name="type">
         <value>value2</value>
      </property>
   </bean>
</code>```

us factory-method for getting class that you know in advance , it's bad practice . You know that you need String and you know how to get it from some static method - but method that return String it's not facory. with spel just call that static method for  field name. In your case use factory method it is overuse

Body:
How would some inject a bean as a value to a property of another bean?

For example

        public class FileNameGenerator
    {
        private String name;
        private String type;

        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getType() {
            return type;
        }
        public void setType(String type) {
            this.type = type;
        }
    }

<bean id="FileNameGenerator" class="FileNameGenerator">
        <property name="name">
            <value>value1</value>
        </property>
        <property name="type">
            <value>value2</value>
        </property>
    </bean>

Instead I am trying to inject a factory method bean in value1

<bean id="FileNameGenerator" class="FileNameGenerator">
                <property name="name">
                    <value>
<bean class="SomeOtherClass" factory-method="staticMethodThatReturnsString">
</value>
                </property>
                <property name="type">
                    <value>value2</value>
                </property>
            </bean>

How would I do this?

Body:
you need use SpEL :

   <bean id="FileNameGenerator" class="org....path....FileNameGenerator">
      <property name="name">
         <value>#{T(org....path....SomeOtherClass).staticMethodThatReturnsString()}</value>
      </property>
      <property name="type">
         <value>value2</value>
      </property>
   </bean>

us factory-method for getting class that you know in advance , it's bad practice . You know that you need String and you know how to get it from some static method - but method that return String it's not facory. with spel just call that static method for  field name. In your case use factory method it is overuse


问:
foreign keys without on delete cascade
I have two tables:

```<code>Challenge:

challengeID INTEGER PRIMARY KEY
...
</code>```

And

```<code>UserChallenge:

ID INTEGER  PRIMARY KEY
challengeID INTEGER NOT NULL
...
FOREIGN KEY(challengeid) REFERENCES challenge(challengeID)
</code>```

If I have one row on challenge table, with challengeID = 1, and one row on UserChallenge table with challengeID = 1.

What would happen with UserChallenge table if I delete the row from the Challenge? May I use ON DELETE CASCADE with UserChallenge.challengeID?

Thanks.

答:
With DELETE CASCADE removing a record from Challenge causes all child records in UserChallenge to be deleted.

Maybe this helps: http://en.wikipedia.org/wiki/Foreign_key#Referential_Actions

Title: foreign keys without on delete cascade

Body:
I have two tables:

Challenge:

challengeID INTEGER PRIMARY KEY
...

And

UserChallenge:

ID INTEGER  PRIMARY KEY
challengeID INTEGER NOT NULL
...
FOREIGN KEY(challengeid) REFERENCES challenge(challengeID)

If I have one row on challenge table, with challengeID = 1, and one row on UserChallenge table with challengeID = 1.

What would happen with UserChallenge table if I delete the row from the Challenge? May I use ON DELETE CASCADE with UserChallenge.challengeID?

Thanks.


问:
Change URL by filter
I am using friendly_id so that I can create such URLs:

/search/france/weekly/toyota-95
```

<p>My routes:</p>

<pre class="lang-ruby prettyprint-override"><code>scope to: 'search#show' do
  get '/search/:car_country_id/:rental_type_id/:car_group_id', as: 'search_country'
end
</code>```

At the search#show view I have a form:

<%= form_tag search_country_path, :method => :get do %>
    <%= select_tag(:car_country_id, options_from_collection_for_select(CarCountry.all, :slug, proc {|c| c.name }, {:selected => @country}), class: "Select-control u-sizeFull") %>
    <%= submit_tag t('shared.search'), class: 'btn btn-primary' %>
<% end %>
```

<p>And search controller:</p>

<pre class="lang-ruby prettyprint-override"><code>@country = CarCountry.friendly.find(params[:car_country_id])
</code>```

So ok, my intention is to change the URL as:

/search/italy/weekly/toyota-95
```

But the thing is, Rails params always sending france as car_country_id when I select country from select tag and submit it.

So what should I do?

答:
Currently, two car_country_id are sent to Rails server. You can rename one of them:

<%= select_tag(:new_car_country_id, options_from_collection_for_select(CarCountry.all, :slug, proc {|c| c.name }, {:selected => @country}), class: "Select-control u-sizeFull") %>
```

In your controller, you should check whether new_car_country_id exists. If it does, then redirect to the corresponding path.

Another way is to make sure that the two car_country_id are the same. You should change the form's submit path once select_tag is updated with JavaScript.

Title: Change URL by filter

Body:
I am using friendly_id so that I can create such URLs:

/search/france/weekly/toyota-95

My routes:

scope to: 'search#show' do
  get '/search/:car_country_id/:rental_type_id/:car_group_id', as: 'search_country'
end

At the search#show view I have a form:

<%= form_tag search_country_path, :method => :get do %>
    <%= select_tag(:car_country_id, options_from_collection_for_select(CarCountry.all, :slug, proc {|c| c.name }, {:selected => @country}), class: "Select-control u-sizeFull") %>
    <%= submit_tag t('shared.search'), class: 'btn btn-primary' %>
<% end %>

And search controller:

@country = CarCountry.friendly.find(params[:car_country_id])

So ok, my intention is to change the URL as:

/search/italy/weekly/toyota-95

But the thing is, Rails params always sending france as car_country_id when I select country from select tag and submit it.

So what should I do?

Body:
Currently, two car_country_id are sent to Rails server. You can rename one of them:

<%= select_tag(:new_car_country_id, options_from_collection_for_select(CarCountry.all, :slug, proc {|c| c.name }, {:selected => @country}), class: "Select-control u-sizeFull") %>

In your controller, you should check whether new_car_country_id exists. If it does, then redirect to the corresponding path.

Another way is to make sure that the two car_country_id are the same. You should change the form's submit path once select_tag is updated with JavaScript.


问:
How to print the entire matrix in python?
I am taking a column from a matrix and then trying to create an array that averages the column over different increments. I have written a sample code to show my problem.

```<code>import numpy
import numpy as np
import matplotlib.pyplot as plt

numint = 2
numflo = 2.0

a = numpy.matrix ([[1,2,3],[4,5,6],[7,8,9,],[10,11,12],[13,14,15],[16,17,18]])

b= a[-2*3:,1]

for i in range (0,numint+1,1):
    avg = sum(b[numint*i:numint*(i+1)])/numflo
    print avg
</code>```

when I run this code and I print avg inside the loop I get the following

```<code>[[ 3.5]]
[[ 9.5]]
[[ 15.5]]
</code>```

but if I print avg outside of the loop then I just get

```<code>[[15.5]]
</code>```

This throws the rest of my code off. Why does it not print the entire matrix avg and just only the last number. Any help is appreciated, thanks!

答:
this is because in your for loop your are always updating avg to the average of the last column you averaged.

 In other words, if you want to have the entire averages you can do something like this as a beautiful one liner:

```<code>avg = [sum(b[numint*i:numint*(i+1)])/numflo for i in range(0,numint+1,1)]
</code>```

you can then simply access your values normally like avg[0] etc..

Body:
I am taking a column from a matrix and then trying to create an array that averages the column over different increments. I have written a sample code to show my problem.

import numpy
import numpy as np
import matplotlib.pyplot as plt

numint = 2
numflo = 2.0

a = numpy.matrix ([[1,2,3],[4,5,6],[7,8,9,],[10,11,12],[13,14,15],[16,17,18]])

b= a[-2*3:,1]

for i in range (0,numint+1,1):
    avg = sum(b[numint*i:numint*(i+1)])/numflo
    print avg

when I run this code and I print avg inside the loop I get the following

[[ 3.5]]
[[ 9.5]]
[[ 15.5]]

but if I print avg outside of the loop then I just get

[[15.5]]

This throws the rest of my code off. Why does it not print the entire matrix avg and just only the last number. Any help is appreciated, thanks!

Body:
this is because in your for loop your are always updating avg to the average of the last column you averaged.

 In other words, if you want to have the entire averages you can do something like this as a beautiful one liner:

avg = [sum(b[numint*i:numint*(i+1)])/numflo for i in range(0,numint+1,1)]

you can then simply access your values normally like avg[0] etc..


问:
Application crashes on clicking options
So using Android Studio 2.3.1 I have the most simple app possible, using default settings and choosing a Basic App template. The app gets created just fine, but crashes if you try to click the options button at the top right corner - i.e. the three dots. This is a serious problem...

This is the error:

```<code>04-30 17:51:13.871 13942-13942/com.topository.optionstest01 W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
04-30 17:51:17.987 13942-13942/com.topository.optionstest01 D/AndroidRuntime: Shutting down VM
04-30 17:51:17.988 13942-13942/com.topository.optionstest01 E/AndroidRuntime: FATAL EXCEPTION: main
                                                                              Process: com.topository.optionstest01, PID: 13942
                                                                              java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
                                                                                at android.support.v7.view.menu.ListMenuItemView.setTitle(ListMenuItemView.java:127)
                                                                                at android.support.v7.view.menu.ListMenuItemView.initialize(ListMenuItemView.java:113)
                                                                                at android.support.v7.view.menu.MenuAdapter.getView(MenuAdapter.java:100)
                                                                                at android.support.v7.view.menu.MenuPopup.measureIndividualMenuWidth(MenuPopup.java:160)
                                                                                at android.support.v7.view.menu.StandardMenuPopup.tryShow(StandardMenuPopup.java:153)
                                                                                at android.support.v7.view.menu.StandardMenuPopup.show(StandardMenuPopup.java:187)
                                                                                at android.support.v7.view.menu.MenuPopupHelper.showPopup(MenuPopupHelper.java:290)
                                                                                at android.support.v7.view.menu.MenuPopupHelper.tryShow(MenuPopupHelper.java:175)
                                                                                at android.support.v7.widget.ActionMenuPresenter$OpenOverflowRunnable.run(ActionMenuPresenter.java:803)
                                                                                at android.os.Handler.handleCallback(Handler.java:751)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6121)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
</code>```

Here is my gradle.build file:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    defaultConfig {
        applicationId "com.topository.optionstest01"
        minSdkVersion 23
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:design:25.3.1'
    testCompile 'junit:junit:4.12'
}
</code>```

For completeness:

```<code>import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
</code>```

Here is my menu.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/settings"
        android:orderInCategory="100"
        android:title="Settings"
        android:titleCondensed="The settings"
        app:showAsAction="never"/>

</menu>
</code>```

And the device is a Pixel running 7.1.2

Has anyone else come across this? Any ideas?

答:
I have had the same issue, my app was crashing, and the example basic app from Android Studio was crashing on clicking "options"menu button (with three dots), too.

Crash log:

java.lang.NullPointerException: Attempt to invoke virtual method 'void
  android.widget.TextView.setText(java.lang.CharSequence)' on a null
  object reference
                                                                                at
  android.support.v7.view.menu.ListMenuItemView.setTitle(ListMenuItemView.java:127)
                                                                                at
  android.support.v7.view.menu.ListMenuItemView.initialize(ListMenuItemView.java:113)
                                                                                at
  android.support.v7.view.menu.MenuAdapter.getView(MenuAdapter.java:100)
                                                                                at
  android.support.v7.view.menu.MenuPopup.measureIndividualMenuWidth(MenuPopup.java:160)
                                                                                at
  android.support.v7.view.menu.StandardMenuPopup.tryShow(StandardMenuPopup.java:153)
                                                                                at
  android.support.v7.view.menu.StandardMenuPopup.show(StandardMenuPopup.java:187)
                                                                                at
  android.support.v7.view.menu.MenuPopupHelper.showPopup(MenuPopupHelper.java:290)
                                                                                at
  android.support.v7.view.menu.MenuPopupHelper.tryShow(MenuPopupHelper.java:175)
                                                                                at
  android.support.v7.widget.ActionMenuPresenter$OpenOverflowRunnable.run(ActionMenuPresenter.java:803)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Setup: Android Studio 2.3.1
Gradle 3.3

The solution that I have found was downgrading Gradle plugin from 3.3 down to 2.14.1

1) Replace the plugin version in
top-level build.gradle:

```<code>dependencies {
    //REPLACED 2.3.3->2.2.3(MENU ISSUE)
    //classpath 'com.android.tools.build:gradle:2.3.3'
    classpath 'com.android.tools.build:gradle:2.2.3'
    ...
    }
</code>```

If you use a wrapper
2) delete the /gradle/wrapper/gradle-wrapper.jar

3) replace the contents of
/gradle/wrapper/gradle-wrapper.properties

```<code>distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip
</code>```

build-> clean project -> rebuild project -> the crash when acessing three-dot upper-right corner menu had gone.

ContentLicense: CC BY-SA 4.0

Title: Application crashes on clicking options

Body:
So using Android Studio 2.3.1 I have the most simple app possible, using default settings and choosing a Basic App template. The app gets created just fine, but crashes if you try to click the options button at the top right corner - i.e. the three dots. This is a serious problem...

This is the error:

04-30 17:51:13.871 13942-13942/com.topository.optionstest01 W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
04-30 17:51:17.987 13942-13942/com.topository.optionstest01 D/AndroidRuntime: Shutting down VM
04-30 17:51:17.988 13942-13942/com.topository.optionstest01 E/AndroidRuntime: FATAL EXCEPTION: main
                                                                              Process: com.topository.optionstest01, PID: 13942
                                                                              java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
                                                                                at android.support.v7.view.menu.ListMenuItemView.setTitle(ListMenuItemView.java:127)
                                                                                at android.support.v7.view.menu.ListMenuItemView.initialize(ListMenuItemView.java:113)
                                                                                at android.support.v7.view.menu.MenuAdapter.getView(MenuAdapter.java:100)
                                                                                at android.support.v7.view.menu.MenuPopup.measureIndividualMenuWidth(MenuPopup.java:160)
                                                                                at android.support.v7.view.menu.StandardMenuPopup.tryShow(StandardMenuPopup.java:153)
                                                                                at android.support.v7.view.menu.StandardMenuPopup.show(StandardMenuPopup.java:187)
                                                                                at android.support.v7.view.menu.MenuPopupHelper.showPopup(MenuPopupHelper.java:290)
                                                                                at android.support.v7.view.menu.MenuPopupHelper.tryShow(MenuPopupHelper.java:175)
                                                                                at android.support.v7.widget.ActionMenuPresenter$OpenOverflowRunnable.run(ActionMenuPresenter.java:803)
                                                                                at android.os.Handler.handleCallback(Handler.java:751)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6121)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)

Here is my gradle.build file:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    defaultConfig {
        applicationId "com.topository.optionstest01"
        minSdkVersion 23
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:design:25.3.1'
    testCompile 'junit:junit:4.12'
}

For completeness:

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

Here is my menu.xml:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/settings"
        android:orderInCategory="100"
        android:title="Settings"
        android:titleCondensed="The settings"
        app:showAsAction="never"/>

</menu>

And the device is a Pixel running 7.1.2

Has anyone else come across this? Any ideas?

Body:
I have had the same issue, my app was crashing, and the example basic app from Android Studio was crashing on clicking "options"menu button (with three dots), too.

Crash log:

java.lang.NullPointerException: Attempt to invoke virtual method 'void
  android.widget.TextView.setText(java.lang.CharSequence)' on a null
  object reference
                                                                                at
  android.support.v7.view.menu.ListMenuItemView.setTitle(ListMenuItemView.java:127)
                                                                                at
  android.support.v7.view.menu.ListMenuItemView.initialize(ListMenuItemView.java:113)
                                                                                at
  android.support.v7.view.menu.MenuAdapter.getView(MenuAdapter.java:100)
                                                                                at
  android.support.v7.view.menu.MenuPopup.measureIndividualMenuWidth(MenuPopup.java:160)
                                                                                at
  android.support.v7.view.menu.StandardMenuPopup.tryShow(StandardMenuPopup.java:153)
                                                                                at
  android.support.v7.view.menu.StandardMenuPopup.show(StandardMenuPopup.java:187)
                                                                                at
  android.support.v7.view.menu.MenuPopupHelper.showPopup(MenuPopupHelper.java:290)
                                                                                at
  android.support.v7.view.menu.MenuPopupHelper.tryShow(MenuPopupHelper.java:175)
                                                                                at
  android.support.v7.widget.ActionMenuPresenter$OpenOverflowRunnable.run(ActionMenuPresenter.java:803)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Setup: Android Studio 2.3.1
Gradle 3.3

The solution that I have found was downgrading Gradle plugin from 3.3 down to 2.14.1

1) Replace the plugin version in
top-level build.gradle:

dependencies {
    //REPLACED 2.3.3->2.2.3(MENU ISSUE)
    //classpath 'com.android.tools.build:gradle:2.3.3'
    classpath 'com.android.tools.build:gradle:2.2.3'
    ...
    }

If you use a wrapper
2) delete the /gradle/wrapper/gradle-wrapper.jar

3) replace the contents of
/gradle/wrapper/gradle-wrapper.properties

distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip

build-> clean project -> rebuild project -> the crash when acessing three-dot upper-right corner menu had gone.


答:
Try </p>

```<code>avg_list = []
for i in range (0,numint+1,1):
    avg = sum(b[numint*i:numint*(i+1)])/numflo
    avg_list.append(avg)

print (avg_list)
</code>```

Title: How to print the entire matrix in python?

Body:
Try

avg_list = []
for i in range (0,numint+1,1):
    avg = sum(b[numint*i:numint*(i+1)])/numflo
    avg_list.append(avg)

print (avg_list)


问:
variable of Class not being recognized in the function for Angular 2 typescript with GoJS
I have an application which uses:

Angular 2

GoJS for visualization

It consists of:

Parent Component: src/app/search.component.ts

it consists of a search bar and some area where a API call to the server will manifest buttons.

Child Component: src/app/search-details.component.ts

it consists of a
 which manifests the GoJS Radial Layout Diagram

within the SearchDetailsComponent class of the child component there is a simple function called nodeClicked which is as follows:

```<code>nodeClicked(e, node) {
  // show the name of the clicked node on the console
  console.log(node.data.text);
  this.checkString = node.data.text // HERE is the ERROR....
}
</code>```

Every time the Diagram is rendered and the user clicks on any node, an error occurs stating:

TypeError: this is undefined

```<code>Stack-Trace:
execute/SearchDetailsComponent</SearchDetailsComponent.prototype.nodeClicked@http://run.plnkr.co/L7H44HHRrMceJAkj/src/app/search-details.component.ts!transpiled:96:21
Vh@https://unpkg.com/gojs/release/go-debug.js:539:43
Vg.prototype.standardMouseClick@https://unpkg.com/gojs/release/go-debug.js:537:201
ek.prototype.doMouseUp@https://unpkg.com/gojs/release/go-debug.js:667:73
E.prototype.doMouseUp@https://unpkg.com/gojs/release/go-debug.js:802:92
Ll/a.no@https://unpkg.com/gojs/release/go-debug.js:1012:149
ZoneDelegate.prototype.invokeTask@https://unpkg.com/zone.js/dist/zone.js:424:17
onInvokeTask@https://unpkg.com/@angular/core/bundles/core.umd.js:3956:28
ZoneDelegate.prototype.invokeTask@https://unpkg.com/zone.js/dist/zone.js:423:17
Zone.prototype.runTask@https://unpkg.com/zone.js/dist/zone.js:191:28
ZoneTask/this.invoke@https://unpkg.com/zone.js/dist/zone.js:486:28
</code>```

the this it is referring to is that of the checkString variable declares in the class SearchDetailsComponent.

How is the checkString not recognized? I have defined it above. This error keeps showing up with a API service I wish to call every time the node is clicked and a HTTP GET is called too.

What am I doing wrong here?

Live Plunker

Embed Plunker

答:
The Node.click property is a function that will be called without binding this.

You could certainly specify a nodeClicked function that was a closure, if you need access to the outer component from within the event handler.

Body:
I have an application which uses:

Angular 2

GoJS for visualization

It consists of:

Parent Component: src/app/search.component.ts

it consists of a search bar and some area where a API call to the server will manifest buttons.

Child Component: src/app/search-details.component.ts

it consists of a
 which manifests the GoJS Radial Layout Diagram

within the SearchDetailsComponent class of the child component there is a simple function called nodeClicked which is as follows:

nodeClicked(e, node) {
  // show the name of the clicked node on the console
  console.log(node.data.text);
  this.checkString = node.data.text // HERE is the ERROR....
}

Every time the Diagram is rendered and the user clicks on any node, an error occurs stating:

TypeError: this is undefined

Stack-Trace:
execute/SearchDetailsComponent</SearchDetailsComponent.prototype.nodeClicked@http://run.plnkr.co/L7H44HHRrMceJAkj/src/app/search-details.component.ts!transpiled:96:21
Vh@https://unpkg.com/gojs/release/go-debug.js:539:43
Vg.prototype.standardMouseClick@https://unpkg.com/gojs/release/go-debug.js:537:201
ek.prototype.doMouseUp@https://unpkg.com/gojs/release/go-debug.js:667:73
E.prototype.doMouseUp@https://unpkg.com/gojs/release/go-debug.js:802:92
Ll/a.no@https://unpkg.com/gojs/release/go-debug.js:1012:149
ZoneDelegate.prototype.invokeTask@https://unpkg.com/zone.js/dist/zone.js:424:17
onInvokeTask@https://unpkg.com/@angular/core/bundles/core.umd.js:3956:28
ZoneDelegate.prototype.invokeTask@https://unpkg.com/zone.js/dist/zone.js:423:17
Zone.prototype.runTask@https://unpkg.com/zone.js/dist/zone.js:191:28
ZoneTask/this.invoke@https://unpkg.com/zone.js/dist/zone.js:486:28

the this it is referring to is that of the checkString variable declares in the class SearchDetailsComponent.

How is the checkString not recognized? I have defined it above. This error keeps showing up with a API service I wish to call every time the node is clicked and a HTTP GET is called too.

What am I doing wrong here?

Live Plunker

Embed Plunker


答:
The reason is because of the way lists work in python, they have what is known as "linked data". If you have an instance pointing to an object in a list, and then modify that object, it will be modified in the list too because the list simply points to the object(s). So:

```<code>x = [1,2]
b = [1,3]
x[0] = b
b[0] = 2
</code>```

Then printing x would give [[2,3],2] not [[1,3],2].

What's happening in your situation is that you set the object at position 1 of a to be a pointer/variable b. Then you inserted that pointer at position 2 of a. So when you modify position 2 of a, you also modify b, and thus modify position 1 of a.

Title: Duplicating an element of a list back into the list in Python

Body:
Copying an element back into the list:

>> a = [[1,2],[3,4]]
>> b = []
>> b = a[1]
>> a.insert(1,b)
>> a
[[1,2],[3,4],[3,4]]
>> a[2][0] = 0
>> a
???

What do you expect list 'a' to be? It comes out to be as [[1,2],[0,4],[0,4]] which was very surprising to me whereas I expected [[1,2],[1,4],[0,4]]

I kind of know the answer but still, the idea is not very clear. Kindly tell in more detail why does this happen and how to get rid of it?

Body:
The reason is because of the way lists work in python, they have what is known as "linked data". If you have an instance pointing to an object in a list, and then modify that object, it will be modified in the list too because the list simply points to the object(s). So:

x = [1,2]
b = [1,3]
x[0] = b
b[0] = 2

Then printing x would give [[2,3],2] not [[1,3],2].

What's happening in your situation is that you set the object at position 1 of a to be a pointer/variable b. Then you inserted that pointer at position 2 of a. So when you modify position 2 of a, you also modify b, and thus modify position 1 of a.


问:
Post-build commits: good or bad?
Is it a good policy to automate source control commits following successful builds?

Edit: I'm asking because I want more frequent, incremental commits between versions that make it easier to find the point where a bug was introduced than rolling back 2K+ new lines of code between v1.0 and v1.1.

答:
No. Where would the meaningful commit messages come from? And the references to issue tracker items? How is the automated process supposed to know that a particular bit of work is complete?

With such a process in place, your repository would degrade to a glorified IDE undo buffer.

Title: Post-build commits: good or bad?