问:
How to create a score board js for my game
I'm just starting to learn how to code, I've been working on a game battleship like, I have managed to do most of the things but I can't make my scoreboard work, I would like to know how to do it or what do I need to change in order for making it work.
I've tried adding var drawScore but when I add it to my game board disappears.
Also, I speak Spanish so part of my code is in that language.

var rows = 8;
var cols = 8;
var squareSize = 55;
var aciertos=0;
var  errores=0;

var gameBoardContainer = document.getElementById("gameboard");

// Columnas y Filas
for (i = 0; i < cols; i++) {
 for (j = 0; j < rows; j++) {

  var square = document.createElement("div");
  gameBoardContainer.appendChild(square);

  square.id = 's' + j + i;

  var topPosition = j * squareSize;
  var leftPosition = i * squareSize;

  square.style.top = topPosition + 'px';
  square.style.left = leftPosition + 'px';
 }

}

var hitCount = 0;
var missCount= 0;

/*

   0 = vacio, 1 = Barco , 2 = Barco Hundiso, 3 = Tiro fallido
*/
var gameBoard = [
    [0,0,0,1,1,1,1,0],
    [0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,1,0],
    [0,0,0,0,0,0,1,0],
    [1,0,0,0,0,0,0,0],
    [1,0,0,0,0,0,0,0],
    [1,0,0,0,0,0,0,0]

    ]

gameBoardContainer.addEventListener("click", fireTorpedo, false);

function fireTorpedo(e) {

 if (e.target !== e.currentTarget) {

  var row = e.target.id.substring(1,2);
  var col = e.target.id.substring(2,3);

  if (gameBoard[row][col] == 0) {
   e.target.style.backgroundImage = "url('agua.png')";
   // se indica que hay un tiro fallido
   gameBoard[row][col] = 3;
            missCount++;
   if (missCount == 8) {
    alert("Perdiste");
            errores=errores+1;
            }

  // Se cambia el color del cuadro si se da click en uno con barco  y se cambia el valor del cuadro
  } else if (gameBoard[row][col] == 1) {
   e.target.style.backgroundImage = "url('explo.png')";
   // El valor cambia a 2 si el barco fue "golpeado"
   gameBoard[row][col] = 2;

   // Se incrementa el valor si otra parte se ha "golpeado"
   hitCount++;
   if (hitCount == 9) {
    alert("Todas las naves enemigas fueron derrotadas! Ganaste!");

   }

  // Alerta si el jugador dio click en un cuadro previamente seleccionado
  } else if (gameBoard[row][col] > 1) {
   alert("No gastes tus torpedos! Ya disparaste aquí.");
  }

        // Si se gana o pierde, el juego se reinicia
        if ((hitCount==9) || (missCount==8))location.href="Battleship.html";
    }
    aciertos==hitCount;
    errores==missCount;
    //Coloca las puntuaciones
    if ((missCount >= 1) ) {

   errores=missCount+1;
   document.puntuacion.errores.value=errores;}

     if ((hitCount >= 1)) {
    aciertos=parseInt(document.puntuacion.aciertos.value);
   aciertos=aciertos+1;
   document.puntuacion.aciertos.value=aciertos;};

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
    margin: 60px auto;
    width: 70%;
    max-width: 950px;
}

h1 {
    font-size: 3em;
    font-family:'Helvetica', 'Arial', 'Sans-Serif';
}

p, button, input {
    font-size: 1.5em;
    line-height: 1.4em;
    color: #333;
 margin-bottom:1em;
}

#gameboard {
 position:relative;
 margin:0 auto 2em auto;
 width:500px;
 height:500px;

    }

#gameboard div {
 position:absolute;

 -moz-box-sizing: border-box;    /* Firefox 1 - 28 */
 box-sizing: border-box;         /* Safari 5.1+, Chrome 10+, Firefox 29+, Opera 7+, IE 8+, Android 4.0+, iOS any */
 background: #add3e6; /* Old browsers */
 border: 1px solid #ddd;
 width:50px;
 height:50px;
}
#gameboard div:hover
{
     color: white;
 background-image: url(mira.png) ;
}</code>```

<!DOCTYPE html>

  <title>Battleship</title>
  <link rel="stylesheet" type="text/css" href="style.css">

  <form name="inicia">

Instrucciones:

                  Coloque el cursor sobre alguno de los cuadros y haga click;

                  La siguiente imagen  aparecerá si en el cuadro no hay un barco
Si el cuadro tiene un barco aparecerá la siguiente imagen .

                Usted debe encontrar los siguientes 3 barcos: uno de dos posiciones (dos celdas), uno de tres posiciones y uno de 4 posiciones, los barcos pueden estar en posición vertical (|) u horizontal (--)

                Si usted comete 8 errores el juego terminará.

                <form name="puntuacion">

                    Puntaje

Aciertos

        <input name="aciertos" type="text" size="3" class="campo" readonly="true" disabled="true" style="background: #9efaf3">

Errores

        <input name="errores" type="text" size="3" class="campo" readonly="true" disabled="true" style="background: #f47f53">

</form>

```

答:
You need to the input for the miss counter and the input for the hit counter.
After that you need to set the input value every time a miss or a hit occur.</p>

```<code>var rows = 8;
var cols = 8;
var squareSize = 55;
var aciertos=0;
var  errores=0;

var gameBoardContainer = document.getElementById("gameboard");

// Here you get the inputs, you need to set the id's in the html code.
var hitCountInputElement = document.getElementById('aciertos');
var missCountInputElement = document.getElementById('errores');

var hitCount = 0;
var missCount= 0;

/*
   0 = vacio, 1 = Barco , 2 = Barco Hundiso, 3 = Tiro fallido
*/
var gameBoard = [
  [0,0,0,1,1,1,1,0],
  [0,0,0,0,0,0,0,0],
  [0,0,0,0,0,0,0,0],
  [0,0,0,0,0,0,1,0],
  [0,0,0,0,0,0,1,0],
  [1,0,0,0,0,0,0,0],
  [1,0,0,0,0,0,0,0],
  [1,0,0,0,0,0,0,0]
]

// Columnas y Filas
for (i = 0; i < cols; i++) {
  for (j = 0; j < rows; j++) {
    var square = document.createElement("div");
    gameBoardContainer.appendChild(square);
    square.id = 's' + j + i;

    var topPosition = j * squareSize;
    var leftPosition = i * squareSize;

    square.style.top = topPosition + 'px';
    square.style.left = leftPosition + 'px';
  }
}

gameBoardContainer.addEventListener("click", fireTorpedo, false);

function fireTorpedo(e) {
  if (e.target !== e.currentTarget) {
    var row = e.target.id.substring(1,2);
    var col = e.target.id.substring(2,3);

    if (gameBoard[row][col] == 0) {
      e.target.style.backgroundImage = "url('agua.png')";
      // se indica que hay un tiro fallido
      gameBoard[row][col] = 3;
      missCount++;
      // Here is where you set the input miss count value
      setMissCountInputElementValue(missCount);
      if (missCount == 8) {
        alert("Perdiste");
        errores=errores+1;
      }

      // Se cambia el color del cuadro si se da click en uno con barco  y se cambia el valor del cuadro
    } else if (gameBoard[row][col] == 1) {
      e.target.style.backgroundImage = "url('explo.png')";
      // El valor cambia a 2 si el barco fue "golpeado"
      gameBoard[row][col] = 2;

      // Se incrementa el valor si otra parte se ha "golpeado"
      hitCount++;
      // Here is where you set the input hit count value
      setHitCountInputElementValue(hitCount);
      if (hitCount == 9) {
        alert("Todas las naves enemigas fueron derrotadas! Ganaste!");
      }

      // Alerta si el jugador dio click en un cuadro previamente seleccionado
    } else if (gameBoard[row][col] > 1) {
      alert("No gastes tus torpedos! Ya disparaste aquí.");
    }

    // Si se gana o pierde, el juego se reinicia
    if ((hitCount==9) || (missCount==8)) {
      location.href="Battleship.html"
    };
  }

  aciertos==hitCount;
  errores==missCount;

  //Coloca las puntuaciones
  if ((missCount >= 1) ) {
    errores=missCount+1;
    document.puntuacion.errores.value=errores;
  }

  if ((hitCount >= 1)) {
    aciertos=parseInt(document.puntuacion.aciertos.value);
    aciertos=aciertos+1;
    document.puntuacion.aciertos.value=aciertos;
  }
}

function setHitCountInputElementValue (hitCount) {
  hitCountInputElement.value = hitCount;
}

function setMissCountInputElementValue (missCount) {
  missCountInputElement.value = missCount;
}
</code>```

Body:
I'm just starting to learn how to code, I've been working on a game battleship like, I have managed to do most of the things but I can't make my scoreboard work, I would like to know how to do it or what do I need to change in order for making it work.
I've tried adding var drawScore but when I add it to my game board disappears.
Also, I speak Spanish so part of my code is in that language.

var rows = 8;
var cols = 8;
var squareSize = 55;
var aciertos=0;
var  errores=0;

var gameBoardContainer = document.getElementById("gameboard");

// Columnas y Filas
for (i = 0; i < cols; i++) {
 for (j = 0; j < rows; j++) {

  var square = document.createElement("div");
  gameBoardContainer.appendChild(square);

  square.id = 's' + j + i;

  var topPosition = j * squareSize;
  var leftPosition = i * squareSize;

  square.style.top = topPosition + 'px';
  square.style.left = leftPosition + 'px';
 }

}

var hitCount = 0;
var missCount= 0;

/*

   0 = vacio, 1 = Barco , 2 = Barco Hundiso, 3 = Tiro fallido
*/
var gameBoard = [
    [0,0,0,1,1,1,1,0],
    [0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,1,0],
    [0,0,0,0,0,0,1,0],
    [1,0,0,0,0,0,0,0],
    [1,0,0,0,0,0,0,0],
    [1,0,0,0,0,0,0,0]

    ]

gameBoardContainer.addEventListener("click", fireTorpedo, false);

function fireTorpedo(e) {

 if (e.target !== e.currentTarget) {

  var row = e.target.id.substring(1,2);
  var col = e.target.id.substring(2,3);

  if (gameBoard[row][col] == 0) {
   e.target.style.backgroundImage = "url('agua.png')";
   // se indica que hay un tiro fallido
   gameBoard[row][col] = 3;
            missCount++;
   if (missCount == 8) {
    alert("Perdiste");
            errores=errores+1;
            }

  // Se cambia el color del cuadro si se da click en uno con barco  y se cambia el valor del cuadro
  } else if (gameBoard[row][col] == 1) {
   e.target.style.backgroundImage = "url('explo.png')";
   // El valor cambia a 2 si el barco fue "golpeado"
   gameBoard[row][col] = 2;

   // Se incrementa el valor si otra parte se ha "golpeado"
   hitCount++;
   if (hitCount == 9) {
    alert("Todas las naves enemigas fueron derrotadas! Ganaste!");

   }

  // Alerta si el jugador dio click en un cuadro previamente seleccionado
  } else if (gameBoard[row][col] > 1) {
   alert("No gastes tus torpedos! Ya disparaste aquí.");
  }

        // Si se gana o pierde, el juego se reinicia
        if ((hitCount==9) || (missCount==8))location.href="Battleship.html";
    }
    aciertos==hitCount;
    errores==missCount;
    //Coloca las puntuaciones
    if ((missCount >= 1) ) {

   errores=missCount+1;
   document.puntuacion.errores.value=errores;}

     if ((hitCount >= 1)) {
    aciertos=parseInt(document.puntuacion.aciertos.value);
   aciertos=aciertos+1;
   document.puntuacion.aciertos.value=aciertos;};

}

body {
    margin: 60px auto;
    width: 70%;
    max-width: 950px;
}

h1 {
    font-size: 3em;
    font-family:'Helvetica', 'Arial', 'Sans-Serif';
}

p, button, input {
    font-size: 1.5em;
    line-height: 1.4em;
    color: #333;
 margin-bottom:1em;
}

#gameboard {
 position:relative;
 margin:0 auto 2em auto;
 width:500px;
 height:500px;

    }

#gameboard div {
 position:absolute;

 -moz-box-sizing: border-box;    /* Firefox 1 - 28 */
 box-sizing: border-box;         /* Safari 5.1+, Chrome 10+, Firefox 29+, Opera 7+, IE 8+, Android 4.0+, iOS any */
 background: #add3e6; /* Old browsers */
 border: 1px solid #ddd;
 width:50px;
 height:50px;
}
#gameboard div:hover
{
     color: white;
 background-image: url(mira.png) ;
}

<!DOCTYPE html>

  <title>Battleship</title>
  <link rel="stylesheet" type="text/css" href="style.css">

  <form name="inicia">

Instrucciones:

                  Coloque el cursor sobre alguno de los cuadros y haga click;

                  La siguiente imagen  aparecerá si en el cuadro no hay un barco
Si el cuadro tiene un barco aparecerá la siguiente imagen .

                Usted debe encontrar los siguientes 3 barcos: uno de dos posiciones (dos celdas), uno de tres posiciones y uno de 4 posiciones, los barcos pueden estar en posición vertical (|) u horizontal (--)

                Si usted comete 8 errores el juego terminará.

                <form name="puntuacion">

                    Puntaje

Aciertos

        <input name="aciertos" type="text" size="3" class="campo" readonly="true" disabled="true" style="background: #9efaf3">

Errores

        <input name="errores" type="text" size="3" class="campo" readonly="true" disabled="true" style="background: #f47f53">

</form>

Body:
You need to the input for the miss counter and the input for the hit counter.
After that you need to set the input value every time a miss or a hit occur.

var rows = 8;
var cols = 8;
var squareSize = 55;
var aciertos=0;
var  errores=0;

var gameBoardContainer = document.getElementById("gameboard");

// Here you get the inputs, you need to set the id's in the html code.
var hitCountInputElement = document.getElementById('aciertos');
var missCountInputElement = document.getElementById('errores');

var hitCount = 0;
var missCount= 0;

/*
   0 = vacio, 1 = Barco , 2 = Barco Hundiso, 3 = Tiro fallido
*/
var gameBoard = [
  [0,0,0,1,1,1,1,0],
  [0,0,0,0,0,0,0,0],
  [0,0,0,0,0,0,0,0],
  [0,0,0,0,0,0,1,0],
  [0,0,0,0,0,0,1,0],
  [1,0,0,0,0,0,0,0],
  [1,0,0,0,0,0,0,0],
  [1,0,0,0,0,0,0,0]
]

// Columnas y Filas
for (i = 0; i < cols; i++) {
  for (j = 0; j < rows; j++) {
    var square = document.createElement("div");
    gameBoardContainer.appendChild(square);
    square.id = 's' + j + i;

    var topPosition = j * squareSize;
    var leftPosition = i * squareSize;

    square.style.top = topPosition + 'px';
    square.style.left = leftPosition + 'px';
  }
}

gameBoardContainer.addEventListener("click", fireTorpedo, false);

function fireTorpedo(e) {
  if (e.target !== e.currentTarget) {
    var row = e.target.id.substring(1,2);
    var col = e.target.id.substring(2,3);

    if (gameBoard[row][col] == 0) {
      e.target.style.backgroundImage = "url('agua.png')";
      // se indica que hay un tiro fallido
      gameBoard[row][col] = 3;
      missCount++;
      // Here is where you set the input miss count value
      setMissCountInputElementValue(missCount);
      if (missCount == 8) {
        alert("Perdiste");
        errores=errores+1;
      }

      // Se cambia el color del cuadro si se da click en uno con barco  y se cambia el valor del cuadro
    } else if (gameBoard[row][col] == 1) {
      e.target.style.backgroundImage = "url('explo.png')";
      // El valor cambia a 2 si el barco fue "golpeado"
      gameBoard[row][col] = 2;

      // Se incrementa el valor si otra parte se ha "golpeado"
      hitCount++;
      // Here is where you set the input hit count value
      setHitCountInputElementValue(hitCount);
      if (hitCount == 9) {
        alert("Todas las naves enemigas fueron derrotadas! Ganaste!");
      }

      // Alerta si el jugador dio click en un cuadro previamente seleccionado
    } else if (gameBoard[row][col] > 1) {
      alert("No gastes tus torpedos! Ya disparaste aquí.");
    }

    // Si se gana o pierde, el juego se reinicia
    if ((hitCount==9) || (missCount==8)) {
      location.href="Battleship.html"
    };
  }

  aciertos==hitCount;
  errores==missCount;

  //Coloca las puntuaciones
  if ((missCount >= 1) ) {
    errores=missCount+1;
    document.puntuacion.errores.value=errores;
  }

  if ((hitCount >= 1)) {
    aciertos=parseInt(document.puntuacion.aciertos.value);
    aciertos=aciertos+1;
    document.puntuacion.aciertos.value=aciertos;
  }
}

function setHitCountInputElementValue (hitCount) {
  hitCountInputElement.value = hitCount;
}

function setMissCountInputElementValue (missCount) {
  missCountInputElement.value = missCount;
}


来源: stackexchange

问:
For a large project, what planning should be done before coding and how should it be approached?
What is your method of "mapping out" an idea before creating it?

Say I wanted to take on a big project, for example at the scale of a site like Facebook or MySpace.  What planning/design steps should I take before I start the actual work?

For example, should I map everything out page by page (their functionalities, data, etc.)?

答:
Usually I do a mindmap of

problem I am trying to solve,

translated into exact requirements,

then mapping that to user workflows.

The cross linking features of mindmapping softwares make it lot easy. Since mindmapping is 'kind of freeform', I end up concentrating on the 'task' rather than 'representation' (e.g which type of UML diagram should I use to represent this) ?

Once initial ideas are clear then I can work on project plan, spec/design documents using UML for more low level details. This approach usually works well for me.

To see if it works for you or not, you can use FreeMind (opensource mindmaping software, good but currently limited functionality). Then You can try Mindmanager or iMindmap for mindmaping. Both integrate well with other Office products.

OwnerDisplayName: sarmenhb

LastEditorDisplayName: Hanno Fietz

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Nitin Bhide


问:
how to to connect and use JDBCUtil
hi
i want to use Class JDBCUtil in java language and eclips workspace and I have the below code:

```<code>import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class JDBCUtil {

static final String CONN_STR = "jdbc:hsqldb:hsql://localhost/";

static {
    try {
        Class.forName("org.hsqldb.jdbcDriver");
    } catch (ClassNotFoundException ex) {
        System.err.println("Unable to load HSQL JDBC driver");
    }
}

public static Connection getConnection() throws SQLException {
    return DriverManager.getConnection(CONN_STR);
}
</code>```

}

but when I run it, I get the below Exception:

```<code>Unable to load HSQL JDBC driver
Exception in thread "main" java.lang.NullPointerException
    at domain.EnrollCtrl.getCurrentOfferings(EnrollCtrl.java:78)
    at ui.UI.main(UI.java:28)
</code>```

in addition there is UI and EnrollCtrl and another file in this project but the error is in this path.
how can i fix this error? should I do sth for connectin to  jdbc:hsqldb:hsql://localhost/?
thank U

答:
The chances are that you are missing the hsqldb.jar file from your classpath or some other environmental issue.

It is difficult to be certain as your question is incredibly specific to your code and environment.

ContentLicense: CC BY-SA 3.0

Title: how to to connect and use JDBCUtil

Body:
hi
i want to use Class JDBCUtil in java language and eclips workspace and I have the below code:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class JDBCUtil {

static final String CONN_STR = "jdbc:hsqldb:hsql://localhost/";

static {
    try {
        Class.forName("org.hsqldb.jdbcDriver");
    } catch (ClassNotFoundException ex) {
        System.err.println("Unable to load HSQL JDBC driver");
    }
}

public static Connection getConnection() throws SQLException {
    return DriverManager.getConnection(CONN_STR);
}

}

but when I run it, I get the below Exception:

Unable to load HSQL JDBC driver
Exception in thread "main" java.lang.NullPointerException
    at domain.EnrollCtrl.getCurrentOfferings(EnrollCtrl.java:78)
    at ui.UI.main(UI.java:28)

in addition there is UI and EnrollCtrl and another file in this project but the error is in this path.
how can i fix this error? should I do sth for connectin to  jdbc:hsqldb:hsql://localhost/?
thank U


问:
Question about array elements and incrementing in C
I have this code:

```<code>#include <stdio.h>

int main(){
   int a[5] = {5, 1, 15, 20, 25};
   int i, j, k = 1, m;
   i = ++a[1];
   j = a[1]++;
   m = a[i++];
   printf("\n%d %d %d", i, j, m);

   return 0;
}
</code>```

The output is: 3 2 15.

Why is that? Shouldn't ++a[1] be 2, a[1]++ is 2, and a[i++] should be 20 because it's a at index 3?

So why is the output not 2 2 20.

Thanks!

答: When a[i++] is evaluated, i has the value of 2. So the value of this expression is the same as a[2], which is 15. The side effect of this expression is a post-increment of i; this side effect will increment i to the value of 3 and takes effect after the expression-value of 15 got evaluated.

ContentLicense: CC BY-SA 4.0

Body:
I have this code:

#include <stdio.h>

int main(){
   int a[5] = {5, 1, 15, 20, 25};
   int i, j, k = 1, m;
   i = ++a[1];
   j = a[1]++;
   m = a[i++];
   printf("\n%d %d %d", i, j, m);

   return 0;
}

The output is: 3 2 15.

Why is that? Shouldn't ++a[1] be 2, a[1]++ is 2, and a[i++] should be 20 because it's a at index 3?

So why is the output not 2 2 20.

Thanks!


问:
How would I round a number (eg: 2.12) to the nearest tenth (2.1) in JS
I am trying to do this but is all I have found is rounding to the nearest whole number. I was wondering if there was a way to do this with math.round or if there is a different solution. Thanks!</p>

答:
```<code>Math.round(X);           // round X to an integer
Math.round(10*X)/10;     // round X to tenths
Math.round(100*X)/100;   // round X to hundredths
Math.round(1000*X)/1000; // round X to thousandths
</code>```


问:
How to fix "undefined method `as_png'" for rqrcode gem
I'm getting this error when I try to use the rqrcode gem to turn a QR code into a PNG file:

```<code>undefined method `as_png' for #<RQRCodeCore::QRCode:0x00007f90b42ec330>
</code>```

Here is the code:

```<code>self.secure_hex = SecureRandom.hex
    self.qr_code = RQRCodeCore::QRCode.new("https://app.mapviapp.com/check_ins/new?d=#{self.secure_hex}")
    self.qr_code_image = RQRCodeCore::QRCode.new("https://app.mapviapp.com/check_ins/new?d=#{self.secure_hex}").as_png
</code>```

and the API documentation.

Any thoughts on what could be going wrong?

答:
I'm not sure why you're initializing RGRCodeCore::QRCode instead of RQRCode::QRCode as dinjas pointed out. Try changing it this way as the documentation suggests to do:

```<code>require 'rqrcode'
self.secure_hex = SecureRandom.hex
self.qr_code = RQRCode::QRCode.new("https://app.mapviapp.com/check_ins/new?d=#{self.secure_hex}")
self.qr_code_image = RQRCode::QRCode.new("https://app.mapviapp.com/check_ins/new?d=#{self.secure_hex}").as_png
</code>```

Also, in the code you shared, you create an instance of self.qr_code, which contains the exact string as the self.qr_code_image instance. Are you sure you need that?

Body:
I'm getting this error when I try to use the rqrcode gem to turn a QR code into a PNG file:

undefined method `as_png' for #<RQRCodeCore::QRCode:0x00007f90b42ec330>

Here is the code:

self.secure_hex = SecureRandom.hex
    self.qr_code = RQRCodeCore::QRCode.new("https://app.mapviapp.com/check_ins/new?d=#{self.secure_hex}")
    self.qr_code_image = RQRCodeCore::QRCode.new("https://app.mapviapp.com/check_ins/new?d=#{self.secure_hex}").as_png

and the API documentation.

Any thoughts on what could be going wrong?

Body:
I'm not sure why you're initializing RGRCodeCore::QRCode instead of RQRCode::QRCode as dinjas pointed out. Try changing it this way as the documentation suggests to do:

require 'rqrcode'
self.secure_hex = SecureRandom.hex
self.qr_code = RQRCode::QRCode.new("https://app.mapviapp.com/check_ins/new?d=#{self.secure_hex}")
self.qr_code_image = RQRCode::QRCode.new("https://app.mapviapp.com/check_ins/new?d=#{self.secure_hex}").as_png

Also, in the code you shared, you create an instance of self.qr_code, which contains the exact string as the self.qr_code_image instance. Are you sure you need that?


问:
No reducer provided for key {name}
I have set up my redux store and everything seems alright all imports and exports seems correct to me but I do not seem to have a valid reducer and sagas. Been stuck, what am I doing wrong?

I get this error message

I have a store with the file structure below

Store

configStore.js

index.js

```<code>import { applyMiddleware, compose, createStore } from 'redux';
import createSagaMiddleware from 'redux-saga';
import rootReducer from '../components/rootReducer';

export default function configureStore(initialState) {
    const sagaMiddleware = createSagaMiddleware();
    const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
    return {
        ...createStore(
            rootReducer,
            initialState,
            composeEnhancers(applyMiddleware(sagaMiddleware)),
        ),
        runSaga: sagaMiddleware.run,
    };
}
</code>```

```<code>
import configureStore from './configStore';
import rootSaga from '../components/rootSaga';

const store = configureStore({});
store.runSaga(rootSaga);

export default store;
</code>```

rootSaga

```<code>import { all } from 'redux-saga/effects';

import planets from './planets';

export default function* rootSaga() {
    yield all([
        planets.sagas(),
    ]);
}
</code>```

rootReducer

```<code>import { combineReducers } from 'redux';

import planets from './planets';

export default combineReducers({
    planets: planets.reducers,
});
</code>```

In my components I have

reducers.js

```<code>import { UPDATE_PLANETS, LOAD_PLANETS } from './actionTypes';

const initialState = {
    isPlanetsLoading: false,
    planets: [],
};

export default (state = initialState, { type, payload }) => {
    switch (type) {
        case LOAD_PLANETS:
            return {
                ...state,
                isPlanetsLoading: true,
            };
        case UPDATE_PLANETS:
            return {
                ...state,
                isPlanetsLoading: false,
                planets: payload,
            };
        default:
            return state;
    }
};

</code>```

Planets.js

```<code>import { List } from "antd";
import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { requestPlanets } from '../actions';

const Planets = () => {
  const dispatch = useDispatch();

  const { planets } = useSelector(
    (state) => state.planets
  );
  console.log(planets);

  useEffect(() => {
      dispatch(requestPlanets());
  }, [dispatch, planets]);
// return statement
};

export default Planets;

</code>```

答:
createStore returns the store. So don't spread it. Just associate the output of createStore to an object property say store.

in index.js, destructure the configStore object { store, runSaga }

configStore

export default function configureStore(initialState) {
    const sagaMiddleware = createSagaMiddleware();
    const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
    return {
        store: createStore(
            rootReducer,
            initialState,
            composeEnhancers(applyMiddleware(sagaMiddleware)),
        ),
        runSaga: sagaMiddleware.run,
    };
}
```

<p><strong>index.js</strong></p>

<pre class="lang-js prettyprint-override"><code>import configureStore from './configStore';
import rootSaga from '../components/rootSaga';

const { store, runSaga } = configureStore({});
runSaga(rootSaga);

export default store;
</code>```

Title: No reducer provided for key {name}

Body:
I have set up my redux store and everything seems alright all imports and exports seems correct to me but I do not seem to have a valid reducer and sagas. Been stuck, what am I doing wrong?

I get this error message

I have a store with the file structure below

Store

configStore.js

index.js

import { applyMiddleware, compose, createStore } from 'redux';
import createSagaMiddleware from 'redux-saga';
import rootReducer from '../components/rootReducer';

export default function configureStore(initialState) {
    const sagaMiddleware = createSagaMiddleware();
    const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
    return {
        ...createStore(
            rootReducer,
            initialState,
            composeEnhancers(applyMiddleware(sagaMiddleware)),
        ),
        runSaga: sagaMiddleware.run,
    };
}

import configureStore from './configStore';
import rootSaga from '../components/rootSaga';

const store = configureStore({});
store.runSaga(rootSaga);

export default store;

rootSaga

import { all } from 'redux-saga/effects';

import planets from './planets';

export default function* rootSaga() {
    yield all([
        planets.sagas(),
    ]);
}

rootReducer

import { combineReducers } from 'redux';

import planets from './planets';

export default combineReducers({
    planets: planets.reducers,
});

In my components I have

reducers.js

import { UPDATE_PLANETS, LOAD_PLANETS } from './actionTypes';

const initialState = {
    isPlanetsLoading: false,
    planets: [],
};

export default (state = initialState, { type, payload }) => {
    switch (type) {
        case LOAD_PLANETS:
            return {
                ...state,
                isPlanetsLoading: true,
            };
        case UPDATE_PLANETS:
            return {
                ...state,
                isPlanetsLoading: false,
                planets: payload,
            };
        default:
            return state;
    }
};

Planets.js

import { List } from "antd";
import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { requestPlanets } from '../actions';

const Planets = () => {
  const dispatch = useDispatch();

  const { planets } = useSelector(
    (state) => state.planets
  );
  console.log(planets);

  useEffect(() => {
      dispatch(requestPlanets());
  }, [dispatch, planets]);
// return statement
};

export default Planets;

Body:
createStore returns the store. So don't spread it. Just associate the output of createStore to an object property say store.

in index.js, destructure the configStore object { store, runSaga }

configStore

export default function configureStore(initialState) {
    const sagaMiddleware = createSagaMiddleware();
    const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
    return {
        store: createStore(
            rootReducer,
            initialState,
            composeEnhancers(applyMiddleware(sagaMiddleware)),
        ),
        runSaga: sagaMiddleware.run,
    };
}

index.js

import configureStore from './configStore';
import rootSaga from '../components/rootSaga';

const { store, runSaga } = configureStore({});
runSaga(rootSaga);

export default store;


问:
python: module 'Crypto.Cipher.AES' has no attribute 'MODE_CCM' even though pycrypto installed
pycrypto is installed (when I run pip list one of the result is pycrypto (2.6.1))

and it works but when I would like to use the MODE_CCM it returns: module 'Crypto.Cipher.AES' has no attribute 'MODE_CCM'

My Python version: Python 3.5.2 :: Anaconda 4.2.0 (x86_64)

答:
By using python 3, i solved it by installing pycryptodome (pip3 install pycryptodome).
 No need to replace Crypto by Cryptodome


问:
Avoid overriding eloquent data
This is my collection of data I need:

```<code>$author_id = 12345;

$newsTagCollection = NewsTag::
   ->where('author_id', $author_id);
</code>```

```<code>$postTodaycnt =$newsTagCollection->where('post_date', '>', \Carbon\Carbon::today())->get()->count();

$postWeekcnt =$newsTagCollection->where('post_date', '>', \Carbon\Carbon::now()->subDays(7))->get()->count();

dd($postWeekcnt);

$newsTags = $newsTagCollection->simplePaginate(12);

</code>```

What I'm trying is to avoid calling the Model multiple times and just past post_date on postTodayCount and PostWeekCount. But $postWeekcnt seem to get value same as $postTodaycnt.

How do I not replace the value and get $postTodaycnt, $postWeekcnt and $newsTags value from $newsTagCollection as desired?

Thank you

答:
Good question.

Answer to that is Optimization. Laravel provide Collection which is very helpful when it comes to such scenarios.

```<code>// This will return a *Collection* of NewsTag model.
$newsTagCollection = NewsTag::where('author_id', $author_id)->get(); // One query. Use ->get() here to fetch all the data

// Here no new queries will triggered.
$postTodaycnt = $newsTagCollection->where('post_date', '>', \Carbon\Carbon::today())->count(); // No need to use get() again
$postWeekcnt =$newsTagCollection->where('post_date', '>', \Carbon\Carbon::now()->subDays(7))->count();
</code>```

Title: Avoid overriding eloquent data

Body:
This is my collection of data I need:

$author_id = 12345;

$newsTagCollection = NewsTag::
   ->where('author_id', $author_id);

$postTodaycnt =$newsTagCollection->where('post_date', '>', \Carbon\Carbon::today())->get()->count();

$postWeekcnt =$newsTagCollection->where('post_date', '>', \Carbon\Carbon::now()->subDays(7))->get()->count();

dd($postWeekcnt);

$newsTags = $newsTagCollection->simplePaginate(12);

What I'm trying is to avoid calling the Model multiple times and just past post_date on postTodayCount and PostWeekCount. But $postWeekcnt seem to get value same as $postTodaycnt.

How do I not replace the value and get $postTodaycnt, $postWeekcnt and $newsTags value from $newsTagCollection as desired?

Thank you

Body:
Good question.

Answer to that is Optimization. Laravel provide Collection which is very helpful when it comes to such scenarios.

// This will return a *Collection* of NewsTag model.
$newsTagCollection = NewsTag::where('author_id', $author_id)->get(); // One query. Use ->get() here to fetch all the data

// Here no new queries will triggered.
$postTodaycnt = $newsTagCollection->where('post_date', '>', \Carbon\Carbon::today())->count(); // No need to use get() again
$postWeekcnt =$newsTagCollection->where('post_date', '>', \Carbon\Carbon::now()->subDays(7))->count();


问:
What is "app:layout_constraintHorizontal_bias" used for?
Can anyone please explain what app:layout_constraintHorizontal_bias is used for?

答:
Position View - bias

bias: (constraint area size - view size) distribution ratio.

app:layout_constraintHorizontal_bias="0~1"

0: Attach to the left

1: Attach to the right

0.5: Center (default)

```<code><Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="button1"
    app:layout_constraintHorizontal_bias="0"
    ... />
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="button2"
    app:layout_constraintHorizontal_bias="1"
    ... />
</code>```

Body:
Position View - bias

bias: (constraint area size - view size) distribution ratio.

app:layout_constraintHorizontal_bias="0~1"

0: Attach to the left

1: Attach to the right

0.5: Center (default)

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="button1"
    app:layout_constraintHorizontal_bias="0"
    ... />
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="button2"
    app:layout_constraintHorizontal_bias="1"
    ... />


问:
Commiting directories with VCSCommand plugin when also using NERD Tree
I am using vim 7.3, the NERDTree 4.1 plugin and VCSCommand version 1.99.42.

To commit a directory in VCSCommand you need have the directory buffer open (it's the same with all commands on directories), however whenever I try to open a directory buffer with the NERD Tree plugin installed it refers to the buffer as Nerd_tree_* and not the directory name which I need to make a relevant commit.

How do I prevent this from happening? How do I open a standard directory buffer with NERD tree installed? How do I turn NERD Tree off periodically to perform the command?

Note: I am aware of this stackoverflow question where the dev says he disabled the NERD Tree plugin because he was using Command-T as a file explorer, but I would like to continue to use NERD Tree, there is no mention of disabling NERD Tree in the help.

答:
I use a simple combination:
  When I'm planning for recursive Diff or recursive Commit - I run command :Hexplore, which opens netrw in split-window, navigate to necessary directory and run :VCSCommit or :VCSDiff. That's a simple fix without additional changes or complex manipulations :).</p>


问:
Radio button in ASP.net Core web application
I am trying to learn ASP.net Core (pretty new) and I am trying something like the below scenario.

Having multiple choice options (want to have radio buttons, option to select one for each section)
there can be only one right choice.
When we click submit after selecting one radio button per selection, I need to highlight the correct selections in green and incorrect in red.

I want to have an OnClick which would determine by some name or value which is correct on click and perform this action. I have checked a couple of options but they don't have all these combinations working correctly.

Please suggest the best options using ASP.net Core web application to perform this functionality.

答:
Give me an example or you could try to refer to my code

<!DOCTYPE html>

Display Radio Buttons

<form>

Please select your gender:

  <input type="radio" id="male" name="gender" value="male">
  Male

  <input type="radio" id="female" name="gender" value="female">
  Female

  <input type="radio" id="other" name="gender" value="other">
  Other

Please select your age:

  <input type="radio" id="age1" name="age" value="30">
  0 - 30

    <input type="radio" id="age2" name="age" value="60">
    31 - 60

   <input type="radio" id="age3" name="age" value="100">
   61 - 100

   <input type="submit" value="Submit">

</form>

```

Body:
Give me an example or you could try to refer to my code

<!DOCTYPE html>
<html>
<body>

<h1>Display Radio Buttons</h1>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<form>

  <div id="question1">
   <p>Please select your gender:</p>
 <div id="answer11">
  <input type="radio" id="male" name="gender" value="male">
  <label for="male">Male</label><br>
 </div>
 <div id="answer12">
  <input type="radio" id="female" name="gender" value="female">
  <label for="female">Female</label><br>
 </div>
 <div id="answer13">
  <input type="radio" id="other" name="gender" value="other">
  <label for="other">Other</label>
 </div>
  </div>

  <br>

  <div id="question2">
   <p>Please select your age:</p>
   <div id="answer21">
  <input type="radio" id="age1" name="age" value="30">
  <label for="age1">0 - 30</label><br>
   </div>
   <div id="answer22">
    <input type="radio" id="age2" name="age" value="60">
    <label for="age2">31 - 60</label><br>
   </div>
   <div id="answer23">
   <input type="radio" id="age3" name="age" value="100">
   <label for="age3">61 - 100</label><br><br>
   </div>

   <input type="submit" value="Submit">
  </div>
</form>
<script>
 $("form").submit(function(){
  //alert("Submitted");
  $("body div[id^=question] input[type=radio]").each(function(i, e){
   if($(e).is( ":checked" ))
   {
    // Compare $(e).attr('value') vs your result
    if(true) // right answer
     $(e).parent().css( "background-color", "green" );
    else // wrong answer
     $(e).parent().css( "background-color", "red" );
   }
  })
  return false;
 });
</script>
</body>
</html>


问:
Is there any way to auto configure OCaml Merlin?
It seems that Merlin requires manually configuring it using the .merlin file. IntelliSense does not require anything like that when using VisualStudio (at least when using it with languages like C++/C#/F#). This includes finding implementations of third party libraries. I imagine that this is partly by using the *proj, packages.config files and maybe data emitted by the compiler (but I'm only guessing). Is there anything similar for Merlin (maybe through using the .opam files or an OCaml compiler)?

答: If you build your code with dune - https://dune.readthedocs.io/ - then it will generate the merlin configuration for you. </p>


问:
AsyncStorage functions just producing garbage in react native
So I implemented this code in a file from the react native docs.

```<code>class Storage {

    //store data in 'key'

    store = async (key, data) => {
        try {
            await AsyncStorage.setItem(key, data);
        } catch (error) {
            // Error saving data
            console.log(error.message);
        }
    };

    retrieve = async (key) => {
        try {
            const   value = await AsyncStorage.getItem(key);
            if (value !== null) {
                // We have data!!
                console.log(value);
            }
        } catch (error) {
            // Error retrieving data
            console.log(error.message);
        }
    };

}
</code>```

And this in other I want to use to actually store and retrieve the variables:

```<code>strg.store('test', 'testing');
testing =  strg.retrieve('test');
</code>```

I kept getting an error but then looking it up here I figured out my storage output was an object and not a string as I expected. So I used JSON.stringify(***) and this gibberish came out instead of a "testing".

{"_40":0, "_65":0, "_55":null,"_72":null}
```

edit: I figure out how to use the console to debug and I found out the 'testing' was inside the promise object that comes out of my function. I read a little about async functions and now I want to know how do I extract the values from the promises?

答:
This happened because you are using AsyncStorage - an asynchronous storage system. You have to wait until it done retrieve data from storage to get the proper data.

I think there are two correct ways to get data from your implementation:

Use async with your container function name & await with your function called

```<code>async function getData() {
    ....
    let data = await strg.retrieve('test');
    console.log("data", data);
}
</code>```

or simple use .then():

```<code>strg.retrieve('test').then((data) => {
    console.log("data", data);
    // Handle retrieved data
});
</code>```

Hope that help. :)

Body:
So I implemented this code in a file from the react native docs.

class Storage {

    //store data in 'key'

    store = async (key, data) => {
        try {
            await AsyncStorage.setItem(key, data);
        } catch (error) {
            // Error saving data
            console.log(error.message);
        }
    };

    retrieve = async (key) => {
        try {
            const   value = await AsyncStorage.getItem(key);
            if (value !== null) {
                // We have data!!
                console.log(value);
            }
        } catch (error) {
            // Error retrieving data
            console.log(error.message);
        }
    };

}

And this in other I want to use to actually store and retrieve the variables:

strg.store('test', 'testing');
testing =  strg.retrieve('test');

I kept getting an error but then looking it up here I figured out my storage output was an object and not a string as I expected. So I used JSON.stringify(***) and this gibberish came out instead of a "testing".

{"_40":0, "_65":0, "_55":null,"_72":null}

edit: I figure out how to use the console to debug and I found out the 'testing' was inside the promise object that comes out of my function. I read a little about async functions and now I want to know how do I extract the values from the promises?

Body:
This happened because you are using AsyncStorage - an asynchronous storage system. You have to wait until it done retrieve data from storage to get the proper data.

I think there are two correct ways to get data from your implementation:

Use async with your container function name & await with your function called

async function getData() {
    ....
    let data = await strg.retrieve('test');
    console.log("data", data);
}

or simple use .then():

strg.retrieve('test').then((data) => {
    console.log("data", data);
    // Handle retrieved data
});

Hope that help. :)


问:
How to understand “add(1)(2)(3)=6”?
I am learning curry function in javascript.
And a question occurs to me.

```<code>// how to implement the add function in the below.

add(1)(2)(3) = 6;
add(1, 2, 3)(4) = 10;
add(1)(2)(3)(4)(5) = 15;
</code>```

I've known the implemented code

function add() {
var _args = Array.prototype.slice.call(arguments);
var _adder = function () {
    _args.push(...arguments);
    return _adder;
};
_adder.toString = function () {
    return _args.reduce(function (a, b) {
        return a + b;
    });
}
return _adder;
}
console.log(add(1)(2)(3)(4)(5))    // function
console.log(add(1)(2)(3))          // function
console.log(add(1, 2, 3)(4))       // function

console.log(add(1)(2)(3)(4)(5) == 15)  // true
console.log(add(1)(2)(3) == 6)         // true
console.log(add(1, 2, 3)(4) == 10)     // true

console.log(add(1)(2)(3)(4)(5) === 15)  // false
console.log(add(1)(2)(3) === 6)         // false
console.log(add(1, 2, 3)(4) === 10)     // false```

I know how the implemented code works.
But I am very curious about the question.
From my view, " add(1)(2)(3) = 6; " means that after executing the expression "add(1)(2)(3)", it should return a value which is fully equals to Number 6. But from this question and its implement codes, I may have a misunderstanding about the question. SO, what does the question REALLY mean? This question is often asked by the interviewer.

答:
This comes down to the JavaScript operators.

= does assignment.

=== does a normal equality comparison. A function never equals a number.

== does troublesome type conversions on the two values, then an equality test. It's usually better to avoid it. In this case, those type conversions can convert your curried function to a string, which might call your toString method if its complicated rules make it coerce the first arg to a string, which runs your curried function, and it converts the other argument to a string, and the two strings are equal.

This kind of automatic-conversion-and-hope-for-the-best test is easy to do the wrong thing. Examples:

console.log(add(10)(-10) == '') --> true

console.log(add(10)(20) == 30) --> true

console.log(add(10)(20) == ' 30 ') --> true

console.log(add(10)(20) == 036) --> true

console.log(add(10)(20) == ' 036 ') --> false

console.log(add(10)(20) == ' 36 ') --> false

console.log(add(2)(-2) == []) -> false

console.log(0 == []) --> true

Also see https://stackoverflow.com/a/359509/1682419

Title: How to understand “add(1)(2)(3)=6”?

Body:
I am learning curry function in javascript.
And a question occurs to me.

// how to implement the add function in the below.

add(1)(2)(3) = 6;
add(1, 2, 3)(4) = 10;
add(1)(2)(3)(4)(5) = 15;

I've known the implemented code

function add() {
var _args = Array.prototype.slice.call(arguments);
var _adder = function () {
    _args.push(...arguments);
    return _adder;
};
_adder.toString = function () {
    return _args.reduce(function (a, b) {
        return a + b;
    });
}
return _adder;
}
console.log(add(1)(2)(3)(4)(5))    // function
console.log(add(1)(2)(3))          // function
console.log(add(1, 2, 3)(4))       // function

console.log(add(1)(2)(3)(4)(5) == 15)  // true
console.log(add(1)(2)(3) == 6)         // true
console.log(add(1, 2, 3)(4) == 10)     // true

console.log(add(1)(2)(3)(4)(5) === 15)  // false
console.log(add(1)(2)(3) === 6)         // false
console.log(add(1, 2, 3)(4) === 10)     // false

I know how the implemented code works.
But I am very curious about the question.
From my view, " add(1)(2)(3) = 6; " means that after executing the expression "add(1)(2)(3)", it should return a value which is fully equals to Number 6. But from this question and its implement codes, I may have a misunderstanding about the question. SO, what does the question REALLY mean? This question is often asked by the interviewer.


问:
Optimizing queries for content popularity by hits

I've done some searching for this but haven't come up with anything, maybe someone could point me in the right direction.

I have a website with lots of content in a MySQL database and a PHP script that loads the most popular content by hits. It does this by logging each content hit in a table along with the access time. Then a select query is run to find the most popular content in the past 24 hours, 7 day or maximum 30 days. A cronjob deletes anything older than 30 days in the log table.

The problem I'm facing now is as the website grows the log table has 1m+ hit records and it is really slowing down my select query (10-20s). At first I though the problem was a join I had in the query to get the content title, url, etc. But now I'm not sure as in test removing the join does not speed the query as much as I though it would.

So my question is what is best practise of doing this kind of popularity storing/selecting? Are they any good open source scripts for this? Or what would you suggest?

Table scheme

"popularity" hit log table

  nid | insert_time | tid

  nid: Node ID of the content

  insert_time: timestamp (2011-06-02 04:08:45)

  tid: Term/category ID

"node" content table

  nid | title | status | (there are more but these are the important ones)

  nid: Node ID

  title: content title

  status: is the content published (0=false, 1=true)

SQL

```<code>SELECT node.nid, node.title, COUNT(popularity.nid) AS count
FROM `node` INNER JOIN `popularity` USING (nid)
WHERE node.status = 1
  AND  popularity.insert_time >= DATE_SUB(CURDATE(),INTERVAL 7 DAY)
GROUP BY popularity.nid
ORDER BY count DESC
LIMIT 10;
</code>```

答:
We've just come across a similar situation and this is how we got around it. We decided we didn't really care about what exact 'time' something happened, only the day it happened on. We then did this:

Every record has a 'total hits' record which is incremented every time something happens

A logs table records these 'total hits' per record, per day (in a cron job)

By selecting the difference between two given dates in this log table, we can deduce the 'hits' between two dates, very quickly.

The advantage of this is the size of your log table is only as big as NumRecords * NumDays which in our case is very small. Also any queries on this logs table are very quick.

The disadvantage is you lose the ability to deduce hits by time of day but if you don't need this then it might be worth considering.

Body:
I've done some searching for this but haven't come up with anything, maybe someone could point me in the right direction.

I have a website with lots of content in a MySQL database and a PHP script that loads the most popular content by hits. It does this by logging each content hit in a table along with the access time. Then a select query is run to find the most popular content in the past 24 hours, 7 day or maximum 30 days. A cronjob deletes anything older than 30 days in the log table.

The problem I'm facing now is as the website grows the log table has 1m+ hit records and it is really slowing down my select query (10-20s). At first I though the problem was a join I had in the query to get the content title, url, etc. But now I'm not sure as in test removing the join does not speed the query as much as I though it would.

So my question is what is best practise of doing this kind of popularity storing/selecting? Are they any good open source scripts for this? Or what would you suggest?

Table scheme

"popularity" hit log table

  nid | insert_time | tid

  nid: Node ID of the content

  insert_time: timestamp (2011-06-02 04:08:45)

  tid: Term/category ID

"node" content table

  nid | title | status | (there are more but these are the important ones)

  nid: Node ID

  title: content title

  status: is the content published (0=false, 1=true)

SQL

SELECT node.nid, node.title, COUNT(popularity.nid) AS count
FROM `node` INNER JOIN `popularity` USING (nid)
WHERE node.status = 1
  AND  popularity.insert_time >= DATE_SUB(CURDATE(),INTERVAL 7 DAY)
GROUP BY popularity.nid
ORDER BY count DESC
LIMIT 10;


问:
Parent DIv can't scroll because of Position:Fixed content
I made a mobile web page using IScroll.

The composition of the web page is as follows.

HTML

```<code><div class="wrap">
 <div class="content">

  <div class="a">
    TOP
  </div>
  <div class="item">
    <div class="disable">
      Google Ads
    </div>
  </div>
  <div class="b">
    BOTTOM
  </div>
 </div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
</code>```

CSS

```<code>html, body, .wrap {
  margin: 0px;
  height: 100%;
}

.content {
  height: 100%;
  overflow-y: scroll;
}
.wrap {
  width:100%;
  height:100%;
  background-color:white;
}

.disable {
  position: fixed;
  width:100%;
  height:100%;
  background-color:aqua;
  z-index:1;
}
.a, .b {
  width: 100%;
  height:100px;
  position:relative;

  z-index:2;
}

.a {
  background-color: red;
}

.item {
  width:100%;
  height:100%;
}
.b {
  background-color: blue;
}
</code>```

If you run the code above,

You can scroll by raising the cursor to A and B.

On mobile, you can scroll using touch.

But, So if you raise your cursor over a DIV with Aqua background color and scroll,

I can't scroll.

The DIV, "Position:Fixed," is...

Since the height is 100%, I don't think there's a scroll event.

For your information, Item needs a Click event.

So the "Pointer-Events: None" property is not allowed.

The "Trigger" function can't even give you an event.

Give me an idea.

https://jsfiddle.net/kasthe/b3w2hpn1/3/

答:
Apply pointer-events: none to just the class=disable div.  div class=item is still clickable.

$(".wrap").css("height", $(document).height() + "px");
console.log($(".wrap").height())```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html, body, .wrap {
  margin: 0px;
  height: 100%;
}

.content {
  height: 100%;
  overflow-y: scroll;
}
.wrap {
  width:100%;
  height:100%;
  background-color:white;
}

.disable {
  position: fixed;
  width:100%;
  height:100%;
  background-color:aqua;
  z-index:1;
}
.a, .b {
  width: 100%;
  height:100px;
  position:relative;

  z-index:2;
}

.a {
  background-color: red;
}

.item {
  width:100%;
  height:100%;
}
.b {
  background-color: blue;
}</code>```

    TOP

      Google Ads

    BOTTOM

```

Body:
I made a mobile web page using IScroll.

The composition of the web page is as follows.

HTML

    TOP

      Google Ads

    BOTTOM

CSS

html, body, .wrap {
  margin: 0px;
  height: 100%;
}

.content {
  height: 100%;
  overflow-y: scroll;
}
.wrap {
  width:100%;
  height:100%;
  background-color:white;
}

.disable {
  position: fixed;
  width:100%;
  height:100%;
  background-color:aqua;
  z-index:1;
}
.a, .b {
  width: 100%;
  height:100px;
  position:relative;

  z-index:2;
}

.a {
  background-color: red;
}

.item {
  width:100%;
  height:100%;
}
.b {
  background-color: blue;
}

If you run the code above,

You can scroll by raising the cursor to A and B.

On mobile, you can scroll using touch.

But, So if you raise your cursor over a DIV with Aqua background color and scroll,

I can't scroll.

The DIV, "Position:Fixed," is...

Since the height is 100%, I don't think there's a scroll event.

For your information, Item needs a Click event.

So the "Pointer-Events: None" property is not allowed.

The "Trigger" function can't even give you an event.

Give me an idea.

https://jsfiddle.net/kasthe/b3w2hpn1/3/

Body:
Apply pointer-events: none to just the class=disable div.  div class=item is still clickable.

$(".wrap").css("height", $(document).height() + "px");
console.log($(".wrap").height())

html, body, .wrap {
  margin: 0px;
  height: 100%;
}

.content {
  height: 100%;
  overflow-y: scroll;
}
.wrap {
  width:100%;
  height:100%;
  background-color:white;
}

.disable {
  position: fixed;
  width:100%;
  height:100%;
  background-color:aqua;
  z-index:1;
}
.a, .b {
  width: 100%;
  height:100px;
  position:relative;

  z-index:2;
}

.a {
  background-color: red;
}

.item {
  width:100%;
  height:100%;
}
.b {
  background-color: blue;
}

<div class="wrap">
 <div class="content">

  <div class="a">
    TOP
  </div>
  <div class="item" onclick="alert('item clicked')">
    <div class="disable" style="pointer-events:none">
      Google Ads
    </div>
  </div>
  <div class="b">
    BOTTOM
  </div>
 </div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>


问:
File upload, using Python(Local System) to Google Cloud Storage
I'm literally stuck on some function.
I want to write the code to upload file to Google Cloud Storage using Python, but I don't know where should I start.

I'd looked into docs from everywhere, but it shows only at Google Cloud Shell.

If anyone knows about this, enlighten me please!

Have a good one!

答:
You can do it in this way,

```<code>from gcloud import storage

client = storage.Client()

bucket = client.get_bucket('<your-bucket-name>')

blob = bucket.blob('my-test-file.txt')

filename = "%s/%s" % (folder, filename)
blob = bucket.blob(filename)

# Uploading string of text
blob.upload_from_string('this is test content!')

# Uploading from a local file using open()
with open('photo.jpg', 'rb') as photo:
    blob.upload_from_file(photo)

# Uploading from local file without open()
blob.upload_from_filename('photo.jpg')

blob.make_public()
url = blob.public_url
</code>```

For an explanation of each of the above line check out this blog post (example for the above is taken from this blog):
https://riptutorial.com/google-cloud-storage/example/28256/upload-files-using-python

Body:
You can do it in this way,

from gcloud import storage

client = storage.Client()

bucket = client.get_bucket('<your-bucket-name>')

blob = bucket.blob('my-test-file.txt')

filename = "%s/%s" % (folder, filename)
blob = bucket.blob(filename)

# Uploading string of text
blob.upload_from_string('this is test content!')

# Uploading from a local file using open()
with open('photo.jpg', 'rb') as photo:
    blob.upload_from_file(photo)

# Uploading from local file without open()
blob.upload_from_filename('photo.jpg')

blob.make_public()
url = blob.public_url

For an explanation of each of the above line check out this blog post (example for the above is taken from this blog):
https://riptutorial.com/google-cloud-storage/example/28256/upload-files-using-python


问:
How can I choose which struct member to update at runtime?
Say I have a struct in Go that looks like this:

```<code>LastUpdate struct {
     Name string `yaml:"name"`
     Address string `yaml:"address"`
     Phone string `yaml:"phone"`
}
</code>```

Now say I want to create a function that accepts the name of the field (eg. "Phone") and then updates that field to a value, like today's date.

How can I build the function in a way that it will accept the name of the field and update that field in the struct?

I know that I could do an IF clause for each scenario (if field == "Phone") {var.LastUpdate.Phone = time.Now().Date()}, but I'd like to build this function so that I don't have to go add an IF clause every time I add a new member to this struct in the future. Thoughts?

答:
Use the reflect package to set a field by name.

```<code>// setFieldByName sets field with given name to specified value.
// The structPtr argument must be a pointer to a struct. The
// value argument must be assignable to the field.
func setFieldByName(structPtr interface{}, name string, value interface{}) error {

    v := reflect.ValueOf(structPtr)
    v = v.Elem()            // deference pointer
    v = v.FieldByName(name) // get field with specified name

    if !v.IsValid() {
        return errors.New("field not found")
    }

    v.Set(reflect.ValueOf(value))

    return nil
}
</code>```

Use it like this:

```<code>var lu LastUpdate
setFieldByName(&lu, "Name", "Russ Cox")
</code>```

Run it on the Playground

Body:
Say I have a struct in Go that looks like this:

LastUpdate struct {
     Name string `yaml:"name"`
     Address string `yaml:"address"`
     Phone string `yaml:"phone"`
}

Now say I want to create a function that accepts the name of the field (eg. "Phone") and then updates that field to a value, like today's date.

How can I build the function in a way that it will accept the name of the field and update that field in the struct?

I know that I could do an IF clause for each scenario (if field == "Phone") {var.LastUpdate.Phone = time.Now().Date()}, but I'd like to build this function so that I don't have to go add an IF clause every time I add a new member to this struct in the future. Thoughts?

Body:
Use the reflect package to set a field by name.

// setFieldByName sets field with given name to specified value.
// The structPtr argument must be a pointer to a struct. The
// value argument must be assignable to the field.
func setFieldByName(structPtr interface{}, name string, value interface{}) error {

    v := reflect.ValueOf(structPtr)
    v = v.Elem()            // deference pointer
    v = v.FieldByName(name) // get field with specified name

    if !v.IsValid() {
        return errors.New("field not found")
    }

    v.Set(reflect.ValueOf(value))

    return nil
}

Use it like this:

var lu LastUpdate
setFieldByName(&lu, "Name", "Russ Cox")

Run it on the Playground


问:
Rails 3 image translations with i18n and tolk
I have implemented tolk engine by dhh to add translations and then create .yml files from it. It works well for text.

Now what I want is same behavior over images.

I create follwing structure in my en.yml file -

images:
     logo: "/images/en/logo.png"

and for hi

images:
     logo: "/images/hi/logo.png

and in my views, I have -
   <%= t("images.logo") %>

This also works for showing different images depending on locale.

But I want to add these translations via tolk engine, so that I can directly upload images from there, and they will stored in respective folders. Also when yml files will be created, that will include structures like above.

Is there any tolk fork already doing this ? or people prefer different approach for image translations(replace as per locals) than this ?

答:
Im not familiar with tolk, but what about using the i18n in the path of an image_tag

Something like:

<%= image_tag("images/#{t("i18n")}/logo.png") %>


问:
Configure encryption of data at rest in MongoDB
I have built a 3 node MongoDB 3.2.3 Cluster on RHEL 7.

As encryption is a new feature in this version of MongoDB I have tried enabling it different ways in my config file. Below is a part of my config file:

```<code>net:
  port: 27017
  bindIp: 127.0.0.1,  # Listen to local interface only, comment to listen on all interfaces.

security:
 authorization: enabled
 keyFile: /data/mongodb-keyfile/auth-keyfile

encryption:
 enabled: true
 Keyfile: /data/encryp-keyfile
</code>```

Trying to enable encryption using local keyfile .

When I am trying restart the service with the above configuration, the encryption configuration service is getting terminated.

Can someone guide me how to enable encryption for data at rest in MongoDB?

答:
Add the above configuration.

Delete the Dbpath folder and create the same with proper permissions.

Restart the mongod again.

Body:
I have built a 3 node MongoDB 3.2.3 Cluster on RHEL 7.

As encryption is a new feature in this version of MongoDB I have tried enabling it different ways in my config file. Below is a part of my config file:

net:
  port: 27017
  bindIp: 127.0.0.1,  # Listen to local interface only, comment to listen on all interfaces.

security:
 authorization: enabled
 keyFile: /data/mongodb-keyfile/auth-keyfile

encryption:
 enabled: true
 Keyfile: /data/encryp-keyfile

Trying to enable encryption using local keyfile .

When I am trying restart the service with the above configuration, the encryption configuration service is getting terminated.

Can someone guide me how to enable encryption for data at rest in MongoDB?


问:
How to use single groupId with multiple artifactId in maven?
First dependency is to validate xml file.

```<code><dependency>
 <groupId>xerces</groupId>
 <artifactId>xerces</artifactId>
 <version>2.4.0</version>
</dependency>
</code>```

Second dependency is to write POI object to file.

```<code><dependency>
 <groupId>xerces</groupId>
 <artifactId>xercesImpl</artifactId>
 <version>2.12.0</version>
</dependency>
</code>```

Now, I need a solution like this below :

```<code><dependency>
 <groupId>xerces</groupId>
 <artifactId>xerces</artifactId>
 <artifactId>xercesImpl</artifactId>
 <version>2.12.0</version>
</dependency>
</code>```

Is it possible to achieve this ?

答:
Maven POM schema won't allow you to declare multiple artifacts of the same group in a single declaration. And to be honest, I see no strong motivation to do so, for some reasons:

Once your POM is set up, you won't change it that often.

There are cases where versions also vary between artifacts of the same group. Maven keeps the parsing simple by assuming that it's always different. The downside is that you have to duplicate some lines, but not a huge deal.

It's unlikely that you have that many artifacts of the same group to justify that. Spring could be one of the exceptions, but they offer a Bill of Materials (BoM) that already do most of the heavy lifting.

Note 1: If you are looking for a more compact version of your build, you may have a look at Maven Polyglot that allows you to have more compact build files while still using Maven.

Note 2: An alternative to Maven that would allow for something like that is Gradle. Due to its imperative nature, you can just code it. Beware though, that moving between Maven and Gradle is a big leap, not just translating some scripts. Both tools have their space and should be considered carefully.

Body:
First dependency is to validate xml file.

<dependency>
 <groupId>xerces</groupId>
 <artifactId>xerces</artifactId>
 <version>2.4.0</version>
</dependency>

Second dependency is to write POI object to file.

<dependency>
 <groupId>xerces</groupId>
 <artifactId>xercesImpl</artifactId>
 <version>2.12.0</version>
</dependency>

Now, I need a solution like this below :

<dependency>
 <groupId>xerces</groupId>
 <artifactId>xerces</artifactId>
 <artifactId>xercesImpl</artifactId>
 <version>2.12.0</version>
</dependency>

Is it possible to achieve this ?


问:
Selenium is unable to find element with data-testid attribute
Trying to find the below element tried the following nothing works can anyone help.</p>

```<code><button data-testid="addToClientBasket"
        class="sc-kfGgVZ kcCRfu">
    <span><i class="icon-Expand_Cross_30_by_30"></i>Add To Basket</span>
</button>
</code>```

```<code>By.xpath("//button[@data-testid='addToClientBasket'");

By.xpath("//div[@id='root']/div/div/div/div[4]/div/div/div[2]/button/span";

By.cssSelector("button.sc-kfGgVZ.kcCRfu.added");

By.cssSelector("button.sc-kfGgVZ.kcCR");

By.cssSelector("button[class='sc-kfGgVZ kcCRfu']");

</code>```

答:
Try with the below locators

```<code>button.sc-kfGgVZ.kcCRfu
button[data-testid="addToClientBasket"]

//button[@class='sc-kfGgVZ kcCRfu']
//button[@data-testid="addToClientBasket"]
</code>```

And the reasons why the locators did not worked in your case

By.xpath("//button[@data-testid='addToClientBasket'");

No closing bracket after attribute value

By.xpath("//div[@id='root']/div/div/div/div[4]/div/div/div[2]/button/span";

Not sure if your element path is correct

By.cssSelector("button.sc-kfGgVZ.kcCRfu.added");

There is no button with added classname

By.cssSelector("button.sc-kfGgVZ.kcCR");

There is no button with the specified classes combination

By.cssSelector("button[class='sc-kfGgVZ kcCRfu']");

those are 2 classes so you have to replace the white-space with .

Body:
Trying to find the below element tried the following nothing works can anyone help.

<button data-testid="addToClientBasket"
        class="sc-kfGgVZ kcCRfu">
    Add To Basket
</button>

By.xpath("//button[@data-testid='addToClientBasket'");

By.xpath("//div[@id='root']/div/div/div/div[4]/div/div/div[2]/button/span";

By.cssSelector("button.sc-kfGgVZ.kcCRfu.added");

By.cssSelector("button.sc-kfGgVZ.kcCR");

By.cssSelector("button[class='sc-kfGgVZ kcCRfu']");

Body:
Try with the below locators

button.sc-kfGgVZ.kcCRfu
button[data-testid="addToClientBasket"]

//button[@class='sc-kfGgVZ kcCRfu']
//button[@data-testid="addToClientBasket"]

And the reasons why the locators did not worked in your case

By.xpath("//button[@data-testid='addToClientBasket'");

No closing bracket after attribute value

By.xpath("//div[@id='root']/div/div/div/div[4]/div/div/div[2]/button/span";

Not sure if your element path is correct

By.cssSelector("button.sc-kfGgVZ.kcCRfu.added");

There is no button with added classname

By.cssSelector("button.sc-kfGgVZ.kcCR");

There is no button with the specified classes combination

By.cssSelector("button[class='sc-kfGgVZ kcCRfu']");

those are 2 classes so you have to replace the white-space with .


问:
ElasticSearch_dsl issue
I am trying to integrate elastic within the django existing db. but within the site packages i am facing Errors on running the local server or to view the respective commands.

Below is the versions of packages i m using,
django-elasticsearch-dsl==0.5.0, elasticsearch==6.3.0 and elasticsearch-dsl==6.2.1.

```<code>  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "Desktop/envs/elas_envs/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line
    utility.execute()
  File "Desktop/envs/elas_envs/lib/python3.6/site-packages/django/core/management/__init__.py", line 337, in execute
    django.setup()
  File "/homeDesktop/envs/elas_envs/lib/python3.6/site-packages/django/__init__.py", line 27, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/home/Desktop/envs/elas_envs/lib/python3.6/site-packages/django/apps/registry.py", line 85, in populate
    app_config = AppConfig.create(entry)
  File "/home/Desktop/envs/elas_envs/lib/python3.6/site-packages/django/apps/config.py", line 94, in create
    module = import_module(entry)
  File "/home//Desktop/envs/elas_envs/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/home/Desktop/envs/elas_envs/lib/python3.6/site-packages/django_elasticsearch_dsl/__init__.py", line 3, in <module>
    from .documents import DocType  # noqa
  File "/home/Desktop/envs/elas_envs/lib/python3.6/site-packages/django_elasticsearch_dsl/documents.py", line 8, in <module>
    from elasticsearch_dsl.document import DocTypeMeta as DSLDocTypeMeta
ImportError: cannot import name 'DocTypeMeta'
</code>```

Thanks in advance.

答:
This question is from almost two years ago but this could help others. In latest versions of django_elasticsearch_dsl you need to use Document:</p>

```<code>from django_elasticsearch_dsl import (
    Document,
    fields,
    Index,
)
</code>```

Title: ElasticSearch_dsl issue

Body:
I am trying to integrate elastic within the django existing db. but within the site packages i am facing Errors on running the local server or to view the respective commands.

Below is the versions of packages i m using,
django-elasticsearch-dsl==0.5.0, elasticsearch==6.3.0 and elasticsearch-dsl==6.2.1.

  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "Desktop/envs/elas_envs/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line
    utility.execute()
  File "Desktop/envs/elas_envs/lib/python3.6/site-packages/django/core/management/__init__.py", line 337, in execute
    django.setup()
  File "/homeDesktop/envs/elas_envs/lib/python3.6/site-packages/django/__init__.py", line 27, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/home/Desktop/envs/elas_envs/lib/python3.6/site-packages/django/apps/registry.py", line 85, in populate
    app_config = AppConfig.create(entry)
  File "/home/Desktop/envs/elas_envs/lib/python3.6/site-packages/django/apps/config.py", line 94, in create
    module = import_module(entry)
  File "/home//Desktop/envs/elas_envs/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/home/Desktop/envs/elas_envs/lib/python3.6/site-packages/django_elasticsearch_dsl/__init__.py", line 3, in <module>
    from .documents import DocType  # noqa
  File "/home/Desktop/envs/elas_envs/lib/python3.6/site-packages/django_elasticsearch_dsl/documents.py", line 8, in <module>
    from elasticsearch_dsl.document import DocTypeMeta as DSLDocTypeMeta
ImportError: cannot import name 'DocTypeMeta'

Thanks in advance.

Body:
This question is from almost two years ago but this could help others. In latest versions of django_elasticsearch_dsl you need to use Document:

from django_elasticsearch_dsl import (
    Document,
    fields,
    Index,
)


问:
Unity2 resolve problem
guys.
We are using MS Unity 2 framework for an application.

We have code similar to described below

```<code>public class Context:IContext
{
    public IFlow Flow {get;set;}
}

public class SomeFlow:IFlow
{
    public IContext Context {get;set;}
}
...
//Some code for getting IContext object
{
     ...
     IContext context = container.Resolve<IContext>();
     ...
}
</code>```

We need to describe the relationship between the classes Context and SomeFlow using Unity. And the problem with constructing is while container is constructing Context object it needs to create SomeFlow object which requires Context object and so on.
In our case SomeFlow object must contain link to the Context object created before. So the algorithm must be next:

```<code>1. Create Context object
2. Create SomeFlow object
3. Point Context.Flow to SomeFlow
4. Point SomeFlow.Context to Context
</code>```

And the question is how could we describe it with unity?

答:
You can do this with constructor injection to give the Flow its context, and then in the constructor set up the backwards reference. Here's a simple example:</p>

```<code>public interface IContext { IFlow Flow { get; set; } }
public interface IFlow { IContext Context { get; } }

public class Context : IContext
{
    public IFlow Flow { get; set; }
}

public class SomeFlow : IFlow
{
    public SomeFlow(IContext context)
    {
        this.Context = context;
        context.Flow = this;
    }
    public IContext Context { get; set; }
}

[Test]
public void Example()
{
    IUnityContainer container = new UnityContainer();
    container.RegisterType<IContext, Context>();
    container.RegisterType<IFlow, SomeFlow>();
    var flow = container.Resolve<IFlow>();
    Assert.IsInstanceOf<Context>(flow.Context);
    Assert.IsInstanceOf<SomeFlow>(flow);
    Assert.AreSame(flow, flow.Context.Flow);
}
</code>```

Title: Unity2 resolve problem

Body:
guys.
We are using MS Unity 2 framework for an application.

We have code similar to described below

public class Context:IContext
{
    public IFlow Flow {get;set;}
}

public class SomeFlow:IFlow
{
    public IContext Context {get;set;}
}
...
//Some code for getting IContext object
{
     ...
     IContext context = container.Resolve<IContext>();
     ...
}

We need to describe the relationship between the classes Context and SomeFlow using Unity. And the problem with constructing is while container is constructing Context object it needs to create SomeFlow object which requires Context object and so on.
In our case SomeFlow object must contain link to the Context object created before. So the algorithm must be next:

1. Create Context object
2. Create SomeFlow object
3. Point Context.Flow to SomeFlow
4. Point SomeFlow.Context to Context

And the question is how could we describe it with unity?

Body:
You can do this with constructor injection to give the Flow its context, and then in the constructor set up the backwards reference. Here's a simple example:

public interface IContext { IFlow Flow { get; set; } }
public interface IFlow { IContext Context { get; } }

public class Context : IContext
{
    public IFlow Flow { get; set; }
}

public class SomeFlow : IFlow
{
    public SomeFlow(IContext context)
    {
        this.Context = context;
        context.Flow = this;
    }
    public IContext Context { get; set; }
}

[Test]
public void Example()
{
    IUnityContainer container = new UnityContainer();
    container.RegisterType<IContext, Context>();
    container.RegisterType<IFlow, SomeFlow>();
    var flow = container.Resolve<IFlow>();
    Assert.IsInstanceOf<Context>(flow.Context);
    Assert.IsInstanceOf<SomeFlow>(flow);
    Assert.AreSame(flow, flow.Context.Flow);
}


问:
Load CSS into a PHP file
everybody. I am following a tutorial to create a register and login system, I am doing it for the first time. I am not being able to style the HTML form that is in the PHP file. I just have one folder with 6 files (error.php, index.php, login.php, register.php, server.php, style.css)
So far I have just wrote code in the register.php and style.css files.
And I get this messages from the console in the register.php file:
1- "The stylesheet http://localhost/registration/register.php/style.css was loaded as CSS even though its MIME type, “text/html”, is not “text/css”."

2- "Ruleset ignored due to bad selector."

What's wrong? I am working with XAMPP

This is the code:

register.php:

```<code><?php
include('server.php');
?>
<!DOCTYPE html>
<html>
<head>
<title>Registration system PHP and MySQL</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="header">
  <h2>Register</h2>
</div>

<form method="post" action="register.php">
<?php
include('errors.php');
?>
 <div class="input-group">
    <label>Username</label>
    <input type="text" name="username" value="<?php
echo $username;
?>">
  </div>
  <div class="input-group">
    <label>Email</label>
    <input type="email" name="email" value="<?php
echo $email;
?>">
  </div>
  <div class="input-group">
    <label>Password</label>
    <input type="password" name="password_1">
  </div>
  <div class="input-group">
    <label>Confirm password</label>
    <input type="password" name="password_2">
  </div>
  <div class="input-group">
    <button type="submit" class="btn" name="reg_user">Register</button>
  </div>
  <p>
      Already a member? <a href="login.php">Sign in</a>
  </p>
  </form>
</body>
</html>
</code>```

style.css:

```<code>    * {
  margin: 0px;
  padding: 0px;
}
body {
  font-size: 120%;
  background: #F8F8FF;
}

.header {
  width: 30%;
  margin: 50px auto 0px;
  color: white;
  background: #5F9EA0;
  text-align: center;
  border: 1px solid #B0C4DE;
  border-bottom: none;
  border-radius: 10px 10px 0px 0px;
  padding: 20px;
}
form, .content {
  width: 30%;
  margin: 0px auto;
  padding: 20px;
  border: 1px solid #B0C4DE;
  background: white;
  border-radius: 0px 0px 10px 10px;
}
.input-group {
  margin: 10px 0px 10px 0px;
}
.input-group label {
  display: block;
  text-align: left;
  margin: 3px;
}
.input-group input {
  height: 30px;
  width: 93%;
  padding: 5px 10px;
  font-size: 16px;
  border-radius: 5px;
  border: 1px solid gray;
}
.btn {
  padding: 10px;
  font-size: 15px;
  color: white;
  background: #5F9EA0;
  border: none;
  border-radius: 5px;
}
.error {
  width: 92%;
  margin: 0px auto;
  padding: 10px;
  border: 1px solid #a94442;
  color: #a94442;
  background: #f2dede;
  border-radius: 5px;
  text-align: left;
}
.success {
  color: #3c763d;
  background: #dff0d8;
  border: 1px solid #3c763d;
  margin-bottom: 20px;
}
</code>```

答:
There two ways that you can try

Replace your line

<link rel="stylesheet" type="text/css" href="style.css">

With

1: Point to current directory

<link rel="stylesheet" type="text/css" href="./style.css">

2: Point from root directory

<link rel="stylesheet" type="text/css" href="/registration/style.css">

Because your css file is in the folder /registration/, not /registration/register.php/

Title: Load CSS into a PHP file

Body:
everybody. I am following a tutorial to create a register and login system, I am doing it for the first time. I am not being able to style the HTML form that is in the PHP file. I just have one folder with 6 files (error.php, index.php, login.php, register.php, server.php, style.css)
So far I have just wrote code in the register.php and style.css files.
And I get this messages from the console in the register.php file:
1- "The stylesheet http://localhost/registration/register.php/style.css was loaded as CSS even though its MIME type, “text/html”, is not “text/css”."

2- "Ruleset ignored due to bad selector."

What's wrong? I am working with XAMPP

This is the code:

register.php:

<?php
include('server.php');
?>
<!DOCTYPE html>

<title>Registration system PHP and MySQL</title>
<link rel="stylesheet" type="text/css" href="style.css">

Register

<form method="post" action="register.php">
<?php
include('errors.php');
?>

    Username
    <input type="text" name="username" value="<?php
echo $username;
?>">

    Email
    <input type="email" name="email" value="<?php
echo $email;
?>">

    Password
    <input type="password" name="password_1">

    Confirm password
    <input type="password" name="password_2">

    <button type="submit" class="btn" name="reg_user">Register</button>

      Already a member? Sign in

  </form>

style.css:

    * {
  margin: 0px;
  padding: 0px;
}
body {
  font-size: 120%;
  background: #F8F8FF;
}

.header {
  width: 30%;
  margin: 50px auto 0px;
  color: white;
  background: #5F9EA0;
  text-align: center;
  border: 1px solid #B0C4DE;
  border-bottom: none;
  border-radius: 10px 10px 0px 0px;
  padding: 20px;
}
form, .content {
  width: 30%;
  margin: 0px auto;
  padding: 20px;
  border: 1px solid #B0C4DE;
  background: white;
  border-radius: 0px 0px 10px 10px;
}
.input-group {
  margin: 10px 0px 10px 0px;
}
.input-group label {
  display: block;
  text-align: left;
  margin: 3px;
}
.input-group input {
  height: 30px;
  width: 93%;
  padding: 5px 10px;
  font-size: 16px;
  border-radius: 5px;
  border: 1px solid gray;
}
.btn {
  padding: 10px;
  font-size: 15px;
  color: white;
  background: #5F9EA0;
  border: none;
  border-radius: 5px;
}
.error {
  width: 92%;
  margin: 0px auto;
  padding: 10px;
  border: 1px solid #a94442;
  color: #a94442;
  background: #f2dede;
  border-radius: 5px;
  text-align: left;
}
.success {
  color: #3c763d;
  background: #dff0d8;
  border: 1px solid #3c763d;
  margin-bottom: 20px;
}


问:
Linked List. Confused as to equality issue in code
```<code>var LinkedList = function() {
  var list = {};
  list.head = null;
  list.tail = null;

  list.addToTail = function(value) {
    var node = Node(value);
    if (list.head === null) {
      //have to equal list.tail = list.head because you want them pointing to the same object
      list.tail = list.head = Node(value);
    } else {
      list.tail.next = node;
      list.tail = node;
    }
  };
return list;
};

var Node = function(value) {
  var node = {};

  node.value = value;
  node.next = null;

  return node;
};
</code>```

I have a bit of a simple question. I'm building a linked list and I have a particular issue with the .addToTail property I have built. The current code above works and executes like I want it to. Two part question. If I write my code like this for the if/else statements:

```<code>  if (list.head === null) {
    list.tail = node;
    list.head = node;
  } else {
    list.tail.next = Node(value);
    list.tail = Node(value);
  }
</code>```

My if statement does not work even though I am setting tail and head to the same value separately. It only works if I have them equal to each other in one line like in the original code list.tail = list.head = node. I don't understand what the difference is here. They're the same values so why does writing it separately not work? Also, in my else statement; if I set the values of list.tail.next and list.tail to Node(value). This does not work properly but replacing Node(value) with var node = Node(value) does work like in the original code.

The first block of code gives me my node list correctly:
head: { value: 4, next: { value: 5, next: [Object] } }. The second block of code gives me: head: { value: 4, next: { value: 5, next: null }} It doesn't set the next value property correctly for tail. What the heck is going on here? Am I missing something? These two blocks of codes should be equivalent

答:
when you do

```<code>    list.tail.next = Node(value);
    list.tail = Node(value);
</code>```

you can creating two instances of Node

where

```<code>      list.tail.next = node;
      list.tail = node;
</code>```

only create one

Body:
var LinkedList = function() {
  var list = {};
  list.head = null;
  list.tail = null;

  list.addToTail = function(value) {
    var node = Node(value);
    if (list.head === null) {
      //have to equal list.tail = list.head because you want them pointing to the same object
      list.tail = list.head = Node(value);
    } else {
      list.tail.next = node;
      list.tail = node;
    }
  };
return list;
};

var Node = function(value) {
  var node = {};

  node.value = value;
  node.next = null;

  return node;
};

I have a bit of a simple question. I'm building a linked list and I have a particular issue with the .addToTail property I have built. The current code above works and executes like I want it to. Two part question. If I write my code like this for the if/else statements:

  if (list.head === null) {
    list.tail = node;
    list.head = node;
  } else {
    list.tail.next = Node(value);
    list.tail = Node(value);
  }

My if statement does not work even though I am setting tail and head to the same value separately. It only works if I have them equal to each other in one line like in the original code list.tail = list.head = node. I don't understand what the difference is here. They're the same values so why does writing it separately not work? Also, in my else statement; if I set the values of list.tail.next and list.tail to Node(value). This does not work properly but replacing Node(value) with var node = Node(value) does work like in the original code.

The first block of code gives me my node list correctly:
head: { value: 4, next: { value: 5, next: [Object] } }. The second block of code gives me: head: { value: 4, next: { value: 5, next: null }} It doesn't set the next value property correctly for tail. What the heck is going on here? Am I missing something? These two blocks of codes should be equivalent

Body:
when you do

    list.tail.next = Node(value);
    list.tail = Node(value);

you can creating two instances of Node

where

      list.tail.next = node;
      list.tail = node;

only create one


问:
Marketing Solutions API permissions not getting approved #linkedin
I'm attempting to build a LinkedIn based application using the Marketing Solutions API which will help users use LinkedIn more efficiently.

For that we require these extra permissions:

r_fullprofile

r_member_social

w_compliance

r_compliance

r_primarycontact

r_1st_connections

I'd like to know if there's anything that we need to do in order to be able to get those permissions granted.

My team and I have spent a lot of time and resources in the last few months researching and building the use case to provide value to LinkedIn professionals. It's really unfortunate that we're not able to proceed further. We're in a very difficult position.

答:
submit your question to linkedin support
https://linkedin.zendesk.com/hc/en-us</p>


问:
How to deploy an already built react app with express.js backend to heroku
I have been working on a project for a while now and want to know if anyone has some resources for how to deploy a site that is already built with react and uses an express.js backend to heroku. Every tutorial I have found online is for setting one up for deployment on creating, but since this site has already been created I cant find a way to deploy it now.</p>

答:
You would need to check your package.json to see if it defines the scripts to launch the application. Typically you would need to create a Procfile that looks like this...

```<code>web: npm run start
</code>```

If the package.json defines a script for "start". Otherwise it might look like...

```<code>web: node index.js
</code>```

or

```<code>web: node server
</code>```

Depending how your application starts.

The fact that it's hosting React shouldn't make a difference if the bundle is already built. It's the same process as hosting any other static content.

Body:
You would need to check your package.json to see if it defines the scripts to launch the application. Typically you would need to create a Procfile that looks like this...

web: npm run start

If the package.json defines a script for "start". Otherwise it might look like...

web: node index.js

or

web: node server

Depending how your application starts.

The fact that it's hosting React shouldn't make a difference if the bundle is already built. It's the same process as hosting any other static content.


问:
how to override background image in media query for different screen size?
I have an email template in that I have used a background image. image size and my template size is 600px (width). I have used class call back-img, I want to override this class for all mobile screen size landscape and portrait. specially new iPhones. how do I do this? please help me on this.

media query

```<code><style>

    @media only screen and (min-device-width: 414px)and (max-device-width: 550px) {

    .back-img  {    background: url(https://img.techpowerup.org/200601/cbanners.jpg) repeat-x !important;
    background-size: contain !important;
    background-repeat: no-repeat !important;
    height: 450px !important;
}
    @media only screen and (min-device-width: 375px) and (max-device-width: 413px) {

    .back-img  {    background: url(https://img.techpowerup.org/200601/cbanners.jpg) repeat-x !important;
    background-size: contain !important;
    background-repeat: no-repeat !important;
    height: 375px !important;
}

    @media screen and (min-device-width: 320px) and (max-device-width: 374px) {

    .back-img  {    background: url(https://img.techpowerup.org/200601/cbanners.jpg) repeat-x !important;
    background-size: contain !important;
    background-repeat: no-repeat !important;
    height: 320px !important;
}
</style>
</code>```

HTML file link below

enter link description here

答:
You missed out the closing curly bracket for each media query. Add a closing curly bracket } for each media query and it shall work.

```<code><style>

    @media only screen and (min-device-width: 414px)and (max-device-width: 550px) {

    .back-img  {    background: url(https://img.techpowerup.org/200601/cbanners.jpg) repeat-x !important;
    background-size: contain !important;
    background-repeat: no-repeat !important;
    height: 450px !important;
}}
    @media only screen and (min-device-width: 375px) and (max-device-width: 413px) {

    .back-img  {    background: url(https://img.techpowerup.org/200601/cbanners.jpg) repeat-x !important;
    background-size: contain !important;
    background-repeat: no-repeat !important;
    height: 375px !important;
}}

    @media screen and (min-device-width: 320px) and (max-device-width: 374px) {

    .back-img  {    background: url(https://img.techpowerup.org/200601/cbanners.jpg) repeat-x !important;
    background-size: contain !important;
    background-repeat: no-repeat !important;
    height: 320px !important;
}}
</style>
</code>```

Body:
I have an email template in that I have used a background image. image size and my template size is 600px (width). I have used class call back-img, I want to override this class for all mobile screen size landscape and portrait. specially new iPhones. how do I do this? please help me on this.

media query

HTML file link below

enter link description here

Body:
You missed out the closing curly bracket for each media query. Add a closing curly bracket } for each media query and it shall work.

<style>

    @media only screen and (min-device-width: 414px)and (max-device-width: 550px) {

    .back-img  {    background: url(https://img.techpowerup.org/200601/cbanners.jpg) repeat-x !important;
    background-size: contain !important;
    background-repeat: no-repeat !important;
    height: 450px !important;
}}
    @media only screen and (min-device-width: 375px) and (max-device-width: 413px) {

    .back-img  {    background: url(https://img.techpowerup.org/200601/cbanners.jpg) repeat-x !important;
    background-size: contain !important;
    background-repeat: no-repeat !important;
    height: 375px !important;
}}

    @media screen and (min-device-width: 320px) and (max-device-width: 374px) {

    .back-img  {    background: url(https://img.techpowerup.org/200601/cbanners.jpg) repeat-x !important;
    background-size: contain !important;
    background-repeat: no-repeat !important;
    height: 320px !important;
}}
</style>


问:
Zend two submit buttons same name
I built a form class extending zend_form.I have two submitting buttons :

```<code>$like=new Zend_Form_Element_Image('vote');
$like->setImage($config->path->images."up.png")
->setValue(2);

$dislike=new Zend_Form_Element_Image('vote');
$dislike->setImage($config->path->images."down.png")
->setValue(1);
</code>```

I'd want to have two submit buttons with same name and different value so that I can later access the value of the submitted one  by a switch statement in the controller:

```<code>$submit = $this->_request->getPost('vote');

 switch($submit) {
 case 'one':
 // button one was pressed
 break;
 case 'two':
}

}
</code>```

But If I do set those with the same name the last one is overriding the first so only one button is output.

With file elements theres a method setMultifile() that does the trick.

what should I do here?

thanks

Luca

答:
Why not do something like this:</p>

```<code>if( $this->_request->isPost() && $yourForm->isValid( $this->_request->getPost() ) ) {
    if($yourForm->one->isChecked())
       // button one was pressed
    elseif($yourForm->two->isChecked())
       // button two was pressed
}
</code>```

Title: Zend two submit buttons same name

Body:
I built a form class extending zend_form.I have two submitting buttons :

$like=new Zend_Form_Element_Image('vote');
$like->setImage($config->path->images."up.png")
->setValue(2);

$dislike=new Zend_Form_Element_Image('vote');
$dislike->setImage($config->path->images."down.png")
->setValue(1);

I'd want to have two submit buttons with same name and different value so that I can later access the value of the submitted one  by a switch statement in the controller:

$submit = $this->_request->getPost('vote');

 switch($submit) {
 case 'one':
 // button one was pressed
 break;
 case 'two':
}

}

But If I do set those with the same name the last one is overriding the first so only one button is output.

With file elements theres a method setMultifile() that does the trick.

what should I do here?

thanks

Luca

Body:
Why not do something like this:

if( $this->_request->isPost() && $yourForm->isValid( $this->_request->getPost() ) ) {
    if($yourForm->one->isChecked())
       // button one was pressed
    elseif($yourForm->two->isChecked())
       // button two was pressed
}


问:
Node.js console.log vs console.info
What is the benefit of using console.log vs console.info?
Or any of the other console commands for that matter?

```<code>console.info("info");
console.error("error");
console.warn("warn");
</code>```

vs

```<code>console.log("log");
</code>```

I thought it might change the color of the output or concatenate some sort of label, but they seem to all do the same thing. And according to the documentation here:

https://nodejs.org/api/console.html#console_console_info_data

they seem to all do the same as console.log

答:
It has been established that log and info are basically the same thing, but I'm not sure that completely answers the question:

What is the benefit of using console.log vs console.info?

One benefit, apart from what has already been mentioned, is you can use each for a different purpose. For example, you might use console.log just for quick debugging and spitting things out to the console, while you might use console.info for permanent messages you want to output to the console in your code, such as information on the current app status. Then when you have a situation where a random object is printed in your console and you realize you've left a log statement in there somewhere by accident, you can do a global search for 'console.log' and delete every instance and have confidence you didn't delete anything important that you meant to leave in there.

Title: Node.js console.log vs console.info

Body:
What is the benefit of using console.log vs console.info?
Or any of the other console commands for that matter?

console.info("info");
console.error("error");
console.warn("warn");

vs

console.log("log");

I thought it might change the color of the output or concatenate some sort of label, but they seem to all do the same thing. And according to the documentation here:

https://nodejs.org/api/console.html#console_console_info_data

they seem to all do the same as console.log


问:
Enable viewBinding by default for new projects
To enable viewBinding I add this to gradle:

```<code>viewBinding
{
   enabled = true
}
</code>```

Is there a way to have viewBinding enabled by default whenever I create a new project?

答: As it is for data binding as it is also for view binding. it happen in the grade by enabling it to true. Voilà!</p>

Body:
To enable viewBinding I add this to gradle:

viewBinding
{
   enabled = true
}

Is there a way to have viewBinding enabled by default whenever I create a new project?