问:
Simultaneous Users in a Google Apps Script Web App
I have a scoreboard web app that would keep track of the score for 2 teams.  How can I make it to where multiple users can use the app simultaneously and both teams can see the same score?  Currently, if I have 2 instances of the app open in a browser they will not reflect the same score when one is incremented.

document.addEventListener('DOMContentLoaded', function() {
    document.getElementById("btn-sub-1").addEventListener("click", function() {
      Counter('s1');
    }, false);
    document.getElementById("btn-add-1").addEventListener("click", function() {
      Counter('a1');
    }, false);
    document.getElementById("btn-sub-2").addEventListener("click", function() {
      Counter('s2');
    }, false);
    document.getElementById("btn-add-2").addEventListener("click", function() {
      Counter('a2');
    }, false);
  });
  function Counter(val) {
    var score_1 = parseInt(document.getElementById("lbl-score-1").innerHTML);
    var score_2 = parseInt(document.getElementById("lbl-score-2").innerHTML);

    if (val=='s1' && score_1>0) {
      score_1--;
      document.getElementById("lbl-score-1").innerHTML = score_1;
    } else if (val=='a1') {
      score_1++;
      document.getElementById("lbl-score-1").innerHTML = score_1;
    } else if (val=='s2' && score_2>0) {
      score_2--;
      document.getElementById("lbl-score-2").innerHTML = score_2;
    } else if (val=='a2') {
      score_2++;
      document.getElementById("lbl-score-2").innerHTML = score_2;
    }

  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
  <head>
    <base target="_top">

    <!--Import Google Icon Font-->
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

    <!--Import materialize.css-->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

    <!--Let browser know website is optimized for mobile-->
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>

    <?!= include("8-general-css"); ?>
    <?!= include("8-landscape-css"); ?>
    <?!= include("8-portrait-css"); ?>

  </head>
  <body>

    <div class="grid-container">
      <div class="team-1-container">
        <label class="lbl-team blk-text font-header" id="lbl-team-1">Team 1</label>
      </div>
      <div class="player-1-container">
        <select class="browser-default player-select font-opt" id="player-opt-1">
          <option value="" disabled selected>Player 1</option>
          <?!= players;?>
        </select>
      </div>
      <div class="stats-1-container">
        <div class="lbl-elo-container">
          <label class="lbl-elo blk-text font-stats" id="lbl-elo-1">ELO: </label>
          <label class="lbl-elo-val blk-text font-stats" id="lbl-elo-val-1">-</label>
        </div>
        <div class="lbl-win-container">
          <label class="lbl-win blk-text font-stats" id="lbl-win-1">Win Prob: </label>
          <label class="lbl-win-val blk-text font-stats" id="lbl-win-val-1">-%</label>
        </div>
      </div>
      <div class="player-3-container">
        <select class="browser-default player-select font-opt" id="player-opt-3">
          <option value="">Player 3</option>
          <?!= players;?>
        </select>
      </div>
      <div class="sub-1-container">
        <button class="btn-sub font-btn" id="btn-sub-1"><span>-</span></button>
      </div>
      <div class="score-1-container">
        <label class="lbl-score blk-text font-score" id="lbl-score-1">0</label>
      </div>
      <div class="add-1-container">
        <button class="btn-add font-btn" id="btn-add-1">+</button>
      </div>
      <div class="reset-container">
        <button class="btn-reset-submit font-reset-submit" id="btn-reset">Reset</button>
      </div>
      <div class="submit-container">
        <button class="btn-reset-submit font-reset-submit" id="btn-submit">Submit</button>
      </div>
      <div class="sub-2-container">
        <button class="btn-sub font-btn" id="btn-sub-2">-</button>
      </div>
      <div class="score-2-container">
        <label class="lbl-score blk-text font-score" id="lbl-score-2">0</label>
      </div>
      <div class="add-2-container">
        <button class="btn-add font-btn" id="btn-add-2">+</button>
      </div>
      <div class="player-2-container">
        <select class="browser-default player-select font-opt" id="player-opt-2">
          <option value="" disabled selected>Player 2</option>
          <?!= players;?>
        </select>
      </div>
      <div class="stats-2-container">
        <div class="lbl-elo-container">
          <label class="lbl-elo blk-text font-stats" id="lbl-elo-2">ELO: </label>
          <label class="lbl-elo-val blk-text font-stats" id="lbl-elo-val-2">-</label>
        </div>
        <div class="lbl-win-container">
          <label class="lbl-win blk-text font-stats" id="lbl-win-2">Win Prob: </label>
          <label class="lbl-win-val blk-text font-stats" id="lbl-win-val-2">-%</label>
        </div>
      </div>
      <div class="player-4-container">
        <select class="browser-default player-select font-opt" id="player-opt-4">
          <option value="">Player 4</option>
          <?!= players;?>
        </select>
      </div>
      <div class="team-2-container">
        <label class="lbl-team blk-text font-header" id="lbl-team-2">Team 2</label>
      </div>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>

    <?!= include("8-ball-js"); ?>
    <?!= include("8-ball-swipe-score"); ?>

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

答:
All of your event Listeners point to this function.

```<code>function Counter(val) {
    var score_1 = parseInt(document.getElementById("lbl-score-1").innerHTML);
    var score_2 = parseInt(document.getElementById("lbl-score-2").innerHTML);
    if (val=='s1' && score_1>0) {
      score_1--;
      document.getElementById("lbl-score-1").innerHTML = score_1;
    } else if (val=='a1') {
      score_1++;
      document.getElementById("lbl-score-1").innerHTML = score_1;
    } else if (val=='s2' && score_2>0) {
      score_2--;
      document.getElementById("lbl-score-2").innerHTML = score_2;
    } else if (val=='a2') {
      score_2++;
      document.getElementById("lbl-score-2").innerHTML = score_2;
    }

  }
</code>```

But the function is not communicating with the server via google.script.run. And there are no forms for a submission. How do you expect the server to do anything if you don't communicate with it?

Body:
I have a scoreboard web app that would keep track of the score for 2 teams.  How can I make it to where multiple users can use the app simultaneously and both teams can see the same score?  Currently, if I have 2 instances of the app open in a browser they will not reflect the same score when one is incremented.

document.addEventListener('DOMContentLoaded', function() {
    document.getElementById("btn-sub-1").addEventListener("click", function() {
      Counter('s1');
    }, false);
    document.getElementById("btn-add-1").addEventListener("click", function() {
      Counter('a1');
    }, false);
    document.getElementById("btn-sub-2").addEventListener("click", function() {
      Counter('s2');
    }, false);
    document.getElementById("btn-add-2").addEventListener("click", function() {
      Counter('a2');
    }, false);
  });
  function Counter(val) {
    var score_1 = parseInt(document.getElementById("lbl-score-1").innerHTML);
    var score_2 = parseInt(document.getElementById("lbl-score-2").innerHTML);

    if (val=='s1' && score_1>0) {
      score_1--;
      document.getElementById("lbl-score-1").innerHTML = score_1;
    } else if (val=='a1') {
      score_1++;
      document.getElementById("lbl-score-1").innerHTML = score_1;
    } else if (val=='s2' && score_2>0) {
      score_2--;
      document.getElementById("lbl-score-2").innerHTML = score_2;
    } else if (val=='a2') {
      score_2++;
      document.getElementById("lbl-score-2").innerHTML = score_2;
    }

  }

<!DOCTYPE html>

    <base target="_top">

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

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>

    <?!= include("8-general-css"); ?>
    <?!= include("8-landscape-css"); ?>
    <?!= include("8-portrait-css"); ?>

        Team 1

        <select class="browser-default player-select font-opt" id="player-opt-1">
          <option value="" disabled selected>Player 1</option>
          <?!= players;?>
        </select>

          ELO:
          -

          Win Prob:
          -%

        <select class="browser-default player-select font-opt" id="player-opt-3">
          <option value="">Player 3</option>
          <?!= players;?>
        </select>

        <button class="btn-sub font-btn" id="btn-sub-1">-</button>

        0

        <button class="btn-add font-btn" id="btn-add-1">+</button>

        <button class="btn-reset-submit font-reset-submit" id="btn-reset">Reset</button>

        <button class="btn-reset-submit font-reset-submit" id="btn-submit">Submit</button>

        <button class="btn-sub font-btn" id="btn-sub-2">-</button>

        0

        <button class="btn-add font-btn" id="btn-add-2">+</button>

        <select class="browser-default player-select font-opt" id="player-opt-2">
          <option value="" disabled selected>Player 2</option>
          <?!= players;?>
        </select>

          ELO:
          -

          Win Prob:
          -%

        <select class="browser-default player-select font-opt" id="player-opt-4">
          <option value="">Player 4</option>
          <?!= players;?>
        </select>

        Team 2

    <?!= include("8-ball-js"); ?>
    <?!= include("8-ball-swipe-score"); ?>

Body:
All of your event Listeners point to this function.

function Counter(val) {
    var score_1 = parseInt(document.getElementById("lbl-score-1").innerHTML);
    var score_2 = parseInt(document.getElementById("lbl-score-2").innerHTML);
    if (val=='s1' && score_1>0) {
      score_1--;
      document.getElementById("lbl-score-1").innerHTML = score_1;
    } else if (val=='a1') {
      score_1++;
      document.getElementById("lbl-score-1").innerHTML = score_1;
    } else if (val=='s2' && score_2>0) {
      score_2--;
      document.getElementById("lbl-score-2").innerHTML = score_2;
    } else if (val=='a2') {
      score_2++;
      document.getElementById("lbl-score-2").innerHTML = score_2;
    }

  }

But the function is not communicating with the server via google.script.run. And there are no forms for a submission. How do you expect the server to do anything if you don't communicate with it?


来源: stackexchange

问:
How can I get 3 divs in one line? Flex not working
I'm trying to put all 3 divs next to each other but it is not happening. I want to align them in one row and have equal spacing between them.

Flex display is not working.

Any idea why is it not working and how can I get all 3 divs in one line?

.package{
 border: solid 1px black;
 display: flex;
 flex-flow: row wrap;
 height: 500px;
 width: 380px;
 text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h2 class="packages">PACKAGES</h2>
    <div class="package">

    </div>
    <div class="package">

    </div>
    <div class="package">

    </div></code>```

HTML CODE

```<code><h2 class="packages">PACKAGES</h2>
            <div class="package">

            </div>
            <div class="package">

            </div>
            <div class="package">

            </div>
</code>```

CSS CODE

```<code>.package{
border: solid 1px black;
display: flex;
flex-flow: row wrap;
height: 500px;
width: 380px;
text-align: center;
</code>```

}

OUTPUT

答:
Your container needs to be display Flex. Like so:

.package-container {
  display: flex;
  flex-flow: row wrap;
}

.package {
  border: solid 1px black;
  height: 500px;
  width: 380px;
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h2 class="packages">PACKAGES</h2>
<div class="package-container">
  <div class="package">1</div>
  <div class="package">2</div>
  <div class="package">3</div>
</div></code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to put all 3 divs next to each other but it is not happening. I want to align them in one row and have equal spacing between them.

Flex display is not working.

Any idea why is it not working and how can I get all 3 divs in one line?

.package{
 border: solid 1px black;
 display: flex;
 flex-flow: row wrap;
 height: 500px;
 width: 380px;
 text-align: center;
}

PACKAGES

HTML CODE

PACKAGES

CSS CODE

.package{
border: solid 1px black;
display: flex;
flex-flow: row wrap;
height: 500px;
width: 380px;
text-align: center;

}

OUTPUT

Body:
Your container needs to be display Flex. Like so:

.package-container {
  display: flex;
  flex-flow: row wrap;
}

.package {
  border: solid 1px black;
  height: 500px;
  width: 380px;
  text-align: center;
}

<h2 class="packages">PACKAGES</h2>
<div class="package-container">
  <div class="package">1</div>
  <div class="package">2</div>
  <div class="package">3</div>
</div>


问:
How to construct a person class that allows tracking of property values over time
I'd like to construct a person class that has a property which the value may change over time but I want to keep the history of values. A person grows taller over time and their weight may change.  You may imagine a "HockeyPlayer: Person" that plays over many seasons.  Each season their height/weight may be different.  I would then use EntityFramework to create tables.  I think the main question I have is where do I put those properties? In their own class? In HockeyPlayer?  In Person?  Thank you in advance

pseudocode example:

```<code>public class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public System.DateTime DateOfBirth { get; set; }
}

public class Season
{
    public int Id { get; set; }
    public string season { get; set; }
}

public class HockeyPlayer : Person
{
    public int PersonId {get; set; }
    public int SeasonId { get; set; }
    public int JerseyNumber { get; set; }
    public int HeightInches { get; set; }
    public int WeightPounds { get; set; }
}
</code>```

答: One way would be to create a separate table with  height, weight and date columns with player Id as a secondary key. Call this table PhysicalStats for example. Your HockeyPlayer would have a list of PhysicalStats rather than just single height/ weight properties as they do currently. </p>

Body:
I'd like to construct a person class that has a property which the value may change over time but I want to keep the history of values. A person grows taller over time and their weight may change.  You may imagine a "HockeyPlayer: Person" that plays over many seasons.  Each season their height/weight may be different.  I would then use EntityFramework to create tables.  I think the main question I have is where do I put those properties? In their own class? In HockeyPlayer?  In Person?  Thank you in advance

pseudocode example:

public class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public System.DateTime DateOfBirth { get; set; }
}

public class Season
{
    public int Id { get; set; }
    public string season { get; set; }
}

public class HockeyPlayer : Person
{
    public int PersonId {get; set; }
    public int SeasonId { get; set; }
    public int JerseyNumber { get; set; }
    public int HeightInches { get; set; }
    public int WeightPounds { get; set; }
}


问:
Guava Maps.difference on Scala maps
trying to do the below but, getting a overloaded method value differences with alternatives: cannot be applied to java.util.Map[String, Any]

```<code>
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.google.common.collect.Maps

import scala.collection.JavaConverters._

object Testing extends App {

  val leftJson = """{
    "name": {
      "first": "John",
      "last": "Doe"
    },
    "address": null,
    "birthday": "1980-01-01",
    "company": "Acme",
    "occupation": "Software engineer",
    "phones": [
    {
      "number": "000000000",
      "type": "home"
    },
    {
      "number": "999999999",
      "type": "mobile"
    }
    ]
  }"""
  val rightJson = """{
    "name": {
      "first": "Jane",
      "last": "Doe",
      "nickname": "Jenny"
    },
    "birthday": "1990-01-01",
    "occupation": null,
    "phones": [
    {
      "number": "111111111",
      "type": "mobile"
    }
    ],
    "favorite": true,
    "groups": [
    "close-friends",
    "gym"
    ]
  }"""

  val mapper = new ObjectMapper
  mapper.registerModule(DefaultScalaModule)
  val leftMap = mapper.readValue(leftJson, classOf[Map[String, Any]])
  val rightMap = mapper.readValue(rightJson, classOf[Map[String, Any]])

  val differences = Maps.difference(leftMap.asJava, rightMap.asJava)

}
</code>```

```<code>Error:(59, 26) overloaded method value difference with alternatives:
  [K, V](x$1: java.util.SortedMap[K, _ <: V], x$2: java.util.Map[_ <: K, _ <: V])com.google.common.collect.SortedMapDifference[K,V] <and>
  [K, V](x$1: java.util.Map[_ <: K, _ <: V], x$2: java.util.Map[_ <: K, _ <: V], x$3: com.google.common.base.Equivalence[_ >: V])com.google.common.collect.MapDifference[K,V] <and>
  [K, V](x$1: java.util.Map[_ <: K, _ <: V], x$2: java.util.Map[_ <: K, _ <: V])com.google.common.collect.MapDifference[K,V]
 cannot be applied to (java.util.Map[String,Object], java.util.Map[String,Object])
  val differences = Maps.difference(leftMap.asJava, rightMap.asJava)
</code>```

答:
The good news is that your code compiles correctly using Scala 2.13.1.

I also tried compiling your code using Scala 2.12.10 and indeed the problems shows up.

The problem gets solved if you hint the type parameters to the compiler:

```<code>val differences = Maps.difference[String, Any](leftMap.asJava, rightMap.asJava)
</code>```

Title: Guava Maps.difference on Scala maps

Body:
trying to do the below but, getting a overloaded method value differences with alternatives: cannot be applied to java.util.Map[String, Any]

import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.google.common.collect.Maps

import scala.collection.JavaConverters._

object Testing extends App {

  val leftJson = """{
    "name": {
      "first": "John",
      "last": "Doe"
    },
    "address": null,
    "birthday": "1980-01-01",
    "company": "Acme",
    "occupation": "Software engineer",
    "phones": [
    {
      "number": "000000000",
      "type": "home"
    },
    {
      "number": "999999999",
      "type": "mobile"
    }
    ]
  }"""
  val rightJson = """{
    "name": {
      "first": "Jane",
      "last": "Doe",
      "nickname": "Jenny"
    },
    "birthday": "1990-01-01",
    "occupation": null,
    "phones": [
    {
      "number": "111111111",
      "type": "mobile"
    }
    ],
    "favorite": true,
    "groups": [
    "close-friends",
    "gym"
    ]
  }"""

  val mapper = new ObjectMapper
  mapper.registerModule(DefaultScalaModule)
  val leftMap = mapper.readValue(leftJson, classOf[Map[String, Any]])
  val rightMap = mapper.readValue(rightJson, classOf[Map[String, Any]])

  val differences = Maps.difference(leftMap.asJava, rightMap.asJava)

}

Error:(59, 26) overloaded method value difference with alternatives:
  [K, V](x$1: java.util.SortedMap[K, _ <: V], x$2: java.util.Map[_ <: K, _ <: V])com.google.common.collect.SortedMapDifference[K,V] <and>
  [K, V](x$1: java.util.Map[_ <: K, _ <: V], x$2: java.util.Map[_ <: K, _ <: V], x$3: com.google.common.base.Equivalence[_ >: V])com.google.common.collect.MapDifference[K,V] <and>
  [K, V](x$1: java.util.Map[_ <: K, _ <: V], x$2: java.util.Map[_ <: K, _ <: V])com.google.common.collect.MapDifference[K,V]
 cannot be applied to (java.util.Map[String,Object], java.util.Map[String,Object])
  val differences = Maps.difference(leftMap.asJava, rightMap.asJava)

Body:
The good news is that your code compiles correctly using Scala 2.13.1.

I also tried compiling your code using Scala 2.12.10 and indeed the problems shows up.

The problem gets solved if you hint the type parameters to the compiler:

val differences = Maps.difference[String, Any](leftMap.asJava, rightMap.asJava)


问:
How succesfully push my node app to Heroku?
I created my react app and am trying second day to push it to Heroku with git push Heroku master. I get an error. I tried all the common solutions from Heroku support and stackoverflow. I must be missing some crutial part. Can anybody please help me? This is what Heroku logs show:

```<code>Installing dependencies
       Installing node modules (package.json + package-lock)

       > node@13.8.0 preinstall /tmp/build_0b181828458420237db1b578ab12a219/node_modules/node
       > node installArchSpecificPackage

       npm ERR! code ETARGET
       npm ERR! notarget No matching version found for node-linux-x64@13.8.0.
       npm ERR! notarget In most cases you or one of your dependencies are requesting
       npm ERR! notarget a package version that doesn't exist.

       npm ERR! A complete log of this run can be found in:
       npm ERR!     /tmp/npmcache.TaYmU/_logs/2020-02-19T18_52_08_718Z-debug.log
       internal/modules/cjs/loader.js:796
           throw err;
           ^

       Error: Cannot find module 'node-linux-x64/package.json'
       Require stack:
       - /tmp/build_0b181828458420237db1b578ab12a219/node_modules/node/installArchSpecificPackage.js
           at Function.Module._resolveFilename (internal/modules/cjs/loader.js:793:17)
           at Function.resolve (internal/modules/cjs/helpers.js:80:19)
           at ChildProcess.<anonymous> (/tmp/build_0b181828458420237db1b578ab12a219/node_modules/node-bin-setup/index.js:18:27)
           at ChildProcess.emit (events.js:223:5)
           at maybeClose (internal/child_process.js:1021:16)
           at Process.ChildProcess._handle.onexit (internal/child_process.js:283:5) {
         code: 'MODULE_NOT_FOUND',
         requireStack: [
           '/tmp/build_0b181828458420237db1b578ab12a219/node_modules/node/installArchSpecificPackage.js'
         ]
       }
       npm ERR! code ELIFECYCLE
       npm ERR! errno 1
       npm ERR! node@13.8.0 preinstall: `node installArchSpecificPackage`
       npm ERR! Exit status 1
       npm ERR!
       npm ERR! Failed at the node@13.8.0 preinstall script.
       npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

       npm ERR! A complete log of this run can be found in:
       npm ERR!     /tmp/npmcache.TaYmU/_logs/2020-02-19T18_52_10_684Z-debug.log
-----> Build failed

       We're sorry this build is failing! You can troubleshoot common issues here:
       https://devcenter.heroku.com/articles/troubleshooting-node-deploys

       Some possible problems:

       - A module may be missing from 'dependencies' in package.json
         https://devcenter.heroku.com/articles/troubleshooting-node-deploys#ensure-you-aren-t-relying-on-untracked-dependencies

       Love,
       Heroku

 !     Push rejected, failed to compile React.js (create-react-app) multi app.
 !     Push failed

</code>```

Thank you!!!

答: Solved it! The solution was to delete node dependence from package.json. </p>

Body:
I created my react app and am trying second day to push it to Heroku with git push Heroku master. I get an error. I tried all the common solutions from Heroku support and stackoverflow. I must be missing some crutial part. Can anybody please help me? This is what Heroku logs show:

Installing dependencies
       Installing node modules (package.json + package-lock)

       > node@13.8.0 preinstall /tmp/build_0b181828458420237db1b578ab12a219/node_modules/node
       > node installArchSpecificPackage

       npm ERR! code ETARGET
       npm ERR! notarget No matching version found for node-linux-x64@13.8.0.
       npm ERR! notarget In most cases you or one of your dependencies are requesting
       npm ERR! notarget a package version that doesn't exist.

       npm ERR! A complete log of this run can be found in:
       npm ERR!     /tmp/npmcache.TaYmU/_logs/2020-02-19T18_52_08_718Z-debug.log
       internal/modules/cjs/loader.js:796
           throw err;
           ^

       Error: Cannot find module 'node-linux-x64/package.json'
       Require stack:
       - /tmp/build_0b181828458420237db1b578ab12a219/node_modules/node/installArchSpecificPackage.js
           at Function.Module._resolveFilename (internal/modules/cjs/loader.js:793:17)
           at Function.resolve (internal/modules/cjs/helpers.js:80:19)
           at ChildProcess.<anonymous> (/tmp/build_0b181828458420237db1b578ab12a219/node_modules/node-bin-setup/index.js:18:27)
           at ChildProcess.emit (events.js:223:5)
           at maybeClose (internal/child_process.js:1021:16)
           at Process.ChildProcess._handle.onexit (internal/child_process.js:283:5) {
         code: 'MODULE_NOT_FOUND',
         requireStack: [
           '/tmp/build_0b181828458420237db1b578ab12a219/node_modules/node/installArchSpecificPackage.js'
         ]
       }
       npm ERR! code ELIFECYCLE
       npm ERR! errno 1
       npm ERR! node@13.8.0 preinstall: `node installArchSpecificPackage`
       npm ERR! Exit status 1
       npm ERR!
       npm ERR! Failed at the node@13.8.0 preinstall script.
       npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

       npm ERR! A complete log of this run can be found in:
       npm ERR!     /tmp/npmcache.TaYmU/_logs/2020-02-19T18_52_10_684Z-debug.log
-----> Build failed

       We're sorry this build is failing! You can troubleshoot common issues here:
       https://devcenter.heroku.com/articles/troubleshooting-node-deploys

       Some possible problems:

       - A module may be missing from 'dependencies' in package.json
         https://devcenter.heroku.com/articles/troubleshooting-node-deploys#ensure-you-aren-t-relying-on-untracked-dependencies

       Love,
       Heroku

 !     Push rejected, failed to compile React.js (create-react-app) multi app.
 !     Push failed

Thank you!!!


问:
Check if a set of points described a triangle

I tried to solve this question but couldn't find a simple solution without passing all rows and find which numbers are on the same line.

Is there a simple way to find triangles?

this is my solution for finding a triangle:

How can I change it to be more "pythonic"? (or even better method for solving it)

```<code>from sympy.solvers import solve
from sympy import Symbol
from collections import Counter

vals = [8,17,19] # the triangle
dicl = []   #list of dics
for v in vals:
    dic = {}
    dic['val'] = v
    v1 = v
    done = 0
    stepsb = 0
    while done == 0:  #going backword untill reaching the big triabgle edges
        x = Symbol('x')
        k = solve((x**2 + x)/2 +1 - v1, x)
        k = list(filter(lambda x:x>0, k))
        if k[0]%1 == 0:
            done = 1
        else:
            v1 -= 1
            stepsb += 1

    dic['line'] = k[0]
    dic['stepsb'] = stepsb  #dist from the left edge
    dic['stepsf'] = (k[0]**2 + 3*k[0] + 2)/2 - v  #dist from the right edge
    dicl.append(dic)
    print(dic)

lines = [l['line'] for l in dicl]
mc = Counter(lines).most_common(1)[0][0]   #finding the numbers on the same line

minv = min([l['val'] for l in dicl if l['line'] == mc])
maxv = max([l['val'] for l in dicl if l['line'] == mc])
stb = [l['stepsb'] for l in dicl if l['val'] == minv][0]
stf = [l['stepsf'] for l in dicl if l['val'] == maxv][0]
for k in dicl:
    if k['stepsb'] == stb and k['stepsf'] == stf:
        print("good")
        break
</code>```

答:
A first step could be to search for a formula that translates the one-dimensional point number t to an x,y coordinate.

So, search for an n such that n*(n+1)/2 < t:

```<code>from sympy import solve, Eq
from sympy.abc import n, t

f = Eq(n * (n + 1), 2 * t)
print(solve(f, n))
</code>```

This shows as positive root: (sqrt(8*t + 1) - 1)/2.
To be strict smaller, a formula that copes with small approximation errors, could be:

```<code>floor((sqrt(8*t + 1) - 1)/2 - 0.0000001
</code>```

The following idea is, given a list of indices:

convert them to xy coordinates

find their center (sum and divide by the length of the list)

find the distances of each xy to the center

check that all distances are equal

To convert to an xy position, note that the height of an equilateral triangle with base 1 is sqrt(3)/2, so the distances between the y-positions should be multiplied by that factor.  The x-positions need to be centered which can be achieved by subtracting n/2.

import math

def find_xy(t):
    # convert the numerical position into an xy coordinate in the plane
    # first find largest n such that n*(n+1)/2 < t
    n = math.floor((math.sqrt(8 * t + 1) - 1) / 2 - 0.0000001)
    return (n + 1) * math.sqrt(3) / 2, t - n * (n + 1) // 2 - n/2

def sq_dist(p, q):
    return (p[0] - q[0]) ** 2 + (p[1] - q[1]) ** 2

def center(points):
    # find the center of a list of points
    l = len(points)
    x = sum(p[0] for p in points)
    y = sum(p[1] for p in points)
    return x / l, y / l

def is_regular(tri_points):
    points = [find_xy(t) for t in tri_points]
    cent = center(points)
    dists = [sq_dist(cent, p) for p in points]
    return max(dists) - min(dists) < 0.000001
```

<p>Note that this code finds geometric figures for which all the points lie on a circle. This doesn't work for the parallelogram. The actual question also has some extra criteria: all edges should follow the grid lines, and all edges need to be equal in length.</p>

<p>Therefore, it is useful to have 3 coordinates for each point: the row, the column and the diagonal (the 3 directions of the grid).</p>

<p>The length in each direction, is just the maximum minus the minimum for that direction. These lengths are called <code>d_r</code>, <code>d_c</code> and <code>d_d</code> in the code below.</p>

<p>Checking for a valid triangle, the 3 lengths need to be equal. One way to check this, is to check that the minimum of the lengths is equal to the maximum.</p>

<p>For a valid parallelogram, two lengths need to be equal, and the third should be the double. Checking that the maximum length is twice the minimum length should cover this. But, because this can already be reached using 3 points, we should also check that for a given direction, there are exactly 2 points at the minimum and 2 at the maximum. Summing all points and comparing twice the sum of maximum and minimum should accomplish this.</p>

<p>For a valid hexagon, the 3 lengths should be equal. So, the same test as for the triangle: the minimum of the lengths equal to the maximum. And also the test on the sums is needed, as 4 points can already fulfil the length conditions.</p>

<pre class="lang-py prettyprint-override"><code>import math

def find_row_col_diag(t):
    # convert the numerical position into an row,col,diag coordinate in the plane
    # first find largest n such that n*(n+1)/2 < t
    n = math.floor((math.sqrt(8 * t + 1) - 1) / 2 - 0.0000001)
    row, col = n + 1, t - n * (n + 1) // 2
    return row, col, row - col

def check_valid_figure(tri_points):
    points = [find_row_col_diag(t) for t in tri_points]
    rs = [r for (r, c, d) in points]
    cs = [c for (r, c, d) in points]
    ds = [d for (r, c, d) in points]
    sum_r = sum(rs)
    min_r = min(rs)
    max_r = max(rs)
    d_r = max_r - min_r
    sum_c = sum(cs)
    min_c = min(cs)
    max_c = max(cs)
    d_c = max_c - min_c
    sum_d = sum(ds)
    min_d = min(ds)
    max_d = max(ds)
    d_d = max_d - min_d
    if len(points) == 3:
        is_ok = max(d_r, d_c, d_d) == min(d_r, d_c, d_d)
    elif len(points) == 4:
        is_ok = max(d_r, d_c, d_d) == 2 * min(d_r, d_c, d_d) \
                and sum_r == 2 * (min_r + max_r) and sum_c == 2 * (min_c + max_c) and sum_d == 2 * (min_d + max_d)
    elif len(points) == 6:
        is_ok = max(d_r, d_c, d_d) == min(d_r, d_c, d_d) \
                and len(set(rs)) == 3 and len(set(cs)) == 3 and len(set(ds)) == 3
    else:
        is_ok = False
    print(" ".join([str(t) for t in tri_points]), end=" ")
    if is_ok:
        print("are the vertices of a",
              "triangle" if len(points) == 3 else "parallelogram" if len(points) == 4 else "hexagon")
    else:
        print("are not the vertices of an acceptable figure")

tri_point_lists = [[1, 2, 3],
                   [11, 13, 22, 24],
                   [11, 13, 29, 31],
                   [11, 13, 23, 25],
                   [26, 11, 13, 24],
                   [22, 23, 30],
                   [4, 5, 9, 13, 12, 7]]
for lst in tri_point_lists:
    check_valid_figure(lst)
</code>```

The last code can be further compressed using list comprehensions:

def check_valid_figure_bis(tri_points):
    points = [find_row_col_diag(t) for t in tri_points]
    rs, cs, ds = [[p[i] for p in points] for i in range(3)]
    sums = [sum(xs) for xs in (rs, cs, ds)]
    mins = [min(xs) for xs in (rs, cs, ds)]
    maxs = [max(xs) for xs in (rs, cs, ds)]
    lens = [ma - mi for mi, ma in zip(mins, maxs)]
    if len(points) == 3:
        is_ok = max(lens) == min(lens)
    elif len(points) == 4:
        is_ok = max(lens) == 2 * min(lens) and all([su == 2 * (mi + ma) for su, mi, ma in zip(sums, mins, maxs)])
    elif len(points) == 6:
        is_ok = max(lens) == min(lens) and all([len(set(xs)) == 3 for xs in (rs, cs, ds)])
    else:
        is_ok = False
    return is_ok
```

Body:
I tried to solve this question but couldn't find a simple solution without passing all rows and find which numbers are on the same line.

Is there a simple way to find triangles?

this is my solution for finding a triangle:

How can I change it to be more "pythonic"? (or even better method for solving it)

from sympy.solvers import solve
from sympy import Symbol
from collections import Counter

vals = [8,17,19] # the triangle
dicl = []   #list of dics
for v in vals:
    dic = {}
    dic['val'] = v
    v1 = v
    done = 0
    stepsb = 0
    while done == 0:  #going backword untill reaching the big triabgle edges
        x = Symbol('x')
        k = solve((x**2 + x)/2 +1 - v1, x)
        k = list(filter(lambda x:x>0, k))
        if k[0]%1 == 0:
            done = 1
        else:
            v1 -= 1
            stepsb += 1

    dic['line'] = k[0]
    dic['stepsb'] = stepsb  #dist from the left edge
    dic['stepsf'] = (k[0]**2 + 3*k[0] + 2)/2 - v  #dist from the right edge
    dicl.append(dic)
    print(dic)

lines = [l['line'] for l in dicl]
mc = Counter(lines).most_common(1)[0][0]   #finding the numbers on the same line

minv = min([l['val'] for l in dicl if l['line'] == mc])
maxv = max([l['val'] for l in dicl if l['line'] == mc])
stb = [l['stepsb'] for l in dicl if l['val'] == minv][0]
stf = [l['stepsf'] for l in dicl if l['val'] == maxv][0]
for k in dicl:
    if k['stepsb'] == stb and k['stepsf'] == stf:
        print("good")
        break

Body:
A first step could be to search for a formula that translates the one-dimensional point number t to an x,y coordinate.

So, search for an n such that n*(n+1)/2 < t:

from sympy import solve, Eq
from sympy.abc import n, t

f = Eq(n * (n + 1), 2 * t)
print(solve(f, n))

This shows as positive root: (sqrt(8*t + 1) - 1)/2.
To be strict smaller, a formula that copes with small approximation errors, could be:

floor((sqrt(8*t + 1) - 1)/2 - 0.0000001

The following idea is, given a list of indices:

convert them to xy coordinates

find their center (sum and divide by the length of the list)

find the distances of each xy to the center

check that all distances are equal

To convert to an xy position, note that the height of an equilateral triangle with base 1 is sqrt(3)/2, so the distances between the y-positions should be multiplied by that factor.  The x-positions need to be centered which can be achieved by subtracting n/2.

import math

def find_xy(t):
    # convert the numerical position into an xy coordinate in the plane
    # first find largest n such that n*(n+1)/2 < t
    n = math.floor((math.sqrt(8 * t + 1) - 1) / 2 - 0.0000001)
    return (n + 1) * math.sqrt(3) / 2, t - n * (n + 1) // 2 - n/2

def sq_dist(p, q):
    return (p[0] - q[0]) ** 2 + (p[1] - q[1]) ** 2

def center(points):
    # find the center of a list of points
    l = len(points)
    x = sum(p[0] for p in points)
    y = sum(p[1] for p in points)
    return x / l, y / l

def is_regular(tri_points):
    points = [find_xy(t) for t in tri_points]
    cent = center(points)
    dists = [sq_dist(cent, p) for p in points]
    return max(dists) - min(dists) < 0.000001

Note that this code finds geometric figures for which all the points lie on a circle. This doesn't work for the parallelogram. The actual question also has some extra criteria: all edges should follow the grid lines, and all edges need to be equal in length.

Therefore, it is useful to have 3 coordinates for each point: the row, the column and the diagonal (the 3 directions of the grid).

The length in each direction, is just the maximum minus the minimum for that direction. These lengths are called d_r, d_c and d_d in the code below.

Checking for a valid triangle, the 3 lengths need to be equal. One way to check this, is to check that the minimum of the lengths is equal to the maximum.

For a valid parallelogram, two lengths need to be equal, and the third should be the double. Checking that the maximum length is twice the minimum length should cover this. But, because this can already be reached using 3 points, we should also check that for a given direction, there are exactly 2 points at the minimum and 2 at the maximum. Summing all points and comparing twice the sum of maximum and minimum should accomplish this.

For a valid hexagon, the 3 lengths should be equal. So, the same test as for the triangle: the minimum of the lengths equal to the maximum. And also the test on the sums is needed, as 4 points can already fulfil the length conditions.

import math

def find_row_col_diag(t):
    # convert the numerical position into an row,col,diag coordinate in the plane
    # first find largest n such that n*(n+1)/2 < t
    n = math.floor((math.sqrt(8 * t + 1) - 1) / 2 - 0.0000001)
    row, col = n + 1, t - n * (n + 1) // 2
    return row, col, row - col

def check_valid_figure(tri_points):
    points = [find_row_col_diag(t) for t in tri_points]
    rs = [r for (r, c, d) in points]
    cs = [c for (r, c, d) in points]
    ds = [d for (r, c, d) in points]
    sum_r = sum(rs)
    min_r = min(rs)
    max_r = max(rs)
    d_r = max_r - min_r
    sum_c = sum(cs)
    min_c = min(cs)
    max_c = max(cs)
    d_c = max_c - min_c
    sum_d = sum(ds)
    min_d = min(ds)
    max_d = max(ds)
    d_d = max_d - min_d
    if len(points) == 3:
        is_ok = max(d_r, d_c, d_d) == min(d_r, d_c, d_d)
    elif len(points) == 4:
        is_ok = max(d_r, d_c, d_d) == 2 * min(d_r, d_c, d_d) \
                and sum_r == 2 * (min_r + max_r) and sum_c == 2 * (min_c + max_c) and sum_d == 2 * (min_d + max_d)
    elif len(points) == 6:
        is_ok = max(d_r, d_c, d_d) == min(d_r, d_c, d_d) \
                and len(set(rs)) == 3 and len(set(cs)) == 3 and len(set(ds)) == 3
    else:
        is_ok = False
    print(" ".join([str(t) for t in tri_points]), end=" ")
    if is_ok:
        print("are the vertices of a",
              "triangle" if len(points) == 3 else "parallelogram" if len(points) == 4 else "hexagon")
    else:
        print("are not the vertices of an acceptable figure")

tri_point_lists = [[1, 2, 3],
                   [11, 13, 22, 24],
                   [11, 13, 29, 31],
                   [11, 13, 23, 25],
                   [26, 11, 13, 24],
                   [22, 23, 30],
                   [4, 5, 9, 13, 12, 7]]
for lst in tri_point_lists:
    check_valid_figure(lst)

The last code can be further compressed using list comprehensions:

def check_valid_figure_bis(tri_points):
    points = [find_row_col_diag(t) for t in tri_points]
    rs, cs, ds = [[p[i] for p in points] for i in range(3)]
    sums = [sum(xs) for xs in (rs, cs, ds)]
    mins = [min(xs) for xs in (rs, cs, ds)]
    maxs = [max(xs) for xs in (rs, cs, ds)]
    lens = [ma - mi for mi, ma in zip(mins, maxs)]
    if len(points) == 3:
        is_ok = max(lens) == min(lens)
    elif len(points) == 4:
        is_ok = max(lens) == 2 * min(lens) and all([su == 2 * (mi + ma) for su, mi, ma in zip(sums, mins, maxs)])
    elif len(points) == 6:
        is_ok = max(lens) == min(lens) and all([len(set(xs)) == 3 for xs in (rs, cs, ds)])
    else:
        is_ok = False
    return is_ok


问:
how to access tag slider value in iphone sdk?
i have a question regarding slider tags. Lets assume i have a slider and its tag is "1", how can i get the .value of slider that has tag '1'? I saw examples of if(slider.tag ==1) but i want to access the value of it - how is this possible? thanks</p>

答:
```<code>value = [[yourView viewWithTag:1] value];
</code>```

I recommend to wire up the slider through a property and access it directly, though, if possible.

ContentLicense: CC BY-SA 3.0

Body:
value = [[yourView viewWithTag:1] value];

I recommend to wire up the slider through a property and access it directly, though, if possible.


问:
How do I copy and paste results from ORACLE SQL Developer to Excel while taking Null values into account?
I have Googled this issue and have looked at previous Stackoverflow questions.  I am trying to figure out how to copy and paste from Oracle SQL Developer into Ms Excel.  I have tried right clicking my results and clicking Export and following the steps to Export to clipboard and I have also tried highlighting all rows and pressing Ctrl + Shift + C and pasting into Excel.  In both cases, when a field has a Null value in SQL Developer, it will just skip the cell in Excel.  For example if Field1 has a value of 'Oracle', Field2 has a value of Null, and Field3 has a value of 200, when I paste into Excel cell A2 (first row is headers) will have a value of 'Oracle', then B2 instead of being blank will have a value of 200.  How do I account for Null values when pasting?  The other issue is that I am working through Citrix so I am not able to easily save work from SQL Developer to my desktop (in fact it is damn near impossible).  </p>

答:
I'm not sure why you're having trouble because I am not. True, I am not using the Export feature but you haven't said that you must use that feature. To continue the conversation in comments will be a bad idea.

First, I am using SQL Developer 19.2.1.247 and Excel 16.24 on macOS (but the OS should not matter).

Here is the query that I am using to test the copy & paste capability:

```<code>select 1, null, 2 from dual
union all
select null, 3, 4 from dual
union all
select 5, 6, null from dual
union all
select null, null, null from dual
</code>```

If you reproduce good results with this query but bad results with your query, then I suggest you edit your post and include an MCV example query that produces bad results.

I select the query and press [Run Statement]. This creates a Query Result window that looks like this:

Then I put my cursor in the Query Result window and select all rows displayed by pressing Meta-A (⌘A or ^A) and then copy the selection by pressing Meta-C (⌘C or ^C). Then I see this:

Then I place my cursor in cell A1 in an Excel sheet and paste the clipboard by pressing Meta-V (⌘V or ^V). Then I see this:

Notice all four row's cells in the Excel sheet are correct w.r.t. the query. I did nothing special, not even invoking Menu->Data->Text to Columns. It was all done "automatically".

Body:
I'm not sure why you're having trouble because I am not. True, I am not using the Export feature but you haven't said that you must use that feature. To continue the conversation in comments will be a bad idea.

First, I am using SQL Developer 19.2.1.247 and Excel 16.24 on macOS (but the OS should not matter).

Here is the query that I am using to test the copy & paste capability:

select 1, null, 2 from dual
union all
select null, 3, 4 from dual
union all
select 5, 6, null from dual
union all
select null, null, null from dual

If you reproduce good results with this query but bad results with your query, then I suggest you edit your post and include an MCV example query that produces bad results.

I select the query and press [Run Statement]. This creates a Query Result window that looks like this:

Then I put my cursor in the Query Result window and select all rows displayed by pressing Meta-A (⌘A or ^A) and then copy the selection by pressing Meta-C (⌘C or ^C). Then I see this:

Then I place my cursor in cell A1 in an Excel sheet and paste the clipboard by pressing Meta-V (⌘V or ^V). Then I see this:

Notice all four row's cells in the Excel sheet are correct w.r.t. the query. I did nothing special, not even invoking Menu->Data->Text to Columns. It was all done "automatically".


问:
Get description attribute of an enum *subset*
I know how to get the description of every enum. I am trying to figure out how to get it of a subset.

Here's what I have, which I trust shows the intent of what I'm aiming for:

```<code>public enum ModelType : int
{
    /// <summary>
    /// No model type. For internal use only.
    /// </summary>
    [Description("NA")]
    _NA = 0,

    [Description("Literal Model")]
    Literal = 1,

    [Description("Linear Model")]
    Linear = 2,

    [Description("Curve Model")]
    Curve = 3
}

var values = Enum.GetValues(typeof(ModelType))
    .Cast<ModelType>()
    .Where(x => x > ModelType._NA)  // filter
    .ToArray();

var attributes = values.GetMembers() // this is wrong
    .SelectMany(member => member.GetCustomAttributes(typeof(DescriptionAttribute), true).Cast<DescriptionAttribute>())
    .ToList();

return attributes.Select(x => x.Description);
</code>```

答:
This should work:</p>

```<code>var type = typeof(ModelType);

var propNames = Enum.GetValues(type)
    .Cast<ModelType>()
    .Where(x => x > ModelType._NA)  // filter
    .Select(x => x.ToString())
    .ToArray();

var attributes = propNames
    .Select(n => type.GetMember(n).First())
    .SelectMany(member => member.GetCustomAttributes(typeof(DescriptionAttribute), true).Cast<DescriptionAttribute>())
    .ToList();

return attributes.Select(x => x.Description);
</code>```

Body:
I know how to get the description of every enum. I am trying to figure out how to get it of a subset.

Here's what I have, which I trust shows the intent of what I'm aiming for:

public enum ModelType : int
{
    ///
    /// No model type. For internal use only.
    ///
    [Description("NA")]
    _NA = 0,

    [Description("Literal Model")]
    Literal = 1,

    [Description("Linear Model")]
    Linear = 2,

    [Description("Curve Model")]
    Curve = 3
}

var values = Enum.GetValues(typeof(ModelType))
    .Cast<ModelType>()
    .Where(x => x > ModelType._NA)  // filter
    .ToArray();

var attributes = values.GetMembers() // this is wrong
    .SelectMany(member => member.GetCustomAttributes(typeof(DescriptionAttribute), true).Cast<DescriptionAttribute>())
    .ToList();

return attributes.Select(x => x.Description);

Body:
This should work:

var type = typeof(ModelType);

var propNames = Enum.GetValues(type)
    .Cast<ModelType>()
    .Where(x => x > ModelType._NA)  // filter
    .Select(x => x.ToString())
    .ToArray();

var attributes = propNames
    .Select(n => type.GetMember(n).First())
    .SelectMany(member => member.GetCustomAttributes(typeof(DescriptionAttribute), true).Cast<DescriptionAttribute>())
    .ToList();

return attributes.Select(x => x.Description);


问:
How to input coordinates values from a multi-value hashmap into javafx point2d?
Currently, I am trying to create a heatmap using JavaFX, and I have stored the country name and its coordinates into a HashMap. My idea was to call the HashMap and get the coordinates value of the countries into Point2D. Such that I could maybe loop the line events = new Point2D[], rather than writing the new points individually. I'm not sure if my thoughts of coding are correct. However, there was an error (as shown in the code below).

The constructor Point2D(List) is undefined

How can I get the coordinates value in the HashMap and input into Point2D, rather then inserting the value itself into Point2D (as shown in the code below) ?

```<code>@Override public void init() {
    //Setting country coordinates on the map
    HashMap<String, List<Integer>> countryCoordinates = new HashMap<>();
    Integer[] coordinates = {};
    countryCoordinates.put("china", Arrays.asList(700, 180));
    countryCoordinates.put("Diamond Princess", Arrays.asList(810, 170));
    countryCoordinates.put("Singapore", Arrays.asList(726, 310));
    countryCoordinates.put("Japan", Arrays.asList(810, 170));
    countryCoordinates.put("Hong Kong", Arrays.asList(755, 225));
    countryCoordinates.put("Thailand", Arrays.asList(720, 250));
    .
    .
    .
    .
    pane = new StackPane();
    heatMap = new SimpleHeatMap(1000, 600, ColorMapping.LIME_YELLOW_RED, 40);
    heatMap.setOpacityDistribution(OpacityDistribution.EXPONENTIAL);
    heatMap.setHeatMapOpacity(1);
    events  = new Point2D[] {
        new Point2D(countryCoordinates.get("china")), //The constructor Point2D(List<Integer>) is undefined
        new Point2D(810, 170),
</code>```

答:
A solution using Java's Stream API which creates an array of Point2D objects - since it appears, from the code in your question, that's what you want to do.

Map<String, List<Integer>> countryCoordinates = new HashMap<>();
countryCoordinates.put("china", Arrays.asList(700, 180));
countryCoordinates.put("Diamond Princess", Arrays.asList(810, 170));
countryCoordinates.put("Singapore", Arrays.asList(726, 310));
countryCoordinates.put("Japan", Arrays.asList(810, 170));
countryCoordinates.put("Hong Kong", Arrays.asList(755, 225));
countryCoordinates.put("Thailand", Arrays.asList(720, 250));
List<Point2D> pts = countryCoordinates.values()
                                      .stream()
                                      .map(lst -> new Point2D(lst.get(0), lst.get(1)))
                                      .collect(Collectors.toList());
Point2D[] points = pts.toArray(new Point2D[]{});
```

Body:
Currently, I am trying to create a heatmap using JavaFX, and I have stored the country name and its coordinates into a HashMap. My idea was to call the HashMap and get the coordinates value of the countries into Point2D. Such that I could maybe loop the line events = new Point2D[], rather than writing the new points individually. I'm not sure if my thoughts of coding are correct. However, there was an error (as shown in the code below).

The constructor Point2D(List) is undefined

How can I get the coordinates value in the HashMap and input into Point2D, rather then inserting the value itself into Point2D (as shown in the code below) ?

@Override public void init() {
    //Setting country coordinates on the map
    HashMap<String, List<Integer>> countryCoordinates = new HashMap<>();
    Integer[] coordinates = {};
    countryCoordinates.put("china", Arrays.asList(700, 180));
    countryCoordinates.put("Diamond Princess", Arrays.asList(810, 170));
    countryCoordinates.put("Singapore", Arrays.asList(726, 310));
    countryCoordinates.put("Japan", Arrays.asList(810, 170));
    countryCoordinates.put("Hong Kong", Arrays.asList(755, 225));
    countryCoordinates.put("Thailand", Arrays.asList(720, 250));
    .
    .
    .
    .
    pane = new StackPane();
    heatMap = new SimpleHeatMap(1000, 600, ColorMapping.LIME_YELLOW_RED, 40);
    heatMap.setOpacityDistribution(OpacityDistribution.EXPONENTIAL);
    heatMap.setHeatMapOpacity(1);
    events  = new Point2D[] {
        new Point2D(countryCoordinates.get("china")), //The constructor Point2D(List<Integer>) is undefined
        new Point2D(810, 170),


问:
What do square brackets mean in pip install?
I see more and more commands like this:

```<code>$ pip install "splinter[django]"
</code>```

What do these square brackets do?

答:
Brackets [optional] in PIP signify optional dependencies

Just in case another developer comes along looking to implement this pattern in their own Python package deployment, here's further explanation of the brackets [] in pip.

For Example: Apache Airflow

To install airflow from pip we use this command:

pip install 'apache-airflow'
```

<p>You can install <em>optional</em> components of airflow with:</p>

<pre class="lang-sh prettyprint-override"><code>pip install 'apache-airflow[aws]'
#      [optional] -----------^
</code>```

When we search pypi for apache-airflow note that the optional packages do not show up:

pip search 'apache-airflow'

apache-airflow (1.10.9)                            - Programmatically author, schedule and monitor data pipelines
pylint-airflow (0.1.0a1)                           - A Pylint plugin to lint Apache Airflow code.
swe-airflow-tools (0.0.3)                          - Tools for Apache Airflow Application
airflow (0.6)                                      - Placeholder for the old Airflow package
...
```

Implementation via setup.py

You can see how this was accomplished in the setup.py script

On the left in setup.py - extras_require is defined.

On the right are the correlated installation commands for these optional sub-packages.

Body:
I see more and more commands like this:

$ pip install "splinter[django]"

What do these square brackets do?

Body:
Brackets [optional] in PIP signify optional dependencies

Just in case another developer comes along looking to implement this pattern in their own Python package deployment, here's further explanation of the brackets [] in pip.

For Example: Apache Airflow

To install airflow from pip we use this command:

pip install 'apache-airflow'

You can install optional components of airflow with:

pip install 'apache-airflow[aws]'
#      [optional] -----------^

When we search pypi for apache-airflow note that the optional packages do not show up:

pip search 'apache-airflow'

apache-airflow (1.10.9)                            - Programmatically author, schedule and monitor data pipelines
pylint-airflow (0.1.0a1)                           - A Pylint plugin to lint Apache Airflow code.
swe-airflow-tools (0.0.3)                          - Tools for Apache Airflow Application
airflow (0.6)                                      - Placeholder for the old Airflow package
...

Implementation via setup.py

You can see how this was accomplished in the setup.py script

On the left in setup.py - extras_require is defined.

On the right are the correlated installation commands for these optional sub-packages.


问:
scrapy list command can see spider but runspider cant find it?
If i type in

```<code>scrapy list
</code>```

I get the correct answer which is a single spider i made called

```<code>wiki
</code>```

but (staying in the same dir in cmd line) when i do;

```<code>scrapy runspider wiki
</code>```

i get;

```<code>    2020-02-19 18:58:05 [scrapy.utils.log] INFO: Scrapy 1.8.0 started (bot: wikipedia)
2020-02-19 18:58:05 [scrapy.utils.log] INFO: Versions: lxml 4.4.2.0, libxml2 2.9.5, cssselect 1.1.0, parsel 1.5.2, w3lib 1.21.0, Twisted 19.10.0, Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 22:39:24) [MSC v.1916 32 bit (Intel)], pyOpenSSL 19.1.0 (OpenSSL 1.1.1d  10 Sep 2019), cryptography 2.8, Platform Windows-10-10.0.18362-SP0
Usage
=====
  scrapy runspider [options] <spider_file>

runspider: error: File not found: wiki
</code>```

What's going on?

答:
You are looking for scrapy crawl. scrapy runspider requires the file of your spider as argument.

scrapy runspider <spider_file.py>

scrapy crawl <spider>

https://docs.scrapy.org/en/latest/topics/commands.html

Body:
If i type in

scrapy list

I get the correct answer which is a single spider i made called

wiki

but (staying in the same dir in cmd line) when i do;

scrapy runspider wiki

i get;

    2020-02-19 18:58:05 [scrapy.utils.log] INFO: Scrapy 1.8.0 started (bot: wikipedia)
2020-02-19 18:58:05 [scrapy.utils.log] INFO: Versions: lxml 4.4.2.0, libxml2 2.9.5, cssselect 1.1.0, parsel 1.5.2, w3lib 1.21.0, Twisted 19.10.0, Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 22:39:24) [MSC v.1916 32 bit (Intel)], pyOpenSSL 19.1.0 (OpenSSL 1.1.1d  10 Sep 2019), cryptography 2.8, Platform Windows-10-10.0.18362-SP0
Usage
=====
  scrapy runspider [options] <spider_file>

runspider: error: File not found: wiki

What's going on?


问:
Azure Policy like where case sensitive
I'm looking to form a policy that, like "matchInsensitively" and "match" are case sensitive but with something like the like conditional operator.

With match I have to define if the statement has either a character, digit, or "." in place but I want to be able to define the actual string, ideally with a leading wildcard.

Anyone know if this is possible?

答: I would recommend using a contains. There are various conditions you can leverage : https://learn.microsoft.com/en-us/azure/governance/policy/concepts/definition-structure#conditions</p>

Title: Azure Policy like where case sensitive


问:
How to run sklearn.model_selection.GridSearchCV without splitting data?
I would like to evaluate the performance of a model pipeline.  I am not training my model on the ground-truth labels that I am evaluating the pipeline against, therefore doing a cross-validation scheme is unnecessary.  However, I would still like to use the grid search functionality provided in sklearn.

Is it possible to use sklearn.model_selection.GridSearchCV without splitting the data?  In other words, I would like to run Grid Search and get scores on the full dataset that I pass in to the pipeline.

Here is a simple example:

I might wish to choose the optimal k for KMeans.  I am actually going to be using KMeans on many datasets that are similar in some sense.  It so happens that I have some ground-truth labels for a few such datasets, which I will call my "training" data.  So, instead of using something like BIC, I decide to simply pick the optimal k for my training data, and employ that k for future datasets.  Search over possible values of k is a grid search.  KMeans is available in the sklearn library, so I can very easily define a grid search on this model.  Incidentally, KMeans takes in an "empty" y value, which simply passes through and can be used in a GridSearchCV scorer.  However, there is no sense in doing cross-validation here, since my individual kmeans models never see the ground truth labels and are therefore incapable of overfitting.

To be clear, the above example is simply a contrived example to justify a possible use case for such a thing for those who are afraid that I might abuse this functionality.  The solution to the example above that I am interested in is how to not split the data in GridSearchCV.

Is it possible to use sklearn.model_selection.GridSearchCV without splitting the data?

答:
The docs claim that the cv parameter in the GridSearchCV constructor optionally is capable of accepting "An iterable yielding (train, test) splits as arrays of indices."  It turns out that the "arrays of indices" bit is irrelevant, and it is possible to send in arbitrary objects that can be used to index arrays.  If we hand in a thing that gives the whole array for both the train and the test split, we can circumvent the cross-validation behavior.

This is one way to accomplish that thing that corresponds to the example given in the question:

```<code>grid_search = sklearn.model_selection.GridSearchCV(
    sklearn.cluster.KMeans(),
    {"k": [2,3,4,5,7,10,20]},
    cv=(((slice(None), slice(None)),)
)
</code>```

If you pass the ground-truth labels as y to this, it will evaluate the outcome of each run of KMeans corresponding to the various k against the entire dataset.

Body:
The docs claim that the cv parameter in the GridSearchCV constructor optionally is capable of accepting "An iterable yielding (train, test) splits as arrays of indices."  It turns out that the "arrays of indices" bit is irrelevant, and it is possible to send in arbitrary objects that can be used to index arrays.  If we hand in a thing that gives the whole array for both the train and the test split, we can circumvent the cross-validation behavior.

This is one way to accomplish that thing that corresponds to the example given in the question:

grid_search = sklearn.model_selection.GridSearchCV(
    sklearn.cluster.KMeans(),
    {"k": [2,3,4,5,7,10,20]},
    cv=(((slice(None), slice(None)),)
)

If you pass the ground-truth labels as y to this, it will evaluate the outcome of each run of KMeans corresponding to the various k against the entire dataset.


问:
empty textbox controls after the data is inserted / saved/ submitted in a c# winform application
I need to empty all the textbox controls after the SAVE button is clicked but the user. I have around 10 of them. How do i clear text from them all simultaneously. I just know about:

```<code>textbox1.Text="";
</code>```

But, if i do this, then i need to repeat this for the no. of textbox controls on my Form, that would be a labor task instead of programmer?

Please guide.

答:
If you want to clear everything on the form, I would suggest a pair of utility function such as:

```<code>public static void ClearAllControls(Control.ControlCollection controls)
{
    foreach (var control in controls)
        ClearAllControls(control);
}

public static void ClearAllControls(Control control)
{
    var textBox = control as TextBox
    if (textBox != null)
    {
        textBox.Text = null;
        return;
    }

    var comboBox = control as ComboBox;
    if (comboBox != null)
    {
        comboBox.SelectedIndex = -1;
        return;
    }

    // ...repeat blocks for other control types as needed

    ClearAllControls(control.Controls);
}
</code>```

Call the first method, passing the form's Controls collection, and it will recursively drill down through panels, groups, etc, clearing all the controls it knows about. You'll have to add a block for each different control type, but at least you only have to do it once. It's a bit brute-force, but it's not the kind of code that ends up running in a loop, and it runs plenty fast, anyway.

The final line, which does the recursion, will only be reached if the current control being worked on hasn't already proven to be one of the known types, so you don't have to worry about accidentally "drilling into" things like TextBoxes, looking for child controls that won't be there.

Body:
I need to empty all the textbox controls after the SAVE button is clicked but the user. I have around 10 of them. How do i clear text from them all simultaneously. I just know about:

textbox1.Text="";

But, if i do this, then i need to repeat this for the no. of textbox controls on my Form, that would be a labor task instead of programmer?

Please guide.

Body:
If you want to clear everything on the form, I would suggest a pair of utility function such as:

public static void ClearAllControls(Control.ControlCollection controls)
{
    foreach (var control in controls)
        ClearAllControls(control);
}

public static void ClearAllControls(Control control)
{
    var textBox = control as TextBox
    if (textBox != null)
    {
        textBox.Text = null;
        return;
    }

    var comboBox = control as ComboBox;
    if (comboBox != null)
    {
        comboBox.SelectedIndex = -1;
        return;
    }

    // ...repeat blocks for other control types as needed

    ClearAllControls(control.Controls);
}

Call the first method, passing the form's Controls collection, and it will recursively drill down through panels, groups, etc, clearing all the controls it knows about. You'll have to add a block for each different control type, but at least you only have to do it once. It's a bit brute-force, but it's not the kind of code that ends up running in a loop, and it runs plenty fast, anyway.

The final line, which does the recursion, will only be reached if the current control being worked on hasn't already proven to be one of the known types, so you don't have to worry about accidentally "drilling into" things like TextBoxes, looking for child controls that won't be there.


问:
RetroFit handle geneirc responses in Kotlin
I currently have login and register endpoints that return similar JSON, the former returns the JWT token and the latter the user id, either way in my repository I have this code:

```<code>suspend fun login(user: User) = try {
    val response = api.login(user)
    LoginResult.Content(response.token)
} catch (t: Throwable) {
    LoginResult.Error(t)
}

suspend fun register(user: User) = try {
    val response = api.register(user)
    RegisterResult.Content(response.id!!)
} catch (t: Throwable) {
    RegisterResult.Error(t)
}
</code>```

My LoginResult looks like this:

```<code>sealed class LoginResult {
    data class Content(val accessToken: String) : LoginResult()
    data class Error(val throwable: Throwable) : LoginResult()
}
</code>```

and my RegisterResult looks very similar:

```<code>sealed class RegisterResult {
    data class Content(val id: Int) : RegisterResult()
    data class Error(val throwable: Throwable) : RegisterResult()
}
</code>```

Clearly I have a lot of duplicate code between these two and considering that I'll have many more requests to handle it will only get worse. Besides this there are also the appropriate ViewStates to think about.

```<code>sealed class LoginViewState {
    object Loading : LoginViewState()
    data class Content(val accessToken: String) : LoginViewState()
    data class Error(val throwable: Throwable) : LoginViewState()
}
</code>```

A similar one exists for register and they are being used in the Motors:

```<code>class LoginMotor : ViewModel() {
    private val _results = MutableLiveData<LoginViewState>()
    val results: LiveData<LoginViewState> = _results

    fun login(user: User) {
        _results.value = LoginViewState.Loading

        viewModelScope.launch(Dispatchers.Main) {
            val result = AuthRepository.login(user)

            _results.value = when (result) {
                is LoginResult.Content -> { LoginViewState.Content(result.accessToken) }
                is LoginResult.Error -> LoginViewState.Error(result.throwable)
            }
        }
    }
}
</code>```

and another such motor for registration. Now I'm trying to use a generic approach here and I can add generics to the EndpointResult, but how can I make the ViewState generic when I have to use a Loading state which is an object and cannot be generic since it's a singleton? This doesn't work:

```<code>sealed class DataViewState<T> {
    object Loading : LoginViewState() //error
    data class Content<T>(val data: T) : LoginViewState<T>()
    data class Error(val throwable: Throwable) : LoginViewState()
}
</code>```

答:
I came up with a solution:</p>

```<code>sealed class DataViewState {
    object Loading: DataViewState()
    data class Content<T>(val data: T): DataViewState()
    data class Error(val throwable: Throwable): DataViewState()
}
</code>```

```<code>sealed class GenericResult {
    data class Content<T>(val data: T) : GenericResult()
    data class Error(val throwable: Throwable) : GenericResult()
}
</code>```

Body:
I currently have login and register endpoints that return similar JSON, the former returns the JWT token and the latter the user id, either way in my repository I have this code:

suspend fun login(user: User) = try {
    val response = api.login(user)
    LoginResult.Content(response.token)
} catch (t: Throwable) {
    LoginResult.Error(t)
}

suspend fun register(user: User) = try {
    val response = api.register(user)
    RegisterResult.Content(response.id!!)
} catch (t: Throwable) {
    RegisterResult.Error(t)
}

My LoginResult looks like this:

sealed class LoginResult {
    data class Content(val accessToken: String) : LoginResult()
    data class Error(val throwable: Throwable) : LoginResult()
}

and my RegisterResult looks very similar:

sealed class RegisterResult {
    data class Content(val id: Int) : RegisterResult()
    data class Error(val throwable: Throwable) : RegisterResult()
}

Clearly I have a lot of duplicate code between these two and considering that I'll have many more requests to handle it will only get worse. Besides this there are also the appropriate ViewStates to think about.

sealed class LoginViewState {
    object Loading : LoginViewState()
    data class Content(val accessToken: String) : LoginViewState()
    data class Error(val throwable: Throwable) : LoginViewState()
}

A similar one exists for register and they are being used in the Motors:

class LoginMotor : ViewModel() {
    private val _results = MutableLiveData<LoginViewState>()
    val results: LiveData<LoginViewState> = _results

    fun login(user: User) {
        _results.value = LoginViewState.Loading

        viewModelScope.launch(Dispatchers.Main) {
            val result = AuthRepository.login(user)

            _results.value = when (result) {
                is LoginResult.Content -> { LoginViewState.Content(result.accessToken) }
                is LoginResult.Error -> LoginViewState.Error(result.throwable)
            }
        }
    }
}

and another such motor for registration. Now I'm trying to use a generic approach here and I can add generics to the EndpointResult, but how can I make the ViewState generic when I have to use a Loading state which is an object and cannot be generic since it's a singleton? This doesn't work:

sealed class DataViewState<T> {
    object Loading : LoginViewState() //error
    data class Content<T>(val data: T) : LoginViewState<T>()
    data class Error(val throwable: Throwable) : LoginViewState()
}

Body:
I came up with a solution:

sealed class DataViewState {
    object Loading: DataViewState()
    data class Content<T>(val data: T): DataViewState()
    data class Error(val throwable: Throwable): DataViewState()
}

sealed class GenericResult {
    data class Content<T>(val data: T) : GenericResult()
    data class Error(val throwable: Throwable) : GenericResult()
}


问:
Trying to create a multithreaded program to find the total primes from 0-100000000
Hello I am trying to write a C++ multithreaded program using POSIX thread library to find the number of prime numbers between 1 and 10,000,000 (10 million) and find out how many microseconds it takes...

Creating my threads and running them works completely fine, however I feel as if there is an error found in my Prime function when determining if a number is prime or not...

I keep receiving 78496 as my output, however I desire 664579. Below is my code. Any hints or pointers would be greatly appreciated.

```<code>#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
#include <sys/time.h> //measure the execution time of the computations

using namespace std;

//The number of thread to be generated
#define NUMBER_OF_THREADS 4

void * Prime(void* index);

long numbers[4] = {250000, 500000, 750000, 1000000};
long start_numbers[4] = {1, 250001, 500001, 750001};

int thread_numbers[4] = {0, 1, 2, 3};

int main(){
  pthread_t tid[NUMBER_OF_THREADS];

  int tn;

  long sum = 0;

  timeval start_time, end_time;

  double start_time_microseconds, end_time_microseconds;

  gettimeofday(&start_time, NULL);

  start_time_microseconds = start_time.tv_sec * 1000000 + start_time.tv_usec;
  for(tn = 0; tn < NUMBER_OF_THREADS; tn++){
    if (pthread_create(&tid[tn], NULL, Prime, (void *) &thread_numbers[tn]) == -1 ) {
        perror("thread fail");
        exit(-1);
    }
  }
 long value[4];

 for(int i = 0; i < NUMBER_OF_THREADS; i++){
    if(pthread_join(tid[i],(void **) &value[i]) == 0){
        sum = sum + value[i]; //add four sums together
    }else{
      perror("Thread join failed");
      exit(-1);
    }
 }
 //get the end time in microseconds
 gettimeofday(&end_time, NULL);

 end_time_microseconds = end_time.tv_sec * 1000000 + end_time.tv_usec;

 //calculate the time passed
 double time_passed = end_time_microseconds - start_time_microseconds;

 cout << "Sum is: " << sum << endl;
 cout << "Running time is: " << time_passed << " microseconds" << endl;

 exit(0);
}

//Prime function
void* Prime(void* index){
  int temp_index;

  temp_index = *((int*)index);
  long  sum_t = 0;

  for(long i = start_numbers[temp_index]; i <= numbers[temp_index]; i++){
        for (int j=2; j*j <= i; j++)
        {
            if (i % j == 0)
            {
                break;
            }
            else if (j+1 > sqrt(i)) {
                sum_t++;
            }
         }

  }

  cout << "Thread " << temp_index << " terminates" << endl;
  pthread_exit( (void*) sum_t);
}```
```

答:
This is because, you used 10^6 instead of 10^7.

Also, added some corner cases for numbers 1, 2 and 3:

```<code>//Prime function
void* Prime(void* index){
  int temp_index;

  temp_index = *((int*)index);
  long  sum_t = 0;

  for(long i = start_numbers[temp_index]; i <= numbers[temp_index]; i++){

      // Corner cases

      if(i<=1)continue;
      if (i <= 3){
            sum_t++;
            continue;
      }

      for (int j=2; j*j <= i; j++)
      {
          if ((i % j == 0) ||  (i %( j+2))==0 )
          {
              break;
          }
          else if (j+1 > sqrt(i)) {
              sum_t++;
          }
       }

  }

    cout << "Thread " << temp_index << " terminates" << endl;
    pthread_exit( (void*) sum_t);
}
</code>```

I tested your code with correct number and got the correct number of primes as output:

```<code>Thread 0 terminates
Thread 1 terminates
Thread 2 terminates
Thread 3 terminates
Sum is: 664579
Running time is: 4.69242e+07 microseconds
</code>```

Thanks to @chux - Reinstate Monica for pointing this out

Body:
Hello I am trying to write a C++ multithreaded program using POSIX thread library to find the number of prime numbers between 1 and 10,000,000 (10 million) and find out how many microseconds it takes...

Creating my threads and running them works completely fine, however I feel as if there is an error found in my Prime function when determining if a number is prime or not...

I keep receiving 78496 as my output, however I desire 664579. Below is my code. Any hints or pointers would be greatly appreciated.

#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
#include <sys/time.h> //measure the execution time of the computations

using namespace std;

//The number of thread to be generated
#define NUMBER_OF_THREADS 4

void * Prime(void* index);

long numbers[4] = {250000, 500000, 750000, 1000000};
long start_numbers[4] = {1, 250001, 500001, 750001};

int thread_numbers[4] = {0, 1, 2, 3};

int main(){
  pthread_t tid[NUMBER_OF_THREADS];

  int tn;

  long sum = 0;

  timeval start_time, end_time;

  double start_time_microseconds, end_time_microseconds;

  gettimeofday(&start_time, NULL);

  start_time_microseconds = start_time.tv_sec * 1000000 + start_time.tv_usec;
  for(tn = 0; tn < NUMBER_OF_THREADS; tn++){
    if (pthread_create(&tid[tn], NULL, Prime, (void *) &thread_numbers[tn]) == -1 ) {
        perror("thread fail");
        exit(-1);
    }
  }
 long value[4];

 for(int i = 0; i < NUMBER_OF_THREADS; i++){
    if(pthread_join(tid[i],(void **) &value[i]) == 0){
        sum = sum + value[i]; //add four sums together
    }else{
      perror("Thread join failed");
      exit(-1);
    }
 }
 //get the end time in microseconds
 gettimeofday(&end_time, NULL);

 end_time_microseconds = end_time.tv_sec * 1000000 + end_time.tv_usec;

 //calculate the time passed
 double time_passed = end_time_microseconds - start_time_microseconds;

 cout << "Sum is: " << sum << endl;
 cout << "Running time is: " << time_passed << " microseconds" << endl;

 exit(0);
}

//Prime function
void* Prime(void* index){
  int temp_index;

  temp_index = *((int*)index);
  long  sum_t = 0;

  for(long i = start_numbers[temp_index]; i <= numbers[temp_index]; i++){
        for (int j=2; j*j <= i; j++)
        {
            if (i % j == 0)
            {
                break;
            }
            else if (j+1 > sqrt(i)) {
                sum_t++;
            }
         }

  }

  cout << "Thread " << temp_index << " terminates" << endl;
  pthread_exit( (void*) sum_t);
}```

Body:
This is because, you used 10^6 instead of 10^7.

Also, added some corner cases for numbers 1, 2 and 3:

//Prime function
void* Prime(void* index){
  int temp_index;

  temp_index = *((int*)index);
  long  sum_t = 0;

  for(long i = start_numbers[temp_index]; i <= numbers[temp_index]; i++){

      // Corner cases

      if(i<=1)continue;
      if (i <= 3){
            sum_t++;
            continue;
      }

      for (int j=2; j*j <= i; j++)
      {
          if ((i % j == 0) ||  (i %( j+2))==0 )
          {
              break;
          }
          else if (j+1 > sqrt(i)) {
              sum_t++;
          }
       }

  }

    cout << "Thread " << temp_index << " terminates" << endl;
    pthread_exit( (void*) sum_t);
}

I tested your code with correct number and got the correct number of primes as output:

Thread 0 terminates
Thread 1 terminates
Thread 2 terminates
Thread 3 terminates
Sum is: 664579
Running time is: 4.69242e+07 microseconds

Thanks to @chux - Reinstate Monica for pointing this out


问:
OutOfMemoryError while compressing a picture
I am working on an application that at a certain point has to compress a picture in order to send it to the server. If the compression doesn't work, it sends the non-compressed photo (not a big deal).

Despite the compression method is surrounded by a try-catch it sometimes throws an OutOfMemory error on a few devices and I want to avoid it.

This is the method:

```<code>fun compressCapture(
    capture: File
): ByteArray? {
    return try {
        val compression = FirebaseRemoteConfig.getInstance().getLong(Constants.PICTURE_QUALITY)
        val pictureBytes = capture.readBytes()
        val bitmap = BitmapFactory.decodeByteArray(pictureBytes, 0, pictureBytes.size)
        val outputStream = ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.JPEG, compression.toInt(), outputStream)
        outputStream.toByteArray()
    } catch (e: Exception) {
        if (!BuildConfig.DEBUG)
            Crashlytics.logException(e)
        null
    }
}
</code>```

If it returns null the application sends the non-compressed file

The stack trace that I am receiving in Firebase sometimes is that:

```<code>Fatal Exception: java.lang.OutOfMemoryError: Failed to allocate a 1735832 byte allocation with 1549160 free bytes and 1512KB until OOM
       at java.io.ByteArrayOutputStream.toByteArray(ByteArrayOutputStream.java:122)
       at com.sagacollect.utils.FileUtils.compressCapture(FileUtils.java:9)
</code>```

Otherwise is that:

```<code>Fatal Exception: java.lang.OutOfMemoryError: Failed to allocate a 51916812 byte allocation with 16777216 free bytes and 45MB until OOM
       at dalvik.system.VMRuntime.newNonMovableArray(VMRuntime.java)
       at android.graphics.BitmapFactory.nativeDecodeByteArray(BitmapFactory.java)
       at android.graphics.BitmapFactory.decodeByteArray(BitmapFactory.java:561)
       at android.graphics.BitmapFactory.decodeByteArray(BitmapFactory.java:591)
       at com.sagacollect.utils.FileUtils.compressCapture(FileUtils.java:9)
</code>```

Any idea of what could be happening?

Cheers, Mauricio

答:
It could be that your VM has run out of memory. You could try adding

```<code>android:largeHeap="true"
</code>```

to your manifest.xml file and see if that solves the problem. It's not recommended as a permanent solution unless really necessary, but might help you troubleshoot.

There are image loading libraries that you can use like Picasso, Coil or Glide that will better help with compression issues.

Body:
I am working on an application that at a certain point has to compress a picture in order to send it to the server. If the compression doesn't work, it sends the non-compressed photo (not a big deal).

Despite the compression method is surrounded by a try-catch it sometimes throws an OutOfMemory error on a few devices and I want to avoid it.

This is the method:

fun compressCapture(
    capture: File
): ByteArray? {
    return try {
        val compression = FirebaseRemoteConfig.getInstance().getLong(Constants.PICTURE_QUALITY)
        val pictureBytes = capture.readBytes()
        val bitmap = BitmapFactory.decodeByteArray(pictureBytes, 0, pictureBytes.size)
        val outputStream = ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.JPEG, compression.toInt(), outputStream)
        outputStream.toByteArray()
    } catch (e: Exception) {
        if (!BuildConfig.DEBUG)
            Crashlytics.logException(e)
        null
    }
}

If it returns null the application sends the non-compressed file

The stack trace that I am receiving in Firebase sometimes is that:

Fatal Exception: java.lang.OutOfMemoryError: Failed to allocate a 1735832 byte allocation with 1549160 free bytes and 1512KB until OOM
       at java.io.ByteArrayOutputStream.toByteArray(ByteArrayOutputStream.java:122)
       at com.sagacollect.utils.FileUtils.compressCapture(FileUtils.java:9)

Otherwise is that:

Fatal Exception: java.lang.OutOfMemoryError: Failed to allocate a 51916812 byte allocation with 16777216 free bytes and 45MB until OOM
       at dalvik.system.VMRuntime.newNonMovableArray(VMRuntime.java)
       at android.graphics.BitmapFactory.nativeDecodeByteArray(BitmapFactory.java)
       at android.graphics.BitmapFactory.decodeByteArray(BitmapFactory.java:561)
       at android.graphics.BitmapFactory.decodeByteArray(BitmapFactory.java:591)
       at com.sagacollect.utils.FileUtils.compressCapture(FileUtils.java:9)

Any idea of what could be happening?

Cheers, Mauricio

Body:
It could be that your VM has run out of memory. You could try adding

android:largeHeap="true"

to your manifest.xml file and see if that solves the problem. It's not recommended as a permanent solution unless really necessary, but might help you troubleshoot.

There are image loading libraries that you can use like Picasso, Coil or Glide that will better help with compression issues.


问:
Ansible - Change user password on Linux
I'm doing some playbook to change username password on linux. I want to use the same playbook for all users.

What i am doing is:

```<code>    - name: change users password
  hosts: localhost
  vars_files: ['credentials.yml']
  tasks:
    - user:
        name: "{{ user_name }}"
        password: "{{ dynamic_password | password_hash('sha512') }}"
</code>```

And my file.yml:

```<code>credentials.yml
dynamic_password: "$6$mysecretsalt$QF9IdmmJLZWuEO8PKQ0w7c81Rre0hv.udU83ypIO3cG5DbAo90IXwHX6wcuhDJaLAkdE5KSSl9lKvdMFh810b."
generic_password: "$6$IxMDgSamMRSMAEY1$rfGAWC8xBgGMMGOFJXAMxnUuiKVKrH3SDOuNIrJpx4rMZy/FG5spqp1f9oSAcDBpTJ2vOK2rAboWHZ6Zn5qZm."
</code>```

What i am executing:

```<code>ansible-playbook prueba81.yml --extra-vars "user_name=pepito type_password=dynamic_password"
</code>```

What i want to do, is indicate in the command line, the user and what password (inside of the file yml) should it use. But seems that the variable type_password is not recognized.

Can you help me?.

Thanks!!!!

答:
Use lookup vars to reference the password indirectly. For example

```<code>  - user:
      name: "{{ user_name }}"
      password: "{{ my_password | password_hash('sha512') }}"
    vars:
      my_password: "{{ lookup('vars', type_password) }}"
</code>```

You might want to set a default type. For example

```<code>  - user:
      name: "{{ user_name }}"
      password: "{{ my_password | password_hash('sha512') }}"
    vars:
      my_password: "{{ lookup('vars', type_password|default('dynamic_password')) }}"
</code>```

Title: Ansible - Change user password on Linux

Body:
I'm doing some playbook to change username password on linux. I want to use the same playbook for all users.

What i am doing is:

    - name: change users password
  hosts: localhost
  vars_files: ['credentials.yml']
  tasks:
    - user:
        name: "{{ user_name }}"
        password: "{{ dynamic_password | password_hash('sha512') }}"

And my file.yml:

credentials.yml
dynamic_password: "$6$mysecretsalt$QF9IdmmJLZWuEO8PKQ0w7c81Rre0hv.udU83ypIO3cG5DbAo90IXwHX6wcuhDJaLAkdE5KSSl9lKvdMFh810b."
generic_password: "$6$IxMDgSamMRSMAEY1$rfGAWC8xBgGMMGOFJXAMxnUuiKVKrH3SDOuNIrJpx4rMZy/FG5spqp1f9oSAcDBpTJ2vOK2rAboWHZ6Zn5qZm."

What i am executing:

ansible-playbook prueba81.yml --extra-vars "user_name=pepito type_password=dynamic_password"

What i want to do, is indicate in the command line, the user and what password (inside of the file yml) should it use. But seems that the variable type_password is not recognized.

Can you help me?.

Thanks!!!!

Body:
Use lookup vars to reference the password indirectly. For example

  - user:
      name: "{{ user_name }}"
      password: "{{ my_password | password_hash('sha512') }}"
    vars:
      my_password: "{{ lookup('vars', type_password) }}"

You might want to set a default type. For example

  - user:
      name: "{{ user_name }}"
      password: "{{ my_password | password_hash('sha512') }}"
    vars:
      my_password: "{{ lookup('vars', type_password|default('dynamic_password')) }}"


问:
How can i append a space in each side of a string?
i have a NSString object named as myString.i need to append a space in each side of my string.
can any one tell me the good way to do it?</p>

答:
Then you can do it in this way.  </p>

```<code>NSString *s = [[NSString alloc]initWithFormat:@" %@ ",str];
</code>```

Body:
Then you can do it in this way.

NSString *s = [[NSString alloc]initWithFormat:@" %@ ",str];


问:
How do I get the last 5 rows of a datatable?
How do I get the last 5 rows of a datatable? I tried something like this:

```<code>var Long_bottom = LongSlection.Last(5);
</code>```

Where LongSlection is a DataRow. But I had an error, any idea?

答:
I needed CopyToDataTable() to get things done:

```<code>dt = dt.AsEnumerable().Reverse().Take(5).CopyToDataTable();
</code>```

Body:
How do I get the last 5 rows of a datatable? I tried something like this:

var Long_bottom = LongSlection.Last(5);

Where LongSlection is a DataRow. But I had an error, any idea?

Body:
I needed CopyToDataTable() to get things done:

dt = dt.AsEnumerable().Reverse().Take(5).CopyToDataTable();


问:
Returning a string from a Function (VAX PASCAL)
This is one for the software archaeologists!

And before you ask why was I even bothering to try to get this to work the reason it is simply because I can - which I think is a perfectly good excuse!

I found that the following code for a procedure compiles using VAX PASCAL (and runs as expected)..

```<code>PROCEDURE format(number : INTEGER);
   VAR
      result : STRING(16);
   BEGIN
     :
     :
      writeln(result);
   END.
</code>```

However if turn this into a function and try to return the result as a string it won't compile.

```<code>FUNCTION format(number : INTEGER) : STRING(16);
   VAR
      result : STRING(16);
   BEGIN
     :
     :
      format := result;
   END.
</code>```

The error suggests that the error is at type definition for the function.

```<code>FUNCTION format(number : INTEGER) : STRING(16);
                                    1
PASCAL-E-TYPCNTDISCR, Type can not be discriminated in this context
</code>```

I tried using VARYING and ARRAY types instead of STRING but they don't work either.  Unfortunately I can't find an example of a function that returns a STRING in SYS$EXAMPLES or in the manuals I found of bitsavers.

Hopefully someone has a better memory than me.

Thanks

答:
"Pascal's type system has been described as "too strong", because the size of an array or string is part of its type, ..." Strong and weak typing

This gives a hint that the String(16) in the function return value is too vague for the compiler.

Fix that by declaring a string type that suits the compiler:

```<code>type
  String16 = packed array[1..16] of char;
</code>```

Then you can use that distinct type in the function:

```<code>FUNCTION format(number : INTEGER) : String16;
VAR
  result : String16;
BEGIN
  :
  :
  format := result;
END.
</code>```

This is very much what was used in many early implementations of the pascal language (and Turbo Pascal), and is still valid. Modern compilers, like Delphi and FreePascal, has implemented a specialized dynamic array for strings, which covers a more convenient handling of the string type, not depending on declaring a strict size.

Body:
This is one for the software archaeologists!

And before you ask why was I even bothering to try to get this to work the reason it is simply because I can - which I think is a perfectly good excuse!

I found that the following code for a procedure compiles using VAX PASCAL (and runs as expected)..

PROCEDURE format(number : INTEGER);
   VAR
      result : STRING(16);
   BEGIN
     :
     :
      writeln(result);
   END.

However if turn this into a function and try to return the result as a string it won't compile.

FUNCTION format(number : INTEGER) : STRING(16);
   VAR
      result : STRING(16);
   BEGIN
     :
     :
      format := result;
   END.

The error suggests that the error is at type definition for the function.

FUNCTION format(number : INTEGER) : STRING(16);
                                    1
PASCAL-E-TYPCNTDISCR, Type can not be discriminated in this context

I tried using VARYING and ARRAY types instead of STRING but they don't work either.  Unfortunately I can't find an example of a function that returns a STRING in SYS$EXAMPLES or in the manuals I found of bitsavers.

Hopefully someone has a better memory than me.

Thanks

Body:
"Pascal's type system has been described as "too strong", because the size of an array or string is part of its type, ..." Strong and weak typing

This gives a hint that the String(16) in the function return value is too vague for the compiler.

Fix that by declaring a string type that suits the compiler:

type
  String16 = packed array[1..16] of char;

Then you can use that distinct type in the function:

FUNCTION format(number : INTEGER) : String16;
VAR
  result : String16;
BEGIN
  :
  :
  format := result;
END.

This is very much what was used in many early implementations of the pascal language (and Turbo Pascal), and is still valid. Modern compilers, like Delphi and FreePascal, has implemented a specialized dynamic array for strings, which covers a more convenient handling of the string type, not depending on declaring a strict size.


问:
problems copying an image and overwriting the existing one c# wpf
I have an image control that I charge an image via a path saved in a bdd, but if I want to change the image, first I look for the new image with an openfiledialogsends me the error, [the process cannot access the file]
this is my code</p>

```<code>OpenFileDialog openFileDialog = new OpenFileDialog();
        openFileDialog.Multiselect = false;
        openFileDialog.Filter = "Image files (*.;*.jpg)|*.jpg;*.png|All files (*.*)|*.*";
        openFileDialog.FilterIndex = 1;
        openFileDialog.RestoreDirectory = true;
        bool? checarOK = openFileDialog.ShowDialog();
        if (checarOK == true)
        {
            try
            {
                string archivo = openFileDialog.FileName;  //nombre archivo seleccionado
                rtjpg.Text = archivo; //ruta de archivo seleccionado en un textbox
                imgfoto.Source = new BitmapImage(new Uri(openFileDialog.FileName)); //coloca la imagen en un control image
            }
            catch
            {
            }
            try
            {
                string origPath = rtjpg.Text; //guarda la ruta original de la imagen
                string filename = "mdk_fr_" + nid + "_" + idpac.Text + ".jpg"; //nombre que se le dara a la copia
                string target_path = @"c:\medikfile\imagenes\"; // carpeta destino de la imagen
                string dest_file = Path.Combine(target_path + filename); //ruta completa de la copia
                string destPath = dest_file;
                destruta.Text = destPath;
                if (!File.Exists(destPath))
                {
                    File.Delete(destPath);
                    MessageBox.Show("borrado" + destPath);
                }
                else
                {
                    //                /////
                    int bufferSize = 1024 * 1024;
                    using (FileStream fileStream = new FileStream(destPath, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.ReadWrite))
                    {
                        FileStream fs = new FileStream(origPath, FileMode.CreateNew, FileAccess.ReadWrite);
                        fileStream.SetLength(fs.Length);
                        int bytesRead = -1;
                        byte[] bytes = new byte[bufferSize];

                        while ((bytesRead = fs.Read(bytes, 0, bufferSize)) > 0)
                        {
                            fileStream.Write(bytes, 0, bytesRead);
                        }
                    }
                }
            }
            catch (Exception im)
            {
                MessageBox.Show("error " + im);
            }
        }
</code>```

答:
It looks like there is a problem with your delete logic.

```<code>if (!File.Exists(destPath)) // <-- RIGHT HERE
{
    File.Delete(destPath);
    MessageBox.Show("borrado" + destPath);
}
</code>```

You're essentially saying that if the file doesn't exist, delete it.

Maybe it should be this instead:

```<code>if (File.Exists(destPath))
{
    File.Delete(destPath);
    MessageBox.Show("borrado" + destPath);
}
</code>```

Body:
I have an image control that I charge an image via a path saved in a bdd, but if I want to change the image, first I look for the new image with an openfiledialogsends me the error, [the process cannot access the file]
this is my code

OpenFileDialog openFileDialog = new OpenFileDialog();
        openFileDialog.Multiselect = false;
        openFileDialog.Filter = "Image files (*.;*.jpg)|*.jpg;*.png|All files (*.*)|*.*";
        openFileDialog.FilterIndex = 1;
        openFileDialog.RestoreDirectory = true;
        bool? checarOK = openFileDialog.ShowDialog();
        if (checarOK == true)
        {
            try
            {
                string archivo = openFileDialog.FileName;  //nombre archivo seleccionado
                rtjpg.Text = archivo; //ruta de archivo seleccionado en un textbox
                imgfoto.Source = new BitmapImage(new Uri(openFileDialog.FileName)); //coloca la imagen en un control image
            }
            catch
            {
            }
            try
            {
                string origPath = rtjpg.Text; //guarda la ruta original de la imagen
                string filename = "mdk_fr_" + nid + "_" + idpac.Text + ".jpg"; //nombre que se le dara a la copia
                string target_path = @"c:\medikfile\imagenes\"; // carpeta destino de la imagen
                string dest_file = Path.Combine(target_path + filename); //ruta completa de la copia
                string destPath = dest_file;
                destruta.Text = destPath;
                if (!File.Exists(destPath))
                {
                    File.Delete(destPath);
                    MessageBox.Show("borrado" + destPath);
                }
                else
                {
                    //                /////
                    int bufferSize = 1024 * 1024;
                    using (FileStream fileStream = new FileStream(destPath, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.ReadWrite))
                    {
                        FileStream fs = new FileStream(origPath, FileMode.CreateNew, FileAccess.ReadWrite);
                        fileStream.SetLength(fs.Length);
                        int bytesRead = -1;
                        byte[] bytes = new byte[bufferSize];

                        while ((bytesRead = fs.Read(bytes, 0, bufferSize)) > 0)
                        {
                            fileStream.Write(bytes, 0, bytesRead);
                        }
                    }
                }
            }
            catch (Exception im)
            {
                MessageBox.Show("error " + im);
            }
        }

Body:
It looks like there is a problem with your delete logic.

if (!File.Exists(destPath)) // <-- RIGHT HERE
{
    File.Delete(destPath);
    MessageBox.Show("borrado" + destPath);
}

You're essentially saying that if the file doesn't exist, delete it.

Maybe it should be this instead:

if (File.Exists(destPath))
{
    File.Delete(destPath);
    MessageBox.Show("borrado" + destPath);
}