问:
I can't seem to define a variable to the value of a form
Hello fellow programmers, i'm trying to make a website that makes a route description, but I can't assign a variable to the input form.
I am trying to assign the variable "Bval" (B value) To the green select form, and "Aval" (A value) To the blue select form. Could anyone point out the issue in this code?

$(document).ready(function() {

  $('#selectroomA').change(function() {
   Aval = $('#selectroomA').value;
  });

 $('#selectroomB').change(function() {
  Bval = $('#selectroomB').value;
 });

 $('#submit').click(function() {
      console.log('clicked');
  if (Aval === "a001") {
            console.log('Aval = a001');
   if (Bval === "a001") {
              console.log('Bval = a001');
     alert('Je bent al in de A001');
   }
  } else {
          console.log('error with if statements');
        }
 });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  margin: 0px;
  padding: 0px;
  font-family: Roboto;
}

.map-box {
  width: 600px;
  height: 300px;
  background: lightgrey;
  overflow: scroll;
}
.svg-container {
  width: 80%;
  margin-left: 10%;
  margin-right: 10%;
  overflow: scroll;
  background: lightgrey;
}
.material-icons {
  font-family: 'Material Icons';
  font-weight: normal;
  font-style: normal;
  font-size: 1px;  /* Preferred icon size */
  display: inline-block;
  line-height: 1;
  text-transform: none;
  letter-spacing: normal;
  word-wrap: normal;
  white-space: nowrap;
  direction: ltr;
  /* Support for all WebKit browsers. */
  -webkit-font-smoothing: antialiased;
  /* Support for Safari and Chrome. */
  text-rendering: optimizeLegibility;
  /* Support for Firefox. */
  -moz-osx-font-smoothing: grayscale;
  /* Support for IE. */
  font-feature-settings: 'liga';
}

/* Buildings */
#building {
  transition: 0.4s fill ease-in-out;
}
.building-a {
  height: 180px;
  width: 120px;
  fill: #455a64;
}
.building-a1 {
  height: 180px;
  width: 120px;
  fill: #1976D2;
}
.building-a2 {
  height: 180px;
  width: 120px;
  fill: #388E3C;
}
#a0 {
  opacity: 1;
}
#a1 {
  opacity: 0;
  transition: 0.4s opacity ease-in-out;
}
#a2 {
  opacity: 0;
  transition: 0.4s opacity ease-in-out;
}

/* Rooms */
#room {
  fill: #607d8b;
  transition: 0.4s fill ease-in-out;
}

/* Paths */
#generalpath {
  fill: white;
}
.path {
  transition: 0.3s opacity ease-in-out;
}
#a0path1, #a0path2, #a0path3, #a001pathty, #a002path, #a003path, #a004path, #a0stairpath {
  fill: #F44336;
  opacity: 0;
}

/* Form */
fieldset {
  border: none;
}
select {
  font-family: Roboto;
  background: white;
  color: black;
  padding: 5px;
  margin: 5px;
  border: none;
  border-radius: 2px;
  cursor: pointer;
}
button {
  margin-top: 12px;
}
#selectroomA {
  background: #40C4FF;
}
#selectroomB {
  background: #00E676;
}

/* Buttons */
.buttons {
  display: block;
}
.upButton, .downButton {
  font-family: Roboto;
  background: #EEE;
  color: black;
  transition: 0.4s all ease-in-out;
  border-radius: 2px;
  text-align: center;
  width: 30px;
  height: 30px;
  margin-top: 5px;
  margin-left: 5px;
  cursor: pointer;
  float: right;
}
.upButton, .downButton:hover {
  box-shadow: 2px 2px 6px #37474F;
  background-color: white;
}
#button i {
  margin-top: 4px;
  font-size: 22px;
}
.disabled {
  font-family: Roboto;
  background: #CCC;
  color: grey;
  transition: 0.4s all ease-in-out;
  border-radius: 2px;
  text-align: center;
  width: 30px;
  height: 30px;
  margin-top: 5px;
  margin-left: 5px;
  cursor: default;
  float: right;
}
/* Toolbar */
#toolbartop {
  width: 77%;
  padding-top: 10px;
  padding-left: 2%;
  padding-right: 1%;
  margin-left: 10%;
  margin-right: 7%;
  background-color: #607D8B;
  color: white;
}
.selection {
  display: block;
  padding-right: 10px;
  white-space: nowrap;
}
.selection select {
  vertical-align: middle;
  margin-left: 10px;
}
#A {
  float: left;
}
#B {
  float: left;
}
#submit {
  width: 77%;
  height: 30px;
  padding-top: 10px;
  padding-left: 2%;
  padding-right: 1%;
  margin-left: 10%;
  margin-right: 7%;
  background-color: #455A64;
  color: white;
  text-align: center;
  cursor: pointer;
  transition: 0.4s background-color ease-in-out;
}
#submit:hover {
  background-color: #546E7A;
}</code>```

    <link rel="stylesheet" type="text/css" href="style.css">
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">

      <form method="post">

          <fieldset class="ui-field-contain">

              <select name="selectroomA" id="selectroomA">
                <option value="null">Selecteer startpunt</option>
                <optgroup label="A-gebouw">
                  <option value="a001">A001</option>
                  <option value="a002">A002</option>
                  <option value="a003">A003</option>
                  <option value="a004">A004</option>
                  <option value="a005">A005</option>
                </optgroup>
              </select>

            <select name="selectroomB" id="selectroomB">
              <option value="null">Selecteer bestemming</option>
              <optgroup label="A-gebouw">
                <option value="a001">A001</option>
                <option value="a002">A002</option>
                <option value="a003">A003</option>
                <option value="a004">A004</option>
                <option value="a005">A005</option>
              </optgroup>
            </select>

          </fieldset>

      </form>

arrow_upward

arrow_downward

Maak route

    <svg class="map-box" xmlns="http://www.w3.org/2000/svg">
      <g id="a0">

        <g class="staircase">
          <rect x='160px' y='16px' height='35px' width='26px' id="building" fill="#455a64" />
          <rect x='175px' y='40px' height='10px' width='11px' fill="#2196f3"/>

          <rect x='175px' y='39px' height='4px' width='11px' fill="#2196f3"/>
          <rect x='175px' y='33px' height='4px' width='11px' fill="#2994E7"/>
          <rect x='175px' y='27px' height='4px' width='11px' fill="#368DCF"/>
          <rect x='160px' y='16px' height='9px' width='26px' fill="#3E8AC2"/>
          <rect x='160px' y='27px' height='4px' width='11px' fill="#4B85AE"/>
          <rect x='160px' y='33px' height='4px' width='11px' fill="#5A7F95"/>
          <rect x='160px' y='39px' height='4px' width='11px' fill="#607D8B"/>
        </g>

        <rect x='130px' y='50px' class="building-a" id="building"/>
        <rect x='330px' y='50px' class="building-a" id="building"/>

        <rect x='213px' y='200px' width="35px" height="30px" id="room" class="a001"/>

        <rect x='130px' y='110px' width="30px" height="57px" id="room" class="a002"/>

        <rect x='130px' y='50px' width="30px" height="57px" id="room" class="a003"/>

        <rect x='130px' y='170px' width="30px" height="50px" id="room" class="a004"/>
        <rect x='130px' y='200px' width="80px" height="30px" id="room" class="a004"/>

        <rect x='185px' y='50px' width="25px" height="40px" id="room" class="a007"/>

        <rect x='164px' y='179px' width="85px" height="17px" id="generalpath"/>
        <rect x='164px' y='50px' width="17px" height="137px" id="generalpath"/>

        <rect x='169px' y='185px' width="65px" height="7px" id="a0path1" class="path"/>
        <rect x='169px' y='135px' width="7px" height="50px" id="a0path2" class="path"/>
        <rect x='169px' y='75px' width="7px" height="60px" id="a0path3" class="path"/>

        <rect x='228px' y='185px' width="7px" height="15px" id="a001path" class="path"/>
        <rect x='160px' y='135px' width="15px" height="7px" id="a002path" class="path"/>
        <rect x='160px' y='75px' width="15px" height="7px" id="a003path" class="path"/>
        <rect x='160px' y='185px' width="15px" height="7px" id="a004path" class="path"/>

        <rect x='169px' y='50px' width="7px" height="60px" id="a0stairpath" class="path"/>
        <rect x='163px' y='18px' width="5" height="32px" id="a0stairpath" class="path"/>
        <rect x='163px' y='18px' width="16" height="5px" id="a0stairpath" class="path"/>
        <rect x='178px' y='18px' width="5" height="32px" id="a0stairpath" class="path"/>
      </g>

      <g id="a1">

        <rect x='160px' y='16px' height='35px' width='11px' id="building" fill="#1976D2"/>
        <rect x='160px' y='16px' height='10px' width='26px' id="building" fill="#1976D2"/>
        <rect x='175px' y='16px' height='35px' width='11px' id="building" fill="#1976D2"/>
        <rect x='175px' y='40px' height='10px' width='11px' fill="#4CAF50"/>

        <rect x='175px' y='39px' height='4px' width='11px' fill="#4CAF50"/>
        <rect x='175px' y='33px' height='4px' width='11px' fill="#41A977"/>
        <rect x='175px' y='27px' height='4px' width='11px' fill="#3DA788"/>
        <rect x='160px' y='16px' height='9px' width='26px' fill="#36A2A5"/>
        <rect x='160px' y='27px' height='4px' width='11px' fill="#2E9EBE"/>
        <rect x='160px' y='33px' height='4px' width='11px' fill="#279AD9"/>
        <rect x='160px' y='39px' height='4px' width='11px' fill="#2196F3"/>

        <rect x='130px' y='50px' class="building-a1" id="building"/>

      </g>

      <g id="a2">
        <rect x='130px' y='50px' class="building-a2" id="building"/>
      </g>
    </svg>

```

Does anyone know what i did wrong? If so thanks in advance.

答:
$(document).ready(function() {

  $('#selectroomA').change(function() {
   Aval = $(this).val();
  });

 $('#selectroomB').change(function() {
  Bval = $(this).val();
 });

 $('#submit').click(function() {
      console.log('clicked');
  if (Aval === "a001") {
            console.log('Aval = a001');
   if (Bval === "a001") {
              console.log('Bval = a001');
     alert('Je bent al in de A001');
   }
  } else {
          console.log('error with if statements');
        }
 });
});```

Body:
Hello fellow programmers, i'm trying to make a website that makes a route description, but I can't assign a variable to the input form.
I am trying to assign the variable "Bval" (B value) To the green select form, and "Aval" (A value) To the blue select form. Could anyone point out the issue in this code?

$(document).ready(function() {

  $('#selectroomA').change(function() {
   Aval = $('#selectroomA').value;
  });

 $('#selectroomB').change(function() {
  Bval = $('#selectroomB').value;
 });

 $('#submit').click(function() {
      console.log('clicked');
  if (Aval === "a001") {
            console.log('Aval = a001');
   if (Bval === "a001") {
              console.log('Bval = a001');
     alert('Je bent al in de A001');
   }
  } else {
          console.log('error with if statements');
        }
 });
});

body {
  margin: 0px;
  padding: 0px;
  font-family: Roboto;
}

.map-box {
  width: 600px;
  height: 300px;
  background: lightgrey;
  overflow: scroll;
}
.svg-container {
  width: 80%;
  margin-left: 10%;
  margin-right: 10%;
  overflow: scroll;
  background: lightgrey;
}
.material-icons {
  font-family: 'Material Icons';
  font-weight: normal;
  font-style: normal;
  font-size: 1px;  /* Preferred icon size */
  display: inline-block;
  line-height: 1;
  text-transform: none;
  letter-spacing: normal;
  word-wrap: normal;
  white-space: nowrap;
  direction: ltr;
  /* Support for all WebKit browsers. */
  -webkit-font-smoothing: antialiased;
  /* Support for Safari and Chrome. */
  text-rendering: optimizeLegibility;
  /* Support for Firefox. */
  -moz-osx-font-smoothing: grayscale;
  /* Support for IE. */
  font-feature-settings: 'liga';
}

/* Buildings */
#building {
  transition: 0.4s fill ease-in-out;
}
.building-a {
  height: 180px;
  width: 120px;
  fill: #455a64;
}
.building-a1 {
  height: 180px;
  width: 120px;
  fill: #1976D2;
}
.building-a2 {
  height: 180px;
  width: 120px;
  fill: #388E3C;
}
#a0 {
  opacity: 1;
}
#a1 {
  opacity: 0;
  transition: 0.4s opacity ease-in-out;
}
#a2 {
  opacity: 0;
  transition: 0.4s opacity ease-in-out;
}

/* Rooms */
#room {
  fill: #607d8b;
  transition: 0.4s fill ease-in-out;
}

/* Paths */
#generalpath {
  fill: white;
}
.path {
  transition: 0.3s opacity ease-in-out;
}
#a0path1, #a0path2, #a0path3, #a001pathty, #a002path, #a003path, #a004path, #a0stairpath {
  fill: #F44336;
  opacity: 0;
}

/* Form */
fieldset {
  border: none;
}
select {
  font-family: Roboto;
  background: white;
  color: black;
  padding: 5px;
  margin: 5px;
  border: none;
  border-radius: 2px;
  cursor: pointer;
}
button {
  margin-top: 12px;
}
#selectroomA {
  background: #40C4FF;
}
#selectroomB {
  background: #00E676;
}

/* Buttons */
.buttons {
  display: block;
}
.upButton, .downButton {
  font-family: Roboto;
  background: #EEE;
  color: black;
  transition: 0.4s all ease-in-out;
  border-radius: 2px;
  text-align: center;
  width: 30px;
  height: 30px;
  margin-top: 5px;
  margin-left: 5px;
  cursor: pointer;
  float: right;
}
.upButton, .downButton:hover {
  box-shadow: 2px 2px 6px #37474F;
  background-color: white;
}
#button i {
  margin-top: 4px;
  font-size: 22px;
}
.disabled {
  font-family: Roboto;
  background: #CCC;
  color: grey;
  transition: 0.4s all ease-in-out;
  border-radius: 2px;
  text-align: center;
  width: 30px;
  height: 30px;
  margin-top: 5px;
  margin-left: 5px;
  cursor: default;
  float: right;
}
/* Toolbar */
#toolbartop {
  width: 77%;
  padding-top: 10px;
  padding-left: 2%;
  padding-right: 1%;
  margin-left: 10%;
  margin-right: 7%;
  background-color: #607D8B;
  color: white;
}
.selection {
  display: block;
  padding-right: 10px;
  white-space: nowrap;
}
.selection select {
  vertical-align: middle;
  margin-left: 10px;
}
#A {
  float: left;
}
#B {
  float: left;
}
#submit {
  width: 77%;
  height: 30px;
  padding-top: 10px;
  padding-left: 2%;
  padding-right: 1%;
  margin-left: 10%;
  margin-right: 7%;
  background-color: #455A64;
  color: white;
  text-align: center;
  cursor: pointer;
  transition: 0.4s background-color ease-in-out;
}
#submit:hover {
  background-color: #546E7A;
}

    <link rel="stylesheet" type="text/css" href="style.css">
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">

      <form method="post">

          <fieldset class="ui-field-contain">

              <select name="selectroomA" id="selectroomA">
                <option value="null">Selecteer startpunt</option>
                <optgroup label="A-gebouw">
                  <option value="a001">A001</option>
                  <option value="a002">A002</option>
                  <option value="a003">A003</option>
                  <option value="a004">A004</option>
                  <option value="a005">A005</option>
                </optgroup>
              </select>

            <select name="selectroomB" id="selectroomB">
              <option value="null">Selecteer bestemming</option>
              <optgroup label="A-gebouw">
                <option value="a001">A001</option>
                <option value="a002">A002</option>
                <option value="a003">A003</option>
                <option value="a004">A004</option>
                <option value="a005">A005</option>
              </optgroup>
            </select>

          </fieldset>

      </form>

arrow_upward

arrow_downward

Maak route

    <svg class="map-box" xmlns="http://www.w3.org/2000/svg">
      <g id="a0">

        <g class="staircase">
          <rect x='160px' y='16px' height='35px' width='26px' id="building" fill="#455a64" />
          <rect x='175px' y='40px' height='10px' width='11px' fill="#2196f3"/>

          <rect x='175px' y='39px' height='4px' width='11px' fill="#2196f3"/>
          <rect x='175px' y='33px' height='4px' width='11px' fill="#2994E7"/>
          <rect x='175px' y='27px' height='4px' width='11px' fill="#368DCF"/>
          <rect x='160px' y='16px' height='9px' width='26px' fill="#3E8AC2"/>
          <rect x='160px' y='27px' height='4px' width='11px' fill="#4B85AE"/>
          <rect x='160px' y='33px' height='4px' width='11px' fill="#5A7F95"/>
          <rect x='160px' y='39px' height='4px' width='11px' fill="#607D8B"/>
        </g>

        <rect x='130px' y='50px' class="building-a" id="building"/>
        <rect x='330px' y='50px' class="building-a" id="building"/>

        <rect x='213px' y='200px' width="35px" height="30px" id="room" class="a001"/>

        <rect x='130px' y='110px' width="30px" height="57px" id="room" class="a002"/>

        <rect x='130px' y='50px' width="30px" height="57px" id="room" class="a003"/>

        <rect x='130px' y='170px' width="30px" height="50px" id="room" class="a004"/>
        <rect x='130px' y='200px' width="80px" height="30px" id="room" class="a004"/>

        <rect x='185px' y='50px' width="25px" height="40px" id="room" class="a007"/>

        <rect x='164px' y='179px' width="85px" height="17px" id="generalpath"/>
        <rect x='164px' y='50px' width="17px" height="137px" id="generalpath"/>

        <rect x='169px' y='185px' width="65px" height="7px" id="a0path1" class="path"/>
        <rect x='169px' y='135px' width="7px" height="50px" id="a0path2" class="path"/>
        <rect x='169px' y='75px' width="7px" height="60px" id="a0path3" class="path"/>

        <rect x='228px' y='185px' width="7px" height="15px" id="a001path" class="path"/>
        <rect x='160px' y='135px' width="15px" height="7px" id="a002path" class="path"/>
        <rect x='160px' y='75px' width="15px" height="7px" id="a003path" class="path"/>
        <rect x='160px' y='185px' width="15px" height="7px" id="a004path" class="path"/>

        <rect x='169px' y='50px' width="7px" height="60px" id="a0stairpath" class="path"/>
        <rect x='163px' y='18px' width="5" height="32px" id="a0stairpath" class="path"/>
        <rect x='163px' y='18px' width="16" height="5px" id="a0stairpath" class="path"/>
        <rect x='178px' y='18px' width="5" height="32px" id="a0stairpath" class="path"/>
      </g>

      <g id="a1">

        <rect x='160px' y='16px' height='35px' width='11px' id="building" fill="#1976D2"/>
        <rect x='160px' y='16px' height='10px' width='26px' id="building" fill="#1976D2"/>
        <rect x='175px' y='16px' height='35px' width='11px' id="building" fill="#1976D2"/>
        <rect x='175px' y='40px' height='10px' width='11px' fill="#4CAF50"/>

        <rect x='175px' y='39px' height='4px' width='11px' fill="#4CAF50"/>
        <rect x='175px' y='33px' height='4px' width='11px' fill="#41A977"/>
        <rect x='175px' y='27px' height='4px' width='11px' fill="#3DA788"/>
        <rect x='160px' y='16px' height='9px' width='26px' fill="#36A2A5"/>
        <rect x='160px' y='27px' height='4px' width='11px' fill="#2E9EBE"/>
        <rect x='160px' y='33px' height='4px' width='11px' fill="#279AD9"/>
        <rect x='160px' y='39px' height='4px' width='11px' fill="#2196F3"/>

        <rect x='130px' y='50px' class="building-a1" id="building"/>

      </g>

      <g id="a2">
        <rect x='130px' y='50px' class="building-a2" id="building"/>
      </g>
    </svg>

Does anyone know what i did wrong? If so thanks in advance.


来源: stackexchange

问:
How to group connected documents (nodes of graph ) from mongodb
Assume that I have a one-way graph with nodes A,B,C,D,E such that

A->B->C is a connected component,

D->E is another connected component.

Nodes are saved in MongoDB as documents

```<code>{name:'A', child: 'B'}, {name:'B', child: 'C'}, {name:'C'},
{name:'D', child: 'E'}, {name:'E'}
</code>```

How to get all connected components?

Expected result: 2 groups

```<code>[{name:'A'...},{name:'B'...}, {name:'C'...}],[{name:'D'...}, {name:'E'...}]
</code>```

答:
Use $graphLookup pipeline stage.

$group - collects all possible values from the name and child fields.

$addFields - generates the array with name field values of the root documents.

$unwind - splits roots array into seperated documents.

$graphLookup - collects related documents by given name field value of the root document.

$project - removes the not necessary fieldss from the result documents.

Query:

```<code>db.getCollection('t').aggregate([
    {
        $group: {
            _id: null,
            names: { $addToSet: "$name" },
            childs: { $addToSet: "$child" }
        }
    },
    {
        $addFields: {
            roots: { $setDifference: ["$names", "$childs"] }
        }
    },
    { $unwind: "$roots" },
    {
        $graphLookup: {
            from: "t",
            startWith: "$roots",
            connectFromField: "child",
            connectToField: "name",
            as: "related"
        }
    },
    {
        $project: {
            "related": 1,
            "_id": 0
        }
    }
])
</code>```

Result:

```<code>/* 1 */
{
    "related" : [
        {
            "_id" : ObjectId("5a29316a545eb40950c33bc8"),
            "name" : "C"
        },
        {
            "_id" : ObjectId("5a29316a545eb40950c33bc7"),
            "name" : "B",
            "child" : "C"
        },
        {
            "_id" : ObjectId("5a29316a545eb40950c33bc6"),
            "name" : "A",
            "child" : "B"
        }
    ]
}

/* 2 */
{
    "related" : [
        {
            "_id" : ObjectId("5a29316a545eb40950c33bca"),
            "name" : "E"
        },
        {
            "_id" : ObjectId("5a29316a545eb40950c33bc9"),
            "name" : "D",
            "child" : "E"
        }
    ]
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Assume that I have a one-way graph with nodes A,B,C,D,E such that

A->B->C is a connected component,

D->E is another connected component.

Nodes are saved in MongoDB as documents

{name:'A', child: 'B'}, {name:'B', child: 'C'}, {name:'C'},
{name:'D', child: 'E'}, {name:'E'}

How to get all connected components?

Expected result: 2 groups

[{name:'A'...},{name:'B'...}, {name:'C'...}],[{name:'D'...}, {name:'E'...}]

Body:
Use $graphLookup pipeline stage.

$group - collects all possible values from the name and child fields.

$addFields - generates the array with name field values of the root documents.

$unwind - splits roots array into seperated documents.

$graphLookup - collects related documents by given name field value of the root document.

$project - removes the not necessary fieldss from the result documents.

Query:

db.getCollection('t').aggregate([
    {
        $group: {
            _id: null,
            names: { $addToSet: "$name" },
            childs: { $addToSet: "$child" }
        }
    },
    {
        $addFields: {
            roots: { $setDifference: ["$names", "$childs"] }
        }
    },
    { $unwind: "$roots" },
    {
        $graphLookup: {
            from: "t",
            startWith: "$roots",
            connectFromField: "child",
            connectToField: "name",
            as: "related"
        }
    },
    {
        $project: {
            "related": 1,
            "_id": 0
        }
    }
])

Result:

/* 1 */
{
    "related" : [
        {
            "_id" : ObjectId("5a29316a545eb40950c33bc8"),
            "name" : "C"
        },
        {
            "_id" : ObjectId("5a29316a545eb40950c33bc7"),
            "name" : "B",
            "child" : "C"
        },
        {
            "_id" : ObjectId("5a29316a545eb40950c33bc6"),
            "name" : "A",
            "child" : "B"
        }
    ]
}

/* 2 */
{
    "related" : [
        {
            "_id" : ObjectId("5a29316a545eb40950c33bca"),
            "name" : "E"
        },
        {
            "_id" : ObjectId("5a29316a545eb40950c33bc9"),
            "name" : "D",
            "child" : "E"
        }
    ]
}


问:
What's the best way to draw a pie chart in Android with selectable slices?
I've looked into achartengine and a couple other options, but none of them seem to support any way to implement drill down into the data.  </p>

答:
I had a similar problem, but with histograms. I ended up creating a custom view that:

takes a maximum value as the top of the graph, to make a proportion with values to graph (you have 360 constant degrees)

an array of values

a parameter for column width

then draws the histogram (it won't be too hard drawing a pie chart) and overriding onTouchEvent() to determine which column was clicked.

As we're talking of a pie chart you'll have to do some more maths to find which slice was clicked.

ContentLicense: CC BY-SA 2.5


问:
OpenCl global work-item operation priority
I want to know the priority of index counting for the following code snippets (simple 2 dimensional matrix multiplication routine).

```<code>kernel void mmul(
   const int N,
   global float* A,
   global float* B,
   global float* C)
 {
     int k;
     int i = get_global_id(0);
     int j = get_global_id(1);
     float tmp;
     if ((i < N) && (j < N))
     {
         tmp = 0.0f;
         for (k = 0; k < N; k++)
             tmp += A[i*N+k] * B[k*N+j];
         C[i*N+j] = tmp;
     }
}
</code>```

If you look inside the for loop with 'k' counter you can see global work-item 'i' and 'j' placed in the same line. I want to know which of them have priority in terms of counting the indexes (eg. 1,2,3,4, ... , n) of 'i' and 'j'. I don't understand how this would work as I am new to OpenCl and I would use nested for loop, if I am just using normal C or Python, for this type of operation.

Can someone explain how the global work-item work?

Thank you.

答:
You should focus more on memory read/write priorities than workitem issuing order. To enforce a priority/order on memory operations, use mem_fence(in-workitem) , barrier(in-workgroup) and even kernels(all workitems sync point). Using deliberate empty for-loops or atomic functions cannot guarantee a memory-write/read priority. Only memory fences/barriers/kernels can.

There is no priority for any workitem(to start/end running) but they are grouped and executed on compute units which have many threads to run them. There is no guarantee that workitem i,j will execute before i+1,j+1 but there is a guarantee they will be executed in same compute unit(with cores sharing L1 cache) if they are in same workgroup(with size of 16,16 for example) when using Nvidia and Amd gpus.

Being executed in same compute unit increases chances of being issued at the same time which is not a priority ofcourse but sharing resources like L1 cache means high performance.

Even in same workgroup, there is no guarantee if a local workitem is issued before some other workitem but they are more likely happening at the same time if they are on same SIMD unit(such as 16-wide parts in Amd gpu).

Body:
I want to know the priority of index counting for the following code snippets (simple 2 dimensional matrix multiplication routine).

kernel void mmul(
   const int N,
   global float* A,
   global float* B,
   global float* C)
 {
     int k;
     int i = get_global_id(0);
     int j = get_global_id(1);
     float tmp;
     if ((i < N) && (j < N))
     {
         tmp = 0.0f;
         for (k = 0; k < N; k++)
             tmp += A[i*N+k] * B[k*N+j];
         C[i*N+j] = tmp;
     }
}

If you look inside the for loop with 'k' counter you can see global work-item 'i' and 'j' placed in the same line. I want to know which of them have priority in terms of counting the indexes (eg. 1,2,3,4, ... , n) of 'i' and 'j'. I don't understand how this would work as I am new to OpenCl and I would use nested for loop, if I am just using normal C or Python, for this type of operation.

Can someone explain how the global work-item work?

Thank you.


问:
Get element at index of a Array[(Array[String, Long)]
So I have some data:

```<code>val data = Array[(Array[String], Long)]
</code>```

Which is an array of pairs, where each pair consists of another array and a number. I have created a ListBuffer as follows:

```<code>var x = ListBuffer[(Array[String], Long)]
</code>```

I would like to append an element at some index i to x. I do the following:

```<code> x += data(i)
</code>```

However, I get the error:

Type mismatch, expected: String, actual: (Array[String], Long)

What am I doing wrong? I am working in IntelliJ and Scala 2.10.7.

Also this example (which is a concrete example (I cannot provide the original example)) also gives the same error:

```<code>val xData = ListBuffer[(Array[String], Long)]
    var x = ListBuffer[(Array[String], Long)]
    x += xData(0)
</code>```

答:
So the issue was that I forgot brackets at the end of ListBuffer initiation.

This works:

```<code>var x = ListBuffer[(Array[String], Long)]()
</code>```

Body:
So I have some data:

val data = Array[(Array[String], Long)]

Which is an array of pairs, where each pair consists of another array and a number. I have created a ListBuffer as follows:

var x = ListBuffer[(Array[String], Long)]

I would like to append an element at some index i to x. I do the following:

 x += data(i)

However, I get the error:

Type mismatch, expected: String, actual: (Array[String], Long)

What am I doing wrong? I am working in IntelliJ and Scala 2.10.7.

Also this example (which is a concrete example (I cannot provide the original example)) also gives the same error:

val xData = ListBuffer[(Array[String], Long)]
    var x = ListBuffer[(Array[String], Long)]
    x += xData(0)

Body:
So the issue was that I forgot brackets at the end of ListBuffer initiation.

This works:

var x = ListBuffer[(Array[String], Long)]()


问:
Which Thread Hold Lock in wait() and notify() multithreading
I have a confusion in multithreading in below code ...

```<code>public class ThreadTest implements Runnable {
        private int num;
        private static SecondThread obj = new SecondThread();

        public void run() {
            synchronized (obj) { //which thread holding lock here
                try {

                    obj.wait();

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
</code>```

which thread is owner while synchronize method is called.

which thread holding lock ThreadTest or SecondThread

what is mean by releasing lock here obj.wait(); means ? Once lock is released can same object come inside synchronized block and access code until previous thread get notified ?

答:
1.which thread is owner while synchronize method is called.
2.which thread holding lock ThreadTest or SecondThread

Ans. The thread which had called synchronized method will be owner. 'synchronized (obj) {' If you mean this line of the code then its not a synchronized method but synchronized block. In this case its ThreadTest which will hold lock on obj which is instance of SecondThread.

3.what is mean by releasing lock here obj.wait(); means ?

Ans. Releasing a lock means giving up their claims allowing other threads to acquire lock on that object so that they can execute synchronized methods/blocks. obj.wait() here means that ThreadTest wants to give up the lock and wait until some one calls notify on 'obj' once other thread has called notify and this notification is received by ThreadTest it will try to get the lock on 'obj'

Once lock is released can same object come inside synchronized block and access code until previous thread get notified ?

Ans. Yes it can but provided that same object owns the lock for 'obj' as this is the requirement to execute any synchronized method/block.

Body:
I have a confusion in multithreading in below code ...

public class ThreadTest implements Runnable {
        private int num;
        private static SecondThread obj = new SecondThread();

        public void run() {
            synchronized (obj) { //which thread holding lock here
                try {

                    obj.wait();

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

which thread is owner while synchronize method is called.

which thread holding lock ThreadTest or SecondThread

what is mean by releasing lock here obj.wait(); means ? Once lock is released can same object come inside synchronized block and access code until previous thread get notified ?


问:
ionic 3 - Error Could not find an installed version of Gradle either in Android Studio
I create ionic 3 project and add file and transfer cordova plugin like this and cant able to run android using this command ionic cordova run android --prod

Installing "cordova-plugin-file-transfer" for android
Failed to install 'cordova-plugin-file-transfer': CordovaError: Version of installed plugin: "cordova-plugin-file@4.3.3" does not satisfy dependency plugin requirement "cordova-plugin-file@^5.0.0". Try --force to use installed plugin as dependency.
    at /usr/local/lib/node_modules/cordova/node_modules/cordova-lib/src/plugman/install.js:581:33
    at _fulfilled (/usr/local/lib/node_modules/cordova/node_modules/q/q.js:787:54)
    at self.promiseDispatch.done (/usr/local/lib/node_modules/cordova/node_modules/q/q.js:816:30)
    at Promise.promise.promiseDispatch (/usr/local/lib/node_modules/cordova/node_modules/q/q.js:749:13)
    at /usr/local/lib/node_modules/cordova/node_modules/q/q.js:509:49
    at flush (/usr/local/lib/node_modules/cordova/node_modules/q/q.js:108:17)
    at _combinedTickCallback (internal/process/next_tick.js:131:7)
    at process._tickCallback (internal/process/next_tick.js:180:9)
Failed to restore plugin "cordova-plugin-file-transfer" from config.xml. You might need to try adding it again. Error: Version of installed plugin: "cordova-plugin-file@4.3.3" does not satisfy dependency plugin requirement "cordova-plugin-file@^5.0.0". Try --force to use installed plugin as dependency.
ANDROID_HOME=/Users/reactivespace/Library/Android/sdk
JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home
Error: Could not find an installed version of Gradle either in Android Studio,
or on your system to install the gradle wrapper. Please include gradle
in your path, or install Android Studio
[ERROR] An error occurred while running cordova run android (exit code 1)

答:
Try this:

Download the latest Gradle distribution here.

Then create a new directory C:\Gradle with File Explorer.

Unzip the content inside this folder.

After that, under System Variables select Path, then click Edit. Add an entry for C:\Gradle\gradle-4.4\bin. Click OK to save.

Restart your computer than give it another try.

Hope this steps can help you.


问:
sql fetch one record per date from table
I have a table like:

```<code>o_id  order_no   date        etc....
 4     1         2017-02-01
 4     2         2017-02-01
 4     3         2017-02-01
</code>```

what i want is only one(highest order no) record per date should be fetched.
For example for only order_no 3 for o_id 4 should be fetched

Output:

```<code>o_id       order_no      date
4          3             2017-02-01
2          1             .........so on
</code>```

答:
You may use GROUP BY and MAX if the order_no is unique in each o_id group

```<code>select your_table.*
from your_table
join
(
  select o_id, max(order_no) maxorder
  from your_table
  group by o_id
) t on t.o_id = your_table.oid and t.maxorder = your_table.order_no
</code>```

Similar questions

Select corresponding to row from the same table - you can find there a performance comparison of group by and window function version, however, the comparison is for SQL Server.

Body:
I have a table like:

o_id  order_no   date        etc....
 4     1         2017-02-01
 4     2         2017-02-01
 4     3         2017-02-01

what i want is only one(highest order no) record per date should be fetched.
For example for only order_no 3 for o_id 4 should be fetched

Output:

o_id       order_no      date
4          3             2017-02-01
2          1             .........so on

Body:
You may use GROUP BY and MAX if the order_no is unique in each o_id group

select your_table.*
from your_table
join
(
  select o_id, max(order_no) maxorder
  from your_table
  group by o_id
) t on t.o_id = your_table.oid and t.maxorder = your_table.order_no

Similar questions

Select corresponding to row from the same table - you can find there a performance comparison of group by and window function version, however, the comparison is for SQL Server.


问:
Firebase addListener in onclick method
Is it possible to attach a firebase database listener in a button's onClick method?

I put datareference.addValueEventListener in the onClick method, but it crashes when I click on the button and try to update a value in firebase.

Do I create a whole new object and use setvalue to substitute the old value? In my case, I want to update the points of a user, and here is my onClick method

```<code>public void itemClick(View view) {
    int position;
    position = (Integer) view.getTag();
    if (taskList.get(position).getWorker()!=null && taskList.get(position).getWorker().compareTo(userEmail)==0) {
        if (taskList.get(position).getStates().compareTo("COMPLETE")==0)
            Toast.makeText(getContext(), getString(R.string.already_complete), Toast.LENGTH_LONG).show();
            taskList.get(position).setStates("COMPLETE");
            db.updateStates(taskList.get(position).getStates(), taskList.get(position).getName());
            Double awardpoint = taskList.get(position).getPoints();
            update(awardpoint);
            search();
            Toast.makeText(getContext(), getString(R.string.successful_complete), Toast.LENGTH_LONG).show();
        }else
            Toast.makeText(getContext(), getString(R.string.fail_complete), Toast.LENGTH_LONG).show();
}
</code>```

Here is my update method, I didnt put anything here, but it still crashes

```<code> private void update ( Double point){
    databaseReference.child("points").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

}
</code>```

}
Here is my onCreate method

```<code> public void onCreate(){

    currentUser = FirebaseAuth.getInstance().getCurrentUser();
    String curren_uid = currentUser.getUid();
    databaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child(curren_uid);
}
</code>```

Here is the exception, and it seems that there's a null pointer exception.
I looked a simliar question on stackOverflow, and it says i should "only listenning the bussniness i interest in ".. but my reference is already pointed to the user with specific uid.

```<code>12-06 20:17:47.401 4399-4399/ca.uottawa.leyaoli.seg2105_final_project E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: ca.uottawa.leyaoli.seg2105_final_project, PID: 4399
                                                                                java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.database.DatabaseReference com.google.firebase.database.DatabaseReference.child(java.lang.String)' on a null object reference
                                                                                at ca.uottawa.leyaoli.seg2105_final_project.Tab2.update(Tab2.java:161)
                                                                                at ca.uottawa.leyaoli.seg2105_final_project.Tab2.itemClick(Tab2.java:153)
                                                                                at ca.uottawa.leyaoli.seg2105_final_project.TaskListAdapter.onClick(TaskListAdapter.java:93)
                                                                                at android.view.View.performClick(View.java:6256)
                                                                                at android.view.View$PerformClick.run(View.java:24701)
                                                                                at android.os.Handler.handleCallback(Handler.java:789)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:98)
                                                                                at android.os.Looper.loop(Looper.java:164)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
</code>```

答:
The problem in your code is that curren_uid returns null. You cannot pass arguments with null value into child() method. In order to solve this problem you need to review your authentication process.

So to answer your question, yes, it's possible to attach a Firebase listener in a button's onClick method.

Title: Firebase addListener in onclick method

Body:
Is it possible to attach a firebase database listener in a button's onClick method?

I put datareference.addValueEventListener in the onClick method, but it crashes when I click on the button and try to update a value in firebase.

Do I create a whole new object and use setvalue to substitute the old value? In my case, I want to update the points of a user, and here is my onClick method

public void itemClick(View view) {
    int position;
    position = (Integer) view.getTag();
    if (taskList.get(position).getWorker()!=null && taskList.get(position).getWorker().compareTo(userEmail)==0) {
        if (taskList.get(position).getStates().compareTo("COMPLETE")==0)
            Toast.makeText(getContext(), getString(R.string.already_complete), Toast.LENGTH_LONG).show();
            taskList.get(position).setStates("COMPLETE");
            db.updateStates(taskList.get(position).getStates(), taskList.get(position).getName());
            Double awardpoint = taskList.get(position).getPoints();
            update(awardpoint);
            search();
            Toast.makeText(getContext(), getString(R.string.successful_complete), Toast.LENGTH_LONG).show();
        }else
            Toast.makeText(getContext(), getString(R.string.fail_complete), Toast.LENGTH_LONG).show();
}

Here is my update method, I didnt put anything here, but it still crashes

 private void update ( Double point){
    databaseReference.child("points").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

}

}
Here is my onCreate method

 public void onCreate(){

    currentUser = FirebaseAuth.getInstance().getCurrentUser();
    String curren_uid = currentUser.getUid();
    databaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child(curren_uid);
}

Here is the exception, and it seems that there's a null pointer exception.
I looked a simliar question on stackOverflow, and it says i should "only listenning the bussniness i interest in ".. but my reference is already pointed to the user with specific uid.

12-06 20:17:47.401 4399-4399/ca.uottawa.leyaoli.seg2105_final_project E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: ca.uottawa.leyaoli.seg2105_final_project, PID: 4399
                                                                                java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.database.DatabaseReference com.google.firebase.database.DatabaseReference.child(java.lang.String)' on a null object reference
                                                                                at ca.uottawa.leyaoli.seg2105_final_project.Tab2.update(Tab2.java:161)
                                                                                at ca.uottawa.leyaoli.seg2105_final_project.Tab2.itemClick(Tab2.java:153)
                                                                                at ca.uottawa.leyaoli.seg2105_final_project.TaskListAdapter.onClick(TaskListAdapter.java:93)
                                                                                at android.view.View.performClick(View.java:6256)
                                                                                at android.view.View$PerformClick.run(View.java:24701)
                                                                                at android.os.Handler.handleCallback(Handler.java:789)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:98)
                                                                                at android.os.Looper.loop(Looper.java:164)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)


问:
Node.js Inter-process communication Faulters
Given the following parent-process code:

```<code>//SSO
this.sso = fork('./app/utils/SSOproxy.js', [], {
  stdio: [0, 1, 2, 'ipc']
});
console.log(process);
console.log(this.sso);

//__handshake
this.sso.send({
  opcode: 'ACK',
  params: [],
  ref: null
});
console.log('STEP_1');
process.prependOnceListener('message', ((msg) => {
  if (msg.status) {
    if ((msg.opcode === 'ACK') && (msg.params[0] === 'ok')) {
      console.log('STEP_3');
    }
  }
}));

//__e.o.handshake
</code>```

And child-process (SSOproxy.js) code:

```<code>process.on('message', ((msg) => {
  switch (msg.opcode) {
    //handshake
    case 'ACK':
      process.send({
        opcode: 'ACK',
        params: ['ok'],
        ref: null
      });
      console.log('STEP_2');
      break;
      //Other paths...
  }
));
</code>```

In the log observed - STEP_1 is followed by STEP_2 but I never see STEP_3 because I can't for-the-life of me figure out how to get duplex communication for child/parent. How to achieve the same?

答:
In your prependOnceListener you have a condition for msg.status but I don't see this anywhere in your SSOproxy.js code.

This means your if will never evaluate true

Can you try adding a status to your message:

```<code>process.send({
    opcode:'ACK',
    params:['ok'],
    ref: null,
    status: 'test1234'
});
</code>```

Body:
Given the following parent-process code:

//SSO
this.sso = fork('./app/utils/SSOproxy.js', [], {
  stdio: [0, 1, 2, 'ipc']
});
console.log(process);
console.log(this.sso);

//__handshake
this.sso.send({
  opcode: 'ACK',
  params: [],
  ref: null
});
console.log('STEP_1');
process.prependOnceListener('message', ((msg) => {
  if (msg.status) {
    if ((msg.opcode === 'ACK') && (msg.params[0] === 'ok')) {
      console.log('STEP_3');
    }
  }
}));

//__e.o.handshake

And child-process (SSOproxy.js) code:

process.on('message', ((msg) => {
  switch (msg.opcode) {
    //handshake
    case 'ACK':
      process.send({
        opcode: 'ACK',
        params: ['ok'],
        ref: null
      });
      console.log('STEP_2');
      break;
      //Other paths...
  }
));

In the log observed - STEP_1 is followed by STEP_2 but I never see STEP_3 because I can't for-the-life of me figure out how to get duplex communication for child/parent. How to achieve the same?

Body:
In your prependOnceListener you have a condition for msg.status but I don't see this anywhere in your SSOproxy.js code.

This means your if will never evaluate true

Can you try adding a status to your message:

process.send({
    opcode:'ACK',
    params:['ok'],
    ref: null,
    status: 'test1234'
});


问:
How to subscribe a wxPython phoenix TreeListCtrl to mouse double-clicks
Using wxPython4 (a.k.a. phoenix), I want a gui with a TreeListCtrl to subscribe to double-clicks and tell the handler code what cell in the TreeListCtrl was double-clicked.

The specific version of wxPython4 that I'm currently using is 4.0.0b2, which comes with a demo code package available here: https://extras.wxpython.org/wxPython4/extras/4.0.0b2/ , and which includes the code below for TreeListCtrl demonstration.

How should I modify this code so that I can handle double clicks on the TreeListCtrl?

```<code>#!/usr/bin/env python

import wx
import wx.dataview

import images

#----------------------------------------------------------------------

class TestPanel(wx.Panel):
    def __init__(self, parent, log):
        self.log = log
        wx.Panel.__init__(self, parent, -1)
        self.Bind(wx.EVT_SIZE, self.OnSize)

        self.tree = wx.dataview.TreeListCtrl(self, -1, style =
                                        wx.TR_DEFAULT_STYLE
                                        #| wx.TR_HAS_BUTTONS
                                        #| wx.TR_TWIST_BUTTONS
                                        #| wx.TR_ROW_LINES
                                        #| wx.TR_COLUMN_LINES
                                        #| wx.TR_NO_LINES
                                        | wx.TR_FULL_ROW_HIGHLIGHT
                                   )

        isz = (16,16)
        il = wx.ImageList(isz[0], isz[1])
        fldridx     = il.Add(wx.ArtProvider.GetBitmap(wx.ART_FOLDER,      wx.ART_OTHER, isz))
        fldropenidx = il.Add(wx.ArtProvider.GetBitmap(wx.ART_FILE_OPEN,   wx.ART_OTHER, isz))
        fileidx     = il.Add(wx.ArtProvider.GetBitmap(wx.ART_NORMAL_FILE, wx.ART_OTHER, isz))
        smileidx    = il.Add(images.Smiles.GetBitmap())

        self.tree.SetImageList(il)
        self.il = il

        # create some columns
        self.tree.AppendColumn("Main column")
        self.tree.AppendColumn("Column 1")
        self.tree.AppendColumn("Column 2")
        ##self.tree.SetMainColumn(0) # the one with the tree in it...
        self.tree.SetColumnWidth(0, 175)

        self.root = self.tree.InsertItem(self.tree.GetRootItem(), wx.dataview.TLI_FIRST, "The Root Item")

        self.tree.SetItemText(self.root, 1, "col 1 root")
        self.tree.SetItemText(self.root, 2, "col 2 root")
        self.tree.SetItemImage(self.root, closed=fldridx, opened=fldropenidx)

        for x in range(15):
            txt = "Item %d" % x
            child = self.tree.AppendItem(self.root, txt)
            self.tree.SetItemText(child, 1, txt + "(c1)")
            self.tree.SetItemText(child, 2, txt + "(c2)")
            self.tree.SetItemImage(child, closed=fldridx, opened=fldropenidx)

            for y in range(5):
                txt = "item %d-%s" % (x, chr(ord("a")+y))
                last = self.tree.AppendItem(child, txt)
                self.tree.SetItemText(last, 1, txt + "(c1)")
                self.tree.SetItemText(last, 2, txt + "(c2)")
                self.tree.SetItemImage(last, closed=fldridx, opened=fldropenidx)

                for z in range(5):
                    txt = "item %d-%s-%d" % (x, chr(ord("a")+y), z)
                    item = self.tree.AppendItem(last,  txt)
                    self.tree.SetItemText(item, 1, txt + "(c1)")
                    self.tree.SetItemText(item, 2, txt + "(c2)")
                    #TODO: Phoenix change selected to smiley
                    self.tree.SetItemImage(item, closed=fileidx, opened=smileidx)
                    ## self.tree.SetItemImage(item, fileidx, which = wx.TreeItemIcon_Normal)
                    ## self.tree.SetItemImage(item, smileidx, which = wx.TreeItemIcon_Selected)

        self.tree.Expand(self.root)

        ## self.tree.GetMainWindow().Bind(wx.EVT_RIGHT_UP, self.OnRightUp)
        self.tree.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnActivate)

    def OnActivate(self, event):
        self.log.write('OnActivate: %s' % self.tree.GetItemText(event.GetItem()))

    def OnRightUp(self, event):
        pos = event.GetPosition()
        item, flags, col = self.tree.HitTest(pos)
        if item:
            self.log.write('Flags: %s, Col:%s, Text: %s' %
                           (flags, col, self.tree.GetItemText(item, col)))

    def OnSize(self, event):
        self.tree.SetSize(self.GetSize())
</code>```

I tried the following two variants at the end of the Panel constructor, neither of which works:

Variant 1:

```<code>...
    self.tree.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnActivate)
    self.tree.Bind(wx.EVT_LEFT_DCLICK, self.OnLeftDClick)

def OnLeftDClick(self, event):
    print("LeftDClick")

def OnActivate(self, event):
...
</code>```

Variant 2:

```<code>...
    self.tree.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnActivate)
    self.Bind(wx.EVT_LEFT_DCLICK, self.OnLeftDClick)

def OnLeftDClick(self, event):
    print("LeftDClick")

def OnActivate(self, event):
...
</code>```

I would have hoped to see the "LeftDClick" text appear on the console when I double-click somewhere in the tree, but it doesn't.

Note 1: I used to have that functionality working in wxPython3, by subscribing as follows:

```<code>self.tree.GetMainWindow().Bind(wx.EVT_LEFT_DCLICK, self.OnLeftDClick)
</code>```

That code doesn't work any more in wxPython4:

```<code>AttributeError: 'TreeListCtrl' object has no attribute 'GetMainWindow'
</code>```

Note 2: The reason I want to specifically make this work for wxPython4 is that I'm porting from python2 to python3, and wxPython3 is incompatible with python3.

Note 3: The wxPython4.0.0b2 TreeListCtrl comes with the following bug in the C++ code: http://trac.wxwidgets.org/ticket/17476 . The patch attached to that bug filing solved the issue for me.

答:
I stumbled upon a workaround for my problem: wxPython provides a class called HyperTreeList, which is very similar to the wxPython3 TreeListCtrl, and which seems to have undergone less changes between wxPython3 and wxPython4.

https://wxpython.org/Phoenix/docs/html/wx.lib.agw.hypertreelist.HyperTreeList.html

In particular it accepts the subscription to double-clicks in the traditional manner:

```<code>self.tree.GetMainWindow().Bind(wx.EVT_LEFT_DCLICK, self.OnLeftDClick)
</code>```

Only two changes needed to be made in my case when switching from TreeListCtrl to HyperTreeList wx3:

tree.SetBackgroundColour('white')

tree.SetImageList became tree.AssignImageList

Body:
Using wxPython4 (a.k.a. phoenix), I want a gui with a TreeListCtrl to subscribe to double-clicks and tell the handler code what cell in the TreeListCtrl was double-clicked.

The specific version of wxPython4 that I'm currently using is 4.0.0b2, which comes with a demo code package available here: https://extras.wxpython.org/wxPython4/extras/4.0.0b2/ , and which includes the code below for TreeListCtrl demonstration.

How should I modify this code so that I can handle double clicks on the TreeListCtrl?

#!/usr/bin/env python

import wx
import wx.dataview

import images

#----------------------------------------------------------------------

class TestPanel(wx.Panel):
    def __init__(self, parent, log):
        self.log = log
        wx.Panel.__init__(self, parent, -1)
        self.Bind(wx.EVT_SIZE, self.OnSize)

        self.tree = wx.dataview.TreeListCtrl(self, -1, style =
                                        wx.TR_DEFAULT_STYLE
                                        #| wx.TR_HAS_BUTTONS
                                        #| wx.TR_TWIST_BUTTONS
                                        #| wx.TR_ROW_LINES
                                        #| wx.TR_COLUMN_LINES
                                        #| wx.TR_NO_LINES
                                        | wx.TR_FULL_ROW_HIGHLIGHT
                                   )

        isz = (16,16)
        il = wx.ImageList(isz[0], isz[1])
        fldridx     = il.Add(wx.ArtProvider.GetBitmap(wx.ART_FOLDER,      wx.ART_OTHER, isz))
        fldropenidx = il.Add(wx.ArtProvider.GetBitmap(wx.ART_FILE_OPEN,   wx.ART_OTHER, isz))
        fileidx     = il.Add(wx.ArtProvider.GetBitmap(wx.ART_NORMAL_FILE, wx.ART_OTHER, isz))
        smileidx    = il.Add(images.Smiles.GetBitmap())

        self.tree.SetImageList(il)
        self.il = il

        # create some columns
        self.tree.AppendColumn("Main column")
        self.tree.AppendColumn("Column 1")
        self.tree.AppendColumn("Column 2")
        ##self.tree.SetMainColumn(0) # the one with the tree in it...
        self.tree.SetColumnWidth(0, 175)

        self.root = self.tree.InsertItem(self.tree.GetRootItem(), wx.dataview.TLI_FIRST, "The Root Item")

        self.tree.SetItemText(self.root, 1, "col 1 root")
        self.tree.SetItemText(self.root, 2, "col 2 root")
        self.tree.SetItemImage(self.root, closed=fldridx, opened=fldropenidx)

        for x in range(15):
            txt = "Item %d" % x
            child = self.tree.AppendItem(self.root, txt)
            self.tree.SetItemText(child, 1, txt + "(c1)")
            self.tree.SetItemText(child, 2, txt + "(c2)")
            self.tree.SetItemImage(child, closed=fldridx, opened=fldropenidx)

            for y in range(5):
                txt = "item %d-%s" % (x, chr(ord("a")+y))
                last = self.tree.AppendItem(child, txt)
                self.tree.SetItemText(last, 1, txt + "(c1)")
                self.tree.SetItemText(last, 2, txt + "(c2)")
                self.tree.SetItemImage(last, closed=fldridx, opened=fldropenidx)

                for z in range(5):
                    txt = "item %d-%s-%d" % (x, chr(ord("a")+y), z)
                    item = self.tree.AppendItem(last,  txt)
                    self.tree.SetItemText(item, 1, txt + "(c1)")
                    self.tree.SetItemText(item, 2, txt + "(c2)")
                    #TODO: Phoenix change selected to smiley
                    self.tree.SetItemImage(item, closed=fileidx, opened=smileidx)
                    ## self.tree.SetItemImage(item, fileidx, which = wx.TreeItemIcon_Normal)
                    ## self.tree.SetItemImage(item, smileidx, which = wx.TreeItemIcon_Selected)

        self.tree.Expand(self.root)

        ## self.tree.GetMainWindow().Bind(wx.EVT_RIGHT_UP, self.OnRightUp)
        self.tree.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnActivate)

    def OnActivate(self, event):
        self.log.write('OnActivate: %s' % self.tree.GetItemText(event.GetItem()))

    def OnRightUp(self, event):
        pos = event.GetPosition()
        item, flags, col = self.tree.HitTest(pos)
        if item:
            self.log.write('Flags: %s, Col:%s, Text: %s' %
                           (flags, col, self.tree.GetItemText(item, col)))

    def OnSize(self, event):
        self.tree.SetSize(self.GetSize())

I tried the following two variants at the end of the Panel constructor, neither of which works:

Variant 1:

...
    self.tree.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnActivate)
    self.tree.Bind(wx.EVT_LEFT_DCLICK, self.OnLeftDClick)

def OnLeftDClick(self, event):
    print("LeftDClick")

def OnActivate(self, event):
...

Variant 2:

...
    self.tree.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnActivate)
    self.Bind(wx.EVT_LEFT_DCLICK, self.OnLeftDClick)

def OnLeftDClick(self, event):
    print("LeftDClick")

def OnActivate(self, event):
...

I would have hoped to see the "LeftDClick" text appear on the console when I double-click somewhere in the tree, but it doesn't.

Note 1: I used to have that functionality working in wxPython3, by subscribing as follows:

self.tree.GetMainWindow().Bind(wx.EVT_LEFT_DCLICK, self.OnLeftDClick)

That code doesn't work any more in wxPython4:

AttributeError: 'TreeListCtrl' object has no attribute 'GetMainWindow'

Note 2: The reason I want to specifically make this work for wxPython4 is that I'm porting from python2 to python3, and wxPython3 is incompatible with python3.

Note 3: The wxPython4.0.0b2 TreeListCtrl comes with the following bug in the C++ code: http://trac.wxwidgets.org/ticket/17476 . The patch attached to that bug filing solved the issue for me.

Body:
I stumbled upon a workaround for my problem: wxPython provides a class called HyperTreeList, which is very similar to the wxPython3 TreeListCtrl, and which seems to have undergone less changes between wxPython3 and wxPython4.

https://wxpython.org/Phoenix/docs/html/wx.lib.agw.hypertreelist.HyperTreeList.html

In particular it accepts the subscription to double-clicks in the traditional manner:

self.tree.GetMainWindow().Bind(wx.EVT_LEFT_DCLICK, self.OnLeftDClick)

Only two changes needed to be made in my case when switching from TreeListCtrl to HyperTreeList wx3:

tree.SetBackgroundColour('white')

tree.SetImageList became tree.AssignImageList

ContentLicense: CC BY-SA 4.0


问:
Removing entire words from a .txt file, but not when that word appears as a substring
I'm currently producing a python program to search through .txt files provided and remove any numbers, commas, and some certain words. It's for use in transcribing phone calls, so these are words like "um" and "uh" which are unnecessary. This is written back into a new text file which contains everything except the removed data.

The code I have produced works, but also removes those words from any longer words containing them, for example "momentum" becomes "moment" as it contains "um". Here is the code:

```<code>infile = "testfile.txt"
outfile = "cleanedfile.txt"
numbers = [1,2,3,4,5,6,7,8,9]
deleteList = [",", "Um", "um", "Uh", "uh", str(numbers)]
fin = open(infile)
fout = open(outfile, 'w+')
for line in fin:
    for word in deleteList:
        line = line.replace(word, "")
    fout.write(line)
fin.close()
fout.close()
</code>```

Any help would be greatly appreciated.

答:
I've solved it using regex, changing the code to look like this:

```<code>import re

for line in fin:
    line = re.sub(r"\b(U|u)(m|h)\b", "", line)
    fout.write(line)
</code>```

Thanks everyone for their help.

Body:
I'm currently producing a python program to search through .txt files provided and remove any numbers, commas, and some certain words. It's for use in transcribing phone calls, so these are words like "um" and "uh" which are unnecessary. This is written back into a new text file which contains everything except the removed data.

The code I have produced works, but also removes those words from any longer words containing them, for example "momentum" becomes "moment" as it contains "um". Here is the code:

infile = "testfile.txt"
outfile = "cleanedfile.txt"
numbers = [1,2,3,4,5,6,7,8,9]
deleteList = [",", "Um", "um", "Uh", "uh", str(numbers)]
fin = open(infile)
fout = open(outfile, 'w+')
for line in fin:
    for word in deleteList:
        line = line.replace(word, "")
    fout.write(line)
fin.close()
fout.close()

Any help would be greatly appreciated.

Body:
I've solved it using regex, changing the code to look like this:

import re

for line in fin:
    line = re.sub(r"\b(U|u)(m|h)\b", "", line)
    fout.write(line)

Thanks everyone for their help.


问:
How to style a div to be fixed and be relative to surroundings
I have a website where I need the following functionality at the same time

The new header is fixed (using position:fixed)

The new header starts above the actual website (using position:relative)

Obviously I can't have both of these at once, but that is what I do want...

So, to explain in another way, what I when a header to be inserted into my webpage (via javascript) it doesn't obscure the website in any way, unless the user scrolls on the webpage, where the header remains 'on top' fixed.

Can this be done with CSS only where the following HTML can't be updated?

```<code><body>
<header>
<nav>
//website
</code>```

And after the javascript inserts the header

```<code><body>
<div id="myInsertedDiv" class="whatCssGoesHere"></div>
<header>
<nav>
//website
</code>```

https://jsfiddle.net/59orh8uf/4/

The fiddle shows a web page, where I insert this 'header' The header needs to be the first item in the webpage (at the top of the webpage). This is what is occurring on the jsfiddle, so the first challenge is fixed... All I need to do now is make it so when I scroll down, it remains on top.

I also need to point out, that the example is not the same for every website, and as such I can't touch the HTML of the header or anything else below

答:
The solution was to not use CSS as I don't think it was possible.

I used javascript and added an eventlistener on the scrollbar. If the scroll bar Y position is less than 1, then style.position = relative, else style.position = fixed

Body:
I have a website where I need the following functionality at the same time

The new header is fixed (using position:fixed)

The new header starts above the actual website (using position:relative)

Obviously I can't have both of these at once, but that is what I do want...

So, to explain in another way, what I when a header to be inserted into my webpage (via javascript) it doesn't obscure the website in any way, unless the user scrolls on the webpage, where the header remains 'on top' fixed.

Can this be done with CSS only where the following HTML can't be updated?

//website

And after the javascript inserts the header

//website

https://jsfiddle.net/59orh8uf/4/

The fiddle shows a web page, where I insert this 'header' The header needs to be the first item in the webpage (at the top of the webpage). This is what is occurring on the jsfiddle, so the first challenge is fixed... All I need to do now is make it so when I scroll down, it remains on top.

I also need to point out, that the example is not the same for every website, and as such I can't touch the HTML of the header or anything else below


答:
change .value to .val().

See http://api.jquery.com/val/

Title: I can't seem to define a variable to the value of a form

Body:
Hello fellow programmers, i'm trying to make a website that makes a route description, but I can't assign a variable to the input form.
I am trying to assign the variable "Bval" (B value) To the green select form, and "Aval" (A value) To the blue select form. Could anyone point out the issue in this code?

$(document).ready(function() {

  $('#selectroomA').change(function() {
   Aval = $('#selectroomA').value;
  });

 $('#selectroomB').change(function() {
  Bval = $('#selectroomB').value;
 });

 $('#submit').click(function() {
      console.log('clicked');
  if (Aval === "a001") {
            console.log('Aval = a001');
   if (Bval === "a001") {
              console.log('Bval = a001');
     alert('Je bent al in de A001');
   }
  } else {
          console.log('error with if statements');
        }
 });
});

body {
  margin: 0px;
  padding: 0px;
  font-family: Roboto;
}

.map-box {
  width: 600px;
  height: 300px;
  background: lightgrey;
  overflow: scroll;
}
.svg-container {
  width: 80%;
  margin-left: 10%;
  margin-right: 10%;
  overflow: scroll;
  background: lightgrey;
}
.material-icons {
  font-family: 'Material Icons';
  font-weight: normal;
  font-style: normal;
  font-size: 1px;  /* Preferred icon size */
  display: inline-block;
  line-height: 1;
  text-transform: none;
  letter-spacing: normal;
  word-wrap: normal;
  white-space: nowrap;
  direction: ltr;
  /* Support for all WebKit browsers. */
  -webkit-font-smoothing: antialiased;
  /* Support for Safari and Chrome. */
  text-rendering: optimizeLegibility;
  /* Support for Firefox. */
  -moz-osx-font-smoothing: grayscale;
  /* Support for IE. */
  font-feature-settings: 'liga';
}

/* Buildings */
#building {
  transition: 0.4s fill ease-in-out;
}
.building-a {
  height: 180px;
  width: 120px;
  fill: #455a64;
}
.building-a1 {
  height: 180px;
  width: 120px;
  fill: #1976D2;
}
.building-a2 {
  height: 180px;
  width: 120px;
  fill: #388E3C;
}
#a0 {
  opacity: 1;
}
#a1 {
  opacity: 0;
  transition: 0.4s opacity ease-in-out;
}
#a2 {
  opacity: 0;
  transition: 0.4s opacity ease-in-out;
}

/* Rooms */
#room {
  fill: #607d8b;
  transition: 0.4s fill ease-in-out;
}

/* Paths */
#generalpath {
  fill: white;
}
.path {
  transition: 0.3s opacity ease-in-out;
}
#a0path1, #a0path2, #a0path3, #a001pathty, #a002path, #a003path, #a004path, #a0stairpath {
  fill: #F44336;
  opacity: 0;
}

/* Form */
fieldset {
  border: none;
}
select {
  font-family: Roboto;
  background: white;
  color: black;
  padding: 5px;
  margin: 5px;
  border: none;
  border-radius: 2px;
  cursor: pointer;
}
button {
  margin-top: 12px;
}
#selectroomA {
  background: #40C4FF;
}
#selectroomB {
  background: #00E676;
}

/* Buttons */
.buttons {
  display: block;
}
.upButton, .downButton {
  font-family: Roboto;
  background: #EEE;
  color: black;
  transition: 0.4s all ease-in-out;
  border-radius: 2px;
  text-align: center;
  width: 30px;
  height: 30px;
  margin-top: 5px;
  margin-left: 5px;
  cursor: pointer;
  float: right;
}
.upButton, .downButton:hover {
  box-shadow: 2px 2px 6px #37474F;
  background-color: white;
}
#button i {
  margin-top: 4px;
  font-size: 22px;
}
.disabled {
  font-family: Roboto;
  background: #CCC;
  color: grey;
  transition: 0.4s all ease-in-out;
  border-radius: 2px;
  text-align: center;
  width: 30px;
  height: 30px;
  margin-top: 5px;
  margin-left: 5px;
  cursor: default;
  float: right;
}
/* Toolbar */
#toolbartop {
  width: 77%;
  padding-top: 10px;
  padding-left: 2%;
  padding-right: 1%;
  margin-left: 10%;
  margin-right: 7%;
  background-color: #607D8B;
  color: white;
}
.selection {
  display: block;
  padding-right: 10px;
  white-space: nowrap;
}
.selection select {
  vertical-align: middle;
  margin-left: 10px;
}
#A {
  float: left;
}
#B {
  float: left;
}
#submit {
  width: 77%;
  height: 30px;
  padding-top: 10px;
  padding-left: 2%;
  padding-right: 1%;
  margin-left: 10%;
  margin-right: 7%;
  background-color: #455A64;
  color: white;
  text-align: center;
  cursor: pointer;
  transition: 0.4s background-color ease-in-out;
}
#submit:hover {
  background-color: #546E7A;
}

    <link rel="stylesheet" type="text/css" href="style.css">
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">

      <form method="post">

          <fieldset class="ui-field-contain">

              <select name="selectroomA" id="selectroomA">
                <option value="null">Selecteer startpunt</option>
                <optgroup label="A-gebouw">
                  <option value="a001">A001</option>
                  <option value="a002">A002</option>
                  <option value="a003">A003</option>
                  <option value="a004">A004</option>
                  <option value="a005">A005</option>
                </optgroup>
              </select>

            <select name="selectroomB" id="selectroomB">
              <option value="null">Selecteer bestemming</option>
              <optgroup label="A-gebouw">
                <option value="a001">A001</option>
                <option value="a002">A002</option>
                <option value="a003">A003</option>
                <option value="a004">A004</option>
                <option value="a005">A005</option>
              </optgroup>
            </select>

          </fieldset>

      </form>

arrow_upward

arrow_downward

Maak route

    <svg class="map-box" xmlns="http://www.w3.org/2000/svg">
      <g id="a0">

        <g class="staircase">
          <rect x='160px' y='16px' height='35px' width='26px' id="building" fill="#455a64" />
          <rect x='175px' y='40px' height='10px' width='11px' fill="#2196f3"/>

          <rect x='175px' y='39px' height='4px' width='11px' fill="#2196f3"/>
          <rect x='175px' y='33px' height='4px' width='11px' fill="#2994E7"/>
          <rect x='175px' y='27px' height='4px' width='11px' fill="#368DCF"/>
          <rect x='160px' y='16px' height='9px' width='26px' fill="#3E8AC2"/>
          <rect x='160px' y='27px' height='4px' width='11px' fill="#4B85AE"/>
          <rect x='160px' y='33px' height='4px' width='11px' fill="#5A7F95"/>
          <rect x='160px' y='39px' height='4px' width='11px' fill="#607D8B"/>
        </g>

        <rect x='130px' y='50px' class="building-a" id="building"/>
        <rect x='330px' y='50px' class="building-a" id="building"/>

        <rect x='213px' y='200px' width="35px" height="30px" id="room" class="a001"/>

        <rect x='130px' y='110px' width="30px" height="57px" id="room" class="a002"/>

        <rect x='130px' y='50px' width="30px" height="57px" id="room" class="a003"/>

        <rect x='130px' y='170px' width="30px" height="50px" id="room" class="a004"/>
        <rect x='130px' y='200px' width="80px" height="30px" id="room" class="a004"/>

        <rect x='185px' y='50px' width="25px" height="40px" id="room" class="a007"/>

        <rect x='164px' y='179px' width="85px" height="17px" id="generalpath"/>
        <rect x='164px' y='50px' width="17px" height="137px" id="generalpath"/>

        <rect x='169px' y='185px' width="65px" height="7px" id="a0path1" class="path"/>
        <rect x='169px' y='135px' width="7px" height="50px" id="a0path2" class="path"/>
        <rect x='169px' y='75px' width="7px" height="60px" id="a0path3" class="path"/>

        <rect x='228px' y='185px' width="7px" height="15px" id="a001path" class="path"/>
        <rect x='160px' y='135px' width="15px" height="7px" id="a002path" class="path"/>
        <rect x='160px' y='75px' width="15px" height="7px" id="a003path" class="path"/>
        <rect x='160px' y='185px' width="15px" height="7px" id="a004path" class="path"/>

        <rect x='169px' y='50px' width="7px" height="60px" id="a0stairpath" class="path"/>
        <rect x='163px' y='18px' width="5" height="32px" id="a0stairpath" class="path"/>
        <rect x='163px' y='18px' width="16" height="5px" id="a0stairpath" class="path"/>
        <rect x='178px' y='18px' width="5" height="32px" id="a0stairpath" class="path"/>
      </g>

      <g id="a1">

        <rect x='160px' y='16px' height='35px' width='11px' id="building" fill="#1976D2"/>
        <rect x='160px' y='16px' height='10px' width='26px' id="building" fill="#1976D2"/>
        <rect x='175px' y='16px' height='35px' width='11px' id="building" fill="#1976D2"/>
        <rect x='175px' y='40px' height='10px' width='11px' fill="#4CAF50"/>

        <rect x='175px' y='39px' height='4px' width='11px' fill="#4CAF50"/>
        <rect x='175px' y='33px' height='4px' width='11px' fill="#41A977"/>
        <rect x='175px' y='27px' height='4px' width='11px' fill="#3DA788"/>
        <rect x='160px' y='16px' height='9px' width='26px' fill="#36A2A5"/>
        <rect x='160px' y='27px' height='4px' width='11px' fill="#2E9EBE"/>
        <rect x='160px' y='33px' height='4px' width='11px' fill="#279AD9"/>
        <rect x='160px' y='39px' height='4px' width='11px' fill="#2196F3"/>

        <rect x='130px' y='50px' class="building-a1" id="building"/>

      </g>

      <g id="a2">
        <rect x='130px' y='50px' class="building-a2" id="building"/>
      </g>
    </svg>

Does anyone know what i did wrong? If so thanks in advance.


问:
C++ inlining class methods causes undefined reference
I'm getting a compiler error when I try to inline a method of one of my classes. It works when I take away the "inline" keyword.

Here's a simplified example:

main.cpp:

```<code>#include "my_class.h"

int main() {
  MyClass c;
  c.TestMethod();

  return 0;
}
</code>```

my_class.h:

```<code>class MyClass {
 public:
  void TestMethod();
};
</code>```

my_class.cpp:

```<code>#include "my_class.h"

inline void MyClass::TestMethod() {
}
</code>```

I try compiling with:

```<code>g++ main.cpp my_class.cpp
</code>```

I get the error:

```<code>main.cpp:(.text+0xd): undefined reference to `MyClass::TestMethod()'
</code>```

Everything is fine if I take away the "inline". What's causing this problem? (and how should I inline class methods? Is it possible?)

Thanks.

答:
You've defined it as not inlined in the header file, while in the cpp file you're trying to define it as inline.  That's a conflicted definition and it won't be able to find one from the other.  Your header is where you really place the inline keyword.

However, I'd remove the inline keyword as it's really more of a suggestion to the compiler anyways.  You really only need it when there's a free-floating function in the header and you don't want multiple definitions popping up in your code base.

Body:
I'm getting a compiler error when I try to inline a method of one of my classes. It works when I take away the "inline" keyword.

Here's a simplified example:

main.cpp:

#include "my_class.h"

int main() {
  MyClass c;
  c.TestMethod();

  return 0;
}

my_class.h:

class MyClass {
 public:
  void TestMethod();
};

my_class.cpp:

#include "my_class.h"

inline void MyClass::TestMethod() {
}

I try compiling with:

g++ main.cpp my_class.cpp

I get the error:

main.cpp:(.text+0xd): undefined reference to `MyClass::TestMethod()'

Everything is fine if I take away the "inline". What's causing this problem? (and how should I inline class methods? Is it possible?)

Thanks.


问:
rpcgen for Linux
We have used rpcgen to create a rpc server on Linux machine (c language).
When there are many calls to our program it still results in a single
threaded request.
I see that it's common problem from 2004, there is a new rpcgen (or other genarator) that solved this problem?

Thanks,
Kobi

答: Beware sun version is being abandoned, look for tirpc</p>

Title: rpcgen for Linux


问:
Getting error in LINQ query to sqlite
I'm trying to make login query in sqlite but can't convert AsyncTableQuery in boolean

```<code>public bool queryLogIn(string userNameLogIn,string passwordLogIn)
{
    var query=database.Table<Users>().Where(i => i.UserName == userNameLogIn && i.Password == passwordLogIn);

    if (query == true)//There is error
    {
        return true;
    }
    else
    {
        return false;
    }
}
</code>```

答:
Where returns an iqueryable of Users. You need Any instead which Determines whether any element of a sequence satisfies a condition and since it's return type is bool you can use it in your if statement:

```<code>var query=database.Table<Users>().Any(i => i.UserName == userNameLogIn
                                           && i.Password == passwordLogIn);
</code>```

EDIT: Or use Any in your if:

```<code>var query=database.Table<Users>().Where(i => i.UserName == userNameLogIn
                                             && i.Password == passwordLogIn);
if (query.Any())
{
    return true;
}
</code>```

Title: Getting error in LINQ query to sqlite

Body:
I'm trying to make login query in sqlite but can't convert AsyncTableQuery in boolean

public bool queryLogIn(string userNameLogIn,string passwordLogIn)
{
    var query=database.Table<Users>().Where(i => i.UserName == userNameLogIn && i.Password == passwordLogIn);

    if (query == true)//There is error
    {
        return true;
    }
    else
    {
        return false;
    }
}

Body:
Where returns an iqueryable of Users. You need Any instead which Determines whether any element of a sequence satisfies a condition and since it's return type is bool you can use it in your if statement:

var query=database.Table<Users>().Any(i => i.UserName == userNameLogIn
                                           && i.Password == passwordLogIn);

EDIT: Or use Any in your if:

var query=database.Table<Users>().Where(i => i.UserName == userNameLogIn
                                             && i.Password == passwordLogIn);
if (query.Any())
{
    return true;
}


问:
smarty code - access variables inside {php} tag
I know we should avoid the {php} tag inside any template engine, still, let's assume that it's the only way on this case.

Considering this, I would like to request some help in order to grab smarty string for php consumption.

On this case, I would like to access $result.domain inside the srtstr php function.

What am I doing wrong?

```<code>{foreach key=period item=regoption from=$result.regoptions}
{if $regoption.$domain}
{if $domain eq "transfer"}
{php}
   $domainName = $result.domain;
   $tld = strstr($domainName, '.');
{/php}

{if $tld eq '.gt'}
   <p>Something</p>
{else}
<option value="{$period}">{$period} {$LANG.orderyears} @ {$regoption.$domain}</option>
{/if}
{/if}
{/if}
{/foreach}
</code>```

Thanks in advance,
MEM

答:
$this doesn't work for us, we finally got it using $GLOBALS variable like this:

```<code>$variable= $GLOBALS['smarty']->getTemplateVars('variable');
</code>```

Body:
I know we should avoid the {php} tag inside any template engine, still, let's assume that it's the only way on this case.

Considering this, I would like to request some help in order to grab smarty string for php consumption.

On this case, I would like to access $result.domain inside the srtstr php function.

What am I doing wrong?

{foreach key=period item=regoption from=$result.regoptions}
{if $regoption.$domain}
{if $domain eq "transfer"}
{php}
   $domainName = $result.domain;
   $tld = strstr($domainName, '.');
{/php}

{if $tld eq '.gt'}

Something

{else}
<option value="{$period}">{$period} {$LANG.orderyears} @ {$regoption.$domain}</option>
{/if}
{/if}
{/if}
{/foreach}

Thanks in advance,
MEM

Body:
$this doesn't work for us, we finally got it using $GLOBALS variable like this:

$variable= $GLOBALS['smarty']->getTemplateVars('variable');


问:
How to reverse a dummy variables from a pandas dataframe
I would like to reverse a dataframe with dummy variables. For example,

from df_input:

```<code>Course_01 Course_02 Course_03
  0           0         1
  1           0         0
  0           1         0
</code>```

To df_output

```<code>   Course
0 03
1 01
2 02
</code>```

I have been looking at the solution provided at Reconstruct a categorical variable from dummies in pandas but it did not work. Please, Any help would be much appreciated.

Many Thanks,
Best Regards,
Carlo

答:
You can use:

```<code>#create id to index if necessary
df = df.set_index('id')
#create MultiIndex
df.columns = df.columns.str.split('_', expand=True)
#reshape by stack and remove 0 rows
df = df.stack().reset_index().query('T != 0').drop('T',1).rename(columns={'level_1':'T'})
print (df)
    id   T
1  id1  40
2  id2  30
</code>```

EDIT:

```<code>col_name = 'Course'
df.columns = df.columns.str.split('_', expand=True)
df = (df.replace(0, np.nan)
        .stack()
        .reset_index()

        .drop([col_name, 'level_0'],1)
        .rename(columns={'level_1':col_name})
)
print (df)
  Course
0     03
1     01
2     02
</code>```

Body:
I would like to reverse a dataframe with dummy variables. For example,

from df_input:

Course_01 Course_02 Course_03
  0           0         1
  1           0         0
  0           1         0

To df_output

   Course
0 03
1 01
2 02

I have been looking at the solution provided at Reconstruct a categorical variable from dummies in pandas but it did not work. Please, Any help would be much appreciated.

Many Thanks,
Best Regards,
Carlo

Body:
You can use:

#create id to index if necessary
df = df.set_index('id')
#create MultiIndex
df.columns = df.columns.str.split('_', expand=True)
#reshape by stack and remove 0 rows
df = df.stack().reset_index().query('T != 0').drop('T',1).rename(columns={'level_1':'T'})
print (df)
    id   T
1  id1  40
2  id2  30

EDIT:

col_name = 'Course'
df.columns = df.columns.str.split('_', expand=True)
df = (df.replace(0, np.nan)
        .stack()
        .reset_index()

        .drop([col_name, 'level_0'],1)
        .rename(columns={'level_1':col_name})
)
print (df)
  Course
0     03
1     01
2     02


问:
APK size is bigger than expected - android studio
My project content size like this,

Main Project (Source & asset size 513KB)

Module 1 (Source & asset size 135KB)

Module 2 (Source & asset size 80KB)

And the apk (signed, debug both) size is 4.87MB. Also tried ProGuard nothing changed.

I do not understand the reason of this. Even I have not added any jar file to my project.

答:
In case of a large png files existed try to enable the AAPT and use the next:</p>

```<code>android {
    …
    buildTypes {
        release {
            crunchPngs true // or false
        }
    }
}
</code>```

Body:
In case of a large png files existed try to enable the AAPT and use the next:

android {
    …
    buildTypes {
        release {
            crunchPngs true // or false
        }
    }
}


问:
How to read data from excel file and create a graph using java or groovy
i'm trying to read data from excel and plot graph using java.

I keep getting the below error:

org.apache.poi.poifs.filesystem.OfficeXmlFileException: The supplied data appears to be in the Office 2007+ XML. You are calling the part of POI that deals with OLE2 Office Documents. You need to call a different part of POI to process this data (eg XSSF instead of HSSF)

Exception in thread "main" java.lang.NoClassDefFoundError: org/jfree/util/PublicCloneable

My code:

```<code>import java.io.*;
import java.util.*;
import org.jfree.data.*;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.plot.PlotOrientation;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.jfree.data.category.DefaultCategoryDataset;

    public class ReadExcel{
        public static void main(String[]args){
    short a=0;
    short b=1;
     int i=0;
    ArrayList<Integer> list1=new ArrayList<Integer>();
    ArrayList<Integer> list2=new ArrayList<Integer>();
        int   x=0, y=0;
       String filename ="C:\\Chart.xlsx";
        if(filename != null && !filename.equals("")){
        try{
        FileInputStream fs =new FileInputStream(filename);
        HSSFWorkbook wb = new HSSFWorkbook(fs);
        for(int k = 0; k < wb.getNumberOfSheets(); k++){
         int j=i+1;
         HSSFSheet sheet = wb.getSheetAt(k);
         int rows  = sheet.getPhysicalNumberOfRows();
         for(int r =     1; r < rows; r++){
         HSSFRow row   = sheet.getRow(r);
         int cells = row.getPhysicalNumberOfCells();
            HSSFCell cell1  = row.getCell(a);
            x =(int) cell1.getNumericCellValue();
            HSSFCell cell2  = row.getCell(b);
            y =(int) cell2.getNumericCellValue();

            list1.add(new Integer(x));
            list2.add(new Integer(y));
          }
          i++;
        }
}catch(Exception e){
    System.out.println(e);

 }

 }
 DefaultCategoryDataset dataset = new DefaultCategoryDataset();
  for(int j=0;j<list1.size();j++){
        dataset.setValue((double)list2.get(j), "Marks", list1.get(j).toString());
  }
        JFreeChart chart = ChartFactory.createBarChart("BarChart using JFreeChart","ID", "Marks", dataset,
        PlotOrientation.VERTICAL, false,true, false);
               try {
               ChartUtilities.saveChartAsJPEG(new File("C:\\chart.jpg"), chart,400, 300);
               } catch (IOException e) {
               System.out.println("Problem in creating chart.");
  }
 }
}
</code>```

Sample excel:

```<code>Response Time   Transaction Name    Runid
25                    Home           1
56                    Login          2
23                    Order          3
</code>```

i tried to use the XSSF Apache POI but no luck.

I also wanted to save the image of the chart somewhere locally.

答: NoClassDefFoundError means that the JVM is unable to find a class that you're using in your code. In a general way, it means you're missing a dependency in your classpath. Try adding this dependency to your project: https://mvnrepository.com/artifact/org.jfree/jcommon

Body:
i'm trying to read data from excel and plot graph using java.

I keep getting the below error:

org.apache.poi.poifs.filesystem.OfficeXmlFileException: The supplied data appears to be in the Office 2007+ XML. You are calling the part of POI that deals with OLE2 Office Documents. You need to call a different part of POI to process this data (eg XSSF instead of HSSF)

Exception in thread "main" java.lang.NoClassDefFoundError: org/jfree/util/PublicCloneable

My code:

import java.io.*;
import java.util.*;
import org.jfree.data.*;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.plot.PlotOrientation;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.jfree.data.category.DefaultCategoryDataset;

    public class ReadExcel{
        public static void main(String[]args){
    short a=0;
    short b=1;
     int i=0;
    ArrayList<Integer> list1=new ArrayList<Integer>();
    ArrayList<Integer> list2=new ArrayList<Integer>();
        int   x=0, y=0;
       String filename ="C:\\Chart.xlsx";
        if(filename != null && !filename.equals("")){
        try{
        FileInputStream fs =new FileInputStream(filename);
        HSSFWorkbook wb = new HSSFWorkbook(fs);
        for(int k = 0; k < wb.getNumberOfSheets(); k++){
         int j=i+1;
         HSSFSheet sheet = wb.getSheetAt(k);
         int rows  = sheet.getPhysicalNumberOfRows();
         for(int r =     1; r < rows; r++){
         HSSFRow row   = sheet.getRow(r);
         int cells = row.getPhysicalNumberOfCells();
            HSSFCell cell1  = row.getCell(a);
            x =(int) cell1.getNumericCellValue();
            HSSFCell cell2  = row.getCell(b);
            y =(int) cell2.getNumericCellValue();

            list1.add(new Integer(x));
            list2.add(new Integer(y));
          }
          i++;
        }
}catch(Exception e){
    System.out.println(e);

 }

 }
 DefaultCategoryDataset dataset = new DefaultCategoryDataset();
  for(int j=0;j<list1.size();j++){
        dataset.setValue((double)list2.get(j), "Marks", list1.get(j).toString());
  }
        JFreeChart chart = ChartFactory.createBarChart("BarChart using JFreeChart","ID", "Marks", dataset,
        PlotOrientation.VERTICAL, false,true, false);
               try {
               ChartUtilities.saveChartAsJPEG(new File("C:\\chart.jpg"), chart,400, 300);
               } catch (IOException e) {
               System.out.println("Problem in creating chart.");
  }
 }
}

Sample excel:

Response Time   Transaction Name    Runid
25                    Home           1
56                    Login          2
23                    Order          3

i tried to use the XSSF Apache POI but no luck.

I also wanted to save the image of the chart somewhere locally.


问:
What's the difference between SparkSession.sql and Dataset.sqlContext.sql?
I have the following snippets of the code and I wonder what is the difference between these two and which one should I use? I am using spark 2.2.

```<code>Dataset<Row> df = sparkSession.readStream()
    .format("kafka")
    .load();

df.createOrReplaceTempView("table");
df.printSchema();

Dataset<Row> resultSet =  df.sqlContext().sql("select value from table"); //sparkSession.sql(this.query);
StreamingQuery streamingQuery = resultSet
        .writeStream()
        .trigger(Trigger.ProcessingTime(1000))
        .format("console")
        .start();
</code>```

vs

```<code>Dataset<Row> df = sparkSession.readStream()
    .format("kafka")
    .load();

df.createOrReplaceTempView("table");

Dataset<Row> resultSet =  sparkSession.sql("select value from table"); //sparkSession.sql(this.query);
StreamingQuery streamingQuery = resultSet
        .writeStream()
        .trigger(Trigger.ProcessingTime(1000))
        .format("console")
        .start();
</code>```

答:
There is a very subtle difference between sparkSession.sql("sql query") vs df.sqlContext().sql("sql query").

Please note that you can have zero, two or more SparkSessions in a single Spark application (but it's assumed you'll have at least and often only one SparkSession in a Spark SQL application).

Please also note that a Dataset is bound to the SparkSession it was created within and the SparkSession will never change.

You may be wondering why anyone would want it, but that gives you boundary between queries and you could use the same table names for different datasets and that is a very powerful feature of Spark SQL actually.

The following example shows the difference and hopefully will give you some idea why it's powerful after all.

```<code>scala> spark.version
res0: String = 2.3.0-SNAPSHOT

scala> :type spark
org.apache.spark.sql.SparkSession

scala> spark.sql("show tables").show
+--------+---------+-----------+
|database|tableName|isTemporary|
+--------+---------+-----------+
+--------+---------+-----------+

scala> val df = spark.range(5)
df: org.apache.spark.sql.Dataset[Long] = [id: bigint]

scala> df.sqlContext.sql("show tables").show
+--------+---------+-----------+
|database|tableName|isTemporary|
+--------+---------+-----------+
+--------+---------+-----------+

scala> val anotherSession = spark.newSession
anotherSession: org.apache.spark.sql.SparkSession = org.apache.spark.sql.SparkSession@195c5803

scala> anotherSession.range(10).createOrReplaceTempView("new_table")

scala> anotherSession.sql("show tables").show
+--------+---------+-----------+
|database|tableName|isTemporary|
+--------+---------+-----------+
|        |new_table|       true|
+--------+---------+-----------+

scala> df.sqlContext.sql("show tables").show
+--------+---------+-----------+
|database|tableName|isTemporary|
+--------+---------+-----------+
+--------+---------+-----------+
</code>```

Body:
I have the following snippets of the code and I wonder what is the difference between these two and which one should I use? I am using spark 2.2.

Dataset<Row> df = sparkSession.readStream()
    .format("kafka")
    .load();

df.createOrReplaceTempView("table");
df.printSchema();

Dataset<Row> resultSet =  df.sqlContext().sql("select value from table"); //sparkSession.sql(this.query);
StreamingQuery streamingQuery = resultSet
        .writeStream()
        .trigger(Trigger.ProcessingTime(1000))
        .format("console")
        .start();

vs

Dataset<Row> df = sparkSession.readStream()
    .format("kafka")
    .load();

df.createOrReplaceTempView("table");

Dataset<Row> resultSet =  sparkSession.sql("select value from table"); //sparkSession.sql(this.query);
StreamingQuery streamingQuery = resultSet
        .writeStream()
        .trigger(Trigger.ProcessingTime(1000))
        .format("console")
        .start();

Body:
There is a very subtle difference between sparkSession.sql("sql query") vs df.sqlContext().sql("sql query").

Please note that you can have zero, two or more SparkSessions in a single Spark application (but it's assumed you'll have at least and often only one SparkSession in a Spark SQL application).

Please also note that a Dataset is bound to the SparkSession it was created within and the SparkSession will never change.

You may be wondering why anyone would want it, but that gives you boundary between queries and you could use the same table names for different datasets and that is a very powerful feature of Spark SQL actually.

The following example shows the difference and hopefully will give you some idea why it's powerful after all.

scala> spark.version
res0: String = 2.3.0-SNAPSHOT

scala> :type spark
org.apache.spark.sql.SparkSession

scala> spark.sql("show tables").show
+--------+---------+-----------+
|database|tableName|isTemporary|
+--------+---------+-----------+
+--------+---------+-----------+

scala> val df = spark.range(5)
df: org.apache.spark.sql.Dataset[Long] = [id: bigint]

scala> df.sqlContext.sql("show tables").show
+--------+---------+-----------+
|database|tableName|isTemporary|
+--------+---------+-----------+
+--------+---------+-----------+

scala> val anotherSession = spark.newSession
anotherSession: org.apache.spark.sql.SparkSession = org.apache.spark.sql.SparkSession@195c5803

scala> anotherSession.range(10).createOrReplaceTempView("new_table")

scala> anotherSession.sql("show tables").show
+--------+---------+-----------+
|database|tableName|isTemporary|
+--------+---------+-----------+
|        |new_table|       true|
+--------+---------+-----------+

scala> df.sqlContext.sql("show tables").show
+--------+---------+-----------+
|database|tableName|isTemporary|
+--------+---------+-----------+
+--------+---------+-----------+


问:
How will _Exit behave in a C++ program?
C99 offers the _Exit function, which exits "immediately", although it does may close file descriptors. Unix/POSIX extends this behavior by mandating the closing of all fd's without flushing (and offers the synonym _exit).

Will these functions call destructors for static objects when called from a C++ program? Does the C++ standard make any guarantees about _Exit?

(Inspired by this question; I suddenly wondered what happens in the typical fork-exec-_exit idiom in C++.)

答: Note that while C++ does not specify _Exit and C99 leaves it implementation-defined whether it flushes buffers, POSIX requires that it not flush buffers (since this would break the main usage of _exit/_Exit, i.e. handling failure of execve after fork). As POSIX does not align itself with C++ standards or defer to them on anything, I think it's very unlikely that a future version of the C++ standard would try to change any of this. It will probably either leave _Exit unspecified or specify that it's implementation-defined.

Title: How will _Exit behave in a C++ program?