问:
changing from old syntax of React Router: rendering white screen
I have been following the Learning React: A Hands-On Guide to Building Web Applications Using React and Redux book but as it is the old book so some of its syntax have been changed. Now, I am at the react router chapter and have to change old syntax to current version. The code examples of the books are as follow

```<code>var App = React.createClass ({
render : function (){
return (
<div>
     <h1> Simple SPA </h1>
     <ul className = "header>
       <li> Home </li>
       <li> Stuff </li>
       <li> Contact </li>
     </ul>
     <div className = "content">
     </div>
</div>

ReactDOM.render(
   <ReactRouter.Router>
     <ReactRouter.Route path ="/" component = {APP}>
     </ReactRouter.Route>
   </ReactRouter.Router>,
   document.getElementById('app'))
</code>```

I have tried to changed to below codes from looking tutorials but it is only rendering white screen. Please have a look at what I have done wrong here

```<code>class App extends React.Component{
  render(){
    return (
      <div>
        <h1> Simple SPA</h1>
        <ul className='header'>
          <li>Home</li>
          <li>Stuff</li>
          <li>Contact</li>
        </ul>
        <div className='content'>

        </div>
      </div>
    )
  }
}
ReactDOM.render(
  <div>
    <Router>
      <Routes>
        <Route path ="/" element={App}></Route>
      </Routes>
    </Router>
  </div>,
  document.getElementById('app')
)
</code>```

答:
Following the syntax from the quickstart example you would need to change you code a little. You need to pass the element into the <Route/>-components as follows:

```<code><Route path="/" element={<App />}>
</code>```

Body:
I have been following the Learning React: A Hands-On Guide to Building Web Applications Using React and Redux book but as it is the old book so some of its syntax have been changed. Now, I am at the react router chapter and have to change old syntax to current version. The code examples of the books are as follow

var App = React.createClass ({
render : function (){
return (

 Simple SPA

 Home

 Stuff

 Contact

ReactDOM.render(
   <ReactRouter.Router>
     <ReactRouter.Route path ="/" component = {APP}>
     </ReactRouter.Route>
   </ReactRouter.Router>,
   document.getElementById('app'))

I have tried to changed to below codes from looking tutorials but it is only rendering white screen. Please have a look at what I have done wrong here

class App extends React.Component{
  render(){
    return (

 Simple SPA

Home

Stuff

Contact

    )
  }
}
ReactDOM.render(

    <Router>
      <Routes>
        <Route path ="/" element={App}></Route>
      </Routes>
    </Router>

,
  document.getElementById('app')
)

Body:
Following the syntax from the quickstart example you would need to change you code a little. You need to pass the element into the <Route/>-components as follows:

<Route path="/" element={<App />}>


来源: stackexchange

问:
How do I update the "board" variable's array's so that the turns of X and O alternate in turns? Btw, this is a Tic Tac Toe Game

let board = [
    ["", "", ""],
    ["", "", ""],
    ["", "", ""]
]

var square1 = document.getElementById("square1")
square1.addEventListener("click", function(turnMove){
    if (turnMove % 2 === 0) {
        square1.innerHTML = "X"
        board[0].splice(0, 0, "X")
    } else {
        square1.innerHTML = "O"
        board[0].splice(0, 0, "O")
    }
    console.log(board)
})

var square2 = document.getElementById("square2")
square2.addEventListener("click", function(turnMove){
    if (turnMove % 2 === 0) {
        square2.innerHTML = "X"
        board[0].splice(1, 1, "X")
    } else {
        square2.innerHTML = "O"
        board[0].splice(1, 1, "O")
    }
    console.log(board)
})

var square3 = document.getElementById("square3")
square3.addEventListener("click", function(turnMove){
    if (turnMove % 2 === 0) {
        square3.innerHTML = "X"
        board[0].splice(2, 2, "X")
    } else {
        square3.innerHTML = "O"
        board[0].splice(2, 2, "O")
    }
    console.log(board)
})

var square4 = document.getElementById("square4")
square4.addEventListener("click", function(turnMove){
    if (turnMove % 2 === 0) {
        square4.innerHTML = "X"
        board[1].splice(0, 0, "X")
    } else {
        square4.innerHTML = "O"
        board[1].splice(0, 0, "O")
    }
    console.log(board)
})

var square5 = document.getElementById("square5")
square5.addEventListener("click", function(turnMove){
    if ((turnMove % 2 === 0)) {
        square5.innerHTML = "X"
        board[1].splice(1, 1, "X")
    } else {
        square5.innerHTML = "O"
        board[1].splice(1, 1, "O")
    }
    console.log(board)
})

var square6 = document.getElementById("square6")
square6.addEventListener("click", function(turnMove){
    if ((turnMove % 2 === 0)) {
        square6.innerHTML = "X"
        board[1].splice(2, 2, "X")
    } else {
        square6.innerHTML = "O"
        board[1].splice(2, 2, "O")
    }
    console.log(board)
})

var square7 = document.getElementById("square7")
square7.addEventListener("click", function(turnMove){
    if ((turnMove % 2 === 0)) {
        square7.innerHTML = "X"
        board[2].splice(0, 0, "X")
    } else {
        square7.innerHTML = "O"
        board[2].splice(0, 0, "O")
    }
    console.log(board)
})

var square8 = document.getElementById("square8")
square8.addEventListener("click", function(turnMove){
    if ((turnMove % 2 === 0)) {
        square8.innerHTML = "X"
        board[2].splice(1, 1, "X")
    } else {
        square8.innerHTML = "O"
        board[2].splice(1, 1, "O")
    }
    console.log(board)
})

var square9 = document.getElementById("square9")
square9.addEventListener("click", function(turnMove){
    if ((turnMove % 2 === 0)) {
        square9.innerHTML = "X"
        board[2].splice(2, 2, "X")
    } else {
        square9.innerHTML = "O"
        board[2].splice(2, 2, "O")
    }
    console.log(board)
})

function turnMove(board) {
    turns = 0
    for (let i = 0; i < board.length; i++) {
        for (let j = 0; j < board[i].length; j++) {
            if (board[i][j]) {
                turns = turns + 1
            } else {
                turns = turns + 0
            }
        }
    }
    return turns
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#board {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    grid-template-rows: 1fr 1fr  1fr;
    max-width: 40%;
    height: 40vw;
    margin: auto;
    border: 2px solid black;
    text-align: center;

}

.square {
    background-color: aliceblue;
    border: 1px solid black;

}

* {
    font-size: 2.5rem;
}</code>```

        <title>Tic Tac Toe Game</title>
        <link rel="stylesheet" href="style.css">
        <meta name="viewport" content="width-device-width initial-scale=1">

```
</div>
</div>
</p>
<p>The function turnMove is determining what move it is in and using this allows the addEventListener to determine if the innerHTML and splice will add "X" or "O" to the div and board arrays.</p>
<p>How can I alternate the "X"s and "O"s? I need to update the board "state." How do I do that?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let board = [
    ["", "", ""],
    ["", "", ""],
    ["", "", ""]
]

var square1 = document.getElementById("square1")
square1.addEventListener("click", function(turnMove){
    if (turnMove % 2 === 0) {
        square1.innerHTML = "X"
        board[0].splice(0, 0, "X")
    } else {
        square1.innerHTML = "O"
        board[0].splice(0, 0, "O")
    }
    console.log(board)
})

// This code is applicable for the 9 squares.
// square2, square2, and so on...

function turnMove(board) {
    turns = 0
    for (let i = 0; i < board.length; i++) {
        for (let j = 0; j < board[i].length; j++) {
            if (board[i][j]) {
                turns = turns + 1
            } else {
                turns = turns + 0
            }
        }
    }
    return turns
}</code>```

答:
Posting this here as a end result, this is not a solution to your problem.

@phucbm on the other hand explained what's wrong with your code, that's your solution, this is just a guide for your end result

Use this as a guide, use @phucbm's answer to fix your problem

-

const emptyBoard = [
    ["-", "-", "-"],
    ["-", "-", "-"],
    ["-", "-", "-"]
];
// Break reference by stringify/parsing
let board = JSON.parse(JSON.stringify(emptyBoard));
const boardEl = document.querySelector('#board');

const createBoard = () => {
  boardEl.innerHTML = ''; // Reset board on win
  board.map((row, rowIndex) => {
      let rowHTML = ``;
      row.map((col, colIndex) => {
          rowHTML += `<div class="cell" data-row="${rowIndex}" data-col="${colIndex}"></div>`;
      });
      boardEl.innerHTML += `<div class="row">${ rowHTML }</div>`;
  });
}

createBoard(); // Init

const checkForWins = (row, col) => {
    // Check either diagonal or current row / col clicked
    const diagonalLeft = [ board[0][0], board[1][1], board[2][2] ];
    const diagonalRight = [ board[0][2], board[1][1], board[2][0] ];
    const currentRow = [board[row][0], board[row][1], board[row][2]];
    const currentCol = [board[0][col], board[1][col], board[2][col]];

    [ diagonalLeft, diagonalRight, currentRow, currentCol ].map((arr) => {
        const string = arr.join('');

        if (string === 'xxx' || string === 'ooo') {
            alert(string[0]+' wins!');
            board = JSON.parse(JSON.stringify(emptyBoard));
            createBoard();
        }
    })
};

let currentPlayer = "x";
boardEl.addEventListener('click', (evt) => {
    const row = evt.target.getAttribute('data-row');
    const col = evt.target.getAttribute('data-col');
    const isEmpty = evt.target.innerText === '';

    if (row && col && isEmpty) {
        board[ row ][ col ] = currentPlayer;
        evt.target.innerHTML = board[row][col];
        checkForWins(row, col);
        currentPlayer = currentPlayer === 'x' ? 'o' : 'x';
    }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#board {
    display: block;
}
#board .row { display: block; font-size: 0; }
#board .row .cell {
    display: inline-block;
    width: 30px;
    height: 30px;
    border: 1px solid #000;
    text-align: center;
    line-height: 30px;
    font-size: 15px;
    vertical-align: top;
}</code>```

```

ContentLicense: CC BY-SA 4.0

Body:
let board = [
    ["", "", ""],
    ["", "", ""],
    ["", "", ""]
]

var square1 = document.getElementById("square1")
square1.addEventListener("click", function(turnMove){
    if (turnMove % 2 === 0) {
        square1.innerHTML = "X"
        board[0].splice(0, 0, "X")
    } else {
        square1.innerHTML = "O"
        board[0].splice(0, 0, "O")
    }
    console.log(board)
})

var square2 = document.getElementById("square2")
square2.addEventListener("click", function(turnMove){
    if (turnMove % 2 === 0) {
        square2.innerHTML = "X"
        board[0].splice(1, 1, "X")
    } else {
        square2.innerHTML = "O"
        board[0].splice(1, 1, "O")
    }
    console.log(board)
})

var square3 = document.getElementById("square3")
square3.addEventListener("click", function(turnMove){
    if (turnMove % 2 === 0) {
        square3.innerHTML = "X"
        board[0].splice(2, 2, "X")
    } else {
        square3.innerHTML = "O"
        board[0].splice(2, 2, "O")
    }
    console.log(board)
})

var square4 = document.getElementById("square4")
square4.addEventListener("click", function(turnMove){
    if (turnMove % 2 === 0) {
        square4.innerHTML = "X"
        board[1].splice(0, 0, "X")
    } else {
        square4.innerHTML = "O"
        board[1].splice(0, 0, "O")
    }
    console.log(board)
})

var square5 = document.getElementById("square5")
square5.addEventListener("click", function(turnMove){
    if ((turnMove % 2 === 0)) {
        square5.innerHTML = "X"
        board[1].splice(1, 1, "X")
    } else {
        square5.innerHTML = "O"
        board[1].splice(1, 1, "O")
    }
    console.log(board)
})

var square6 = document.getElementById("square6")
square6.addEventListener("click", function(turnMove){
    if ((turnMove % 2 === 0)) {
        square6.innerHTML = "X"
        board[1].splice(2, 2, "X")
    } else {
        square6.innerHTML = "O"
        board[1].splice(2, 2, "O")
    }
    console.log(board)
})

var square7 = document.getElementById("square7")
square7.addEventListener("click", function(turnMove){
    if ((turnMove % 2 === 0)) {
        square7.innerHTML = "X"
        board[2].splice(0, 0, "X")
    } else {
        square7.innerHTML = "O"
        board[2].splice(0, 0, "O")
    }
    console.log(board)
})

var square8 = document.getElementById("square8")
square8.addEventListener("click", function(turnMove){
    if ((turnMove % 2 === 0)) {
        square8.innerHTML = "X"
        board[2].splice(1, 1, "X")
    } else {
        square8.innerHTML = "O"
        board[2].splice(1, 1, "O")
    }
    console.log(board)
})

var square9 = document.getElementById("square9")
square9.addEventListener("click", function(turnMove){
    if ((turnMove % 2 === 0)) {
        square9.innerHTML = "X"
        board[2].splice(2, 2, "X")
    } else {
        square9.innerHTML = "O"
        board[2].splice(2, 2, "O")
    }
    console.log(board)
})

function turnMove(board) {
    turns = 0
    for (let i = 0; i < board.length; i++) {
        for (let j = 0; j < board[i].length; j++) {
            if (board[i][j]) {
                turns = turns + 1
            } else {
                turns = turns + 0
            }
        }
    }
    return turns
}

#board {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    grid-template-rows: 1fr 1fr  1fr;
    max-width: 40%;
    height: 40vw;
    margin: auto;
    border: 2px solid black;
    text-align: center;

}

.square {
    background-color: aliceblue;
    border: 1px solid black;

}

* {
    font-size: 2.5rem;
}

        <title>Tic Tac Toe Game</title>
        <link rel="stylesheet" href="style.css">
        <meta name="viewport" content="width-device-width initial-scale=1">

The function turnMove is determining what move it is in and using this allows the addEventListener to determine if the innerHTML and splice will add "X" or "O" to the div and board arrays.

How can I alternate the "X"s and "O"s? I need to update the board "state." How do I do that?

let board = [
    ["", "", ""],
    ["", "", ""],
    ["", "", ""]
]

var square1 = document.getElementById("square1")
square1.addEventListener("click", function(turnMove){
    if (turnMove % 2 === 0) {
        square1.innerHTML = "X"
        board[0].splice(0, 0, "X")
    } else {
        square1.innerHTML = "O"
        board[0].splice(0, 0, "O")
    }
    console.log(board)
})

// This code is applicable for the 9 squares.
// square2, square2, and so on...

function turnMove(board) {
    turns = 0
    for (let i = 0; i < board.length; i++) {
        for (let j = 0; j < board[i].length; j++) {
            if (board[i][j]) {
                turns = turns + 1
            } else {
                turns = turns + 0
            }
        }
    }
    return turns
}

Body:
Posting this here as a end result, this is not a solution to your problem.

@phucbm on the other hand explained what's wrong with your code, that's your solution, this is just a guide for your end result

Use this as a guide, use @phucbm's answer to fix your problem

-

const emptyBoard = [
    ["-", "-", "-"],
    ["-", "-", "-"],
    ["-", "-", "-"]
];
// Break reference by stringify/parsing
let board = JSON.parse(JSON.stringify(emptyBoard));
const boardEl = document.querySelector('#board');

const createBoard = () => {
  boardEl.innerHTML = ''; // Reset board on win
  board.map((row, rowIndex) => {
      let rowHTML = ``;
      row.map((col, colIndex) => {
          rowHTML += `<div class="cell" data-row="${rowIndex}" data-col="${colIndex}"></div>`;
      });
      boardEl.innerHTML += `<div class="row">${ rowHTML }</div>`;
  });
}

createBoard(); // Init

const checkForWins = (row, col) => {
    // Check either diagonal or current row / col clicked
    const diagonalLeft = [ board[0][0], board[1][1], board[2][2] ];
    const diagonalRight = [ board[0][2], board[1][1], board[2][0] ];
    const currentRow = [board[row][0], board[row][1], board[row][2]];
    const currentCol = [board[0][col], board[1][col], board[2][col]];

    [ diagonalLeft, diagonalRight, currentRow, currentCol ].map((arr) => {
        const string = arr.join('');

        if (string === 'xxx' || string === 'ooo') {
            alert(string[0]+' wins!');
            board = JSON.parse(JSON.stringify(emptyBoard));
            createBoard();
        }
    })
};

let currentPlayer = "x";
boardEl.addEventListener('click', (evt) => {
    const row = evt.target.getAttribute('data-row');
    const col = evt.target.getAttribute('data-col');
    const isEmpty = evt.target.innerText === '';

    if (row && col && isEmpty) {
        board[ row ][ col ] = currentPlayer;
        evt.target.innerHTML = board[row][col];
        checkForWins(row, col);
        currentPlayer = currentPlayer === 'x' ? 'o' : 'x';
    }
})

#board {
    display: block;
}
#board .row { display: block; font-size: 0; }
#board .row .cell {
    display: inline-block;
    width: 30px;
    height: 30px;
    border: 1px solid #000;
    text-align: center;
    line-height: 30px;
    font-size: 15px;
    vertical-align: top;
}

<div id="board"></div>


问:
Circular dependency best practice
What is the best way to solve this.

I have projects the following projects:

Model

Logic (references model)

Synchronization (references both model and logic)

Web (references all projects)

All runs fine, the web project fires the synchronization project, which uses model and logic, and does it's work.
But now, some times, the logic project also has to call a method in the synchronization project, but this reference cannot be added because of the circular dependency that is not allowed.

What would be the easiest way to make this whole thing work?

A bit more on the synchronization project.
Synchronization works on it's own. It runs processes that bring data from an external database to the database in my application. It does this by creating objects based on the model and saves them by using the logic.
This works fine, and gives us the ability to simply create another synchronization project/assembly that could do the same thing, but targeted at a completely different type of database.

The problem is, that we now, from time to time, want to call a method in the sychronization project to update some data in the other direction / to the external database.

答: Sounds like it's time to refactor. The easiest is to break the pieces neded in both Synchronization and Logic out into a fifth project and reference that in both. However, like most easy things, this can also be a sign that you need to rethink how you've allocated your code in the first place. It may be that the code needed by Logic in Synchronization belongs in Logic in the first place.</p>

ContentLicense: CC BY-SA 3.0

Title: Circular dependency best practice


问:
Unity 3D - Move Humanoid head muscles using script

Goal

I would like to rotate a head of a humanoid character given x, y, z rotation values using a script (without using any other object in the scene as "look" direction).

What I want to do

When setting-up the rigging of a Humanoid character (humanoid prefab --> Rig --> Animation Type: Humanoid --> Configure --> Muscles & Settings), you see the following interface: https://docs.unity3d.com/Manual/MuscleDefinitions.html

In this menu, under Head, you can drag a slider to move e.g. your humanoid head up and down. I want to achieve the same with a script, but I don't know how to do this.

Resources

This question never received a proper answer with example code: https://answers.unity.com/questions/824628/can-we-using-script-to-moving-the-muscles-in-unity.html

I presume I have to do something with HumanPose.muscles (https://docs.unity3d.com/ScriptReference/HumanPose-muscles.html), however with the lack of code samples, I have no idea how to approach this.

Edit 3: This link has a code sample for HumanPose, but I didn't get it to work yet: https://forum.unity.com/threads/humanposehandler.430354/

Question

How to get the head muscles of a humanoid character and rotate them by giving values through a script? (Or any other way how to rotate the head using head rotation values, without another object in the scene). Any help would be appreciated.

Edit 1 & 2: Sample code

I receive a JSON formatted message from which I extract the radian values and change it into degrees:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Newtonsoft.Json.Linq;  // JSON reader; https://assetstore.unity.com/packages/tools/input-management/json-net-for-unity-11347

public class HeadRotator : MonoBehaviour {

    Quaternion rotation = Quaternion.identity;

    // Radians to degree
    float Rad2Degree = 180 / Mathf.PI;

    // Human muscle stuff
    HumanPoseHandler humanPoseHandler;
    HumanPose humanPose;
    Animator anim;
    //Transform head;

    // Use this for initialization
    void Start () {
        // get attached Animator controller
        anim = GetComponent<Animator>();

        //head = anim.GetBoneTransform(HumanBodyBones.Head);
        //Debug.Log (head);
    }

    // Use JSON message to set head rotation and facial expressions;
    // IEnumerator to run in main thread (needed for SetBlendShapeWeight)
    public IEnumerator RequestHeadRotation(JObject head_pose)
    {
        // rotate head of character with received x, y, z rotations in radian
        List<float> head_rotation = new List<float> ();
        foreach (KeyValuePair<string, JToken> pair in head_pose) {
            //Debug.Log(pair);
            // store head rotation in degrees
            head_rotation.Add(float.Parse(pair.Value.ToString())*Rad2Degree*10);
        }

        Debug.Log ("" + head_rotation[0] + ", " + head_rotation[1] + ", " + head_rotation[2]);
        //Quaternion rotation = Quaternion.Euler(new Vector3(head_rotation[0], head_rotation[1], head_rotation[2]));
        //Debug.Log ("" + rotation[0] + ", " + rotation[1] + ", " + rotation[2] + ", " + rotation[3]);
        // head.Rotate (rotation);

        // https://docs.unity3d.com/ScriptReference/Quaternion-eulerAngles.html
        rotation.eulerAngles = new Vector3 (head_rotation[0], head_rotation[1], head_rotation[2]);

        // Animator.GetBoneTransform()
        anim.SetBoneLocalRotation(HumanBodyBones.Head, rotation);

        yield return null;
    }
}
```

Head rotation data: 3.208564, 0.4583662, 0.1145916

Quaternion data: 0.0280001, 0.003970424, 0.0008876149, 0.9995997

I don't really know well how to set either the head bone or the muscles. Most examples provide only a snippet of the code, so I'm struggling in figuring out how it works.

Edit 2: I feel I'm getting close, but anim.SetBoneLocalRotation(HumanBodyBones.Head, rotation); seems to get ignored.

Edit 4: I put on Github a simple version of my head rotation attempt: https://github.com/NumesSanguis/Basic-Unity-Head-Rotation

答:
Two addition to the muscle answer

1, To solve the problem:

The character to which it was applied moved quite far from where he was supposed to be when humanPoseHandler.SetHumanPose(ref humanPose); was set.

You need to add:

```<code>humanPose.bodyPosition = transform.position;
humanPose.bodyRotation = transform.rotation;
</code>```

That will keep your character exactly where it is located.

2, Actually the muscle solution is still valid when an AnimatorController is attached to current humanoid character. You just need to switch Update Mode to Animate Physics and put your muscle code in Update(). That will make your muscle code (which executes in Update()) executes after the AnimationController effects (which executes in FixedUpdate(), which is called earlier than the Update()).

This approach will allow you directly control some muscle, and use Unity IK effect at the same time.

Body:
Goal

I would like to rotate a head of a humanoid character given x, y, z rotation values using a script (without using any other object in the scene as "look" direction).

What I want to do

When setting-up the rigging of a Humanoid character (humanoid prefab --> Rig --> Animation Type: Humanoid --> Configure --> Muscles & Settings), you see the following interface: https://docs.unity3d.com/Manual/MuscleDefinitions.html

In this menu, under Head, you can drag a slider to move e.g. your humanoid head up and down. I want to achieve the same with a script, but I don't know how to do this.

Resources

This question never received a proper answer with example code: https://answers.unity.com/questions/824628/can-we-using-script-to-moving-the-muscles-in-unity.html

I presume I have to do something with HumanPose.muscles (https://docs.unity3d.com/ScriptReference/HumanPose-muscles.html), however with the lack of code samples, I have no idea how to approach this.

Edit 3: This link has a code sample for HumanPose, but I didn't get it to work yet: https://forum.unity.com/threads/humanposehandler.430354/

Question

How to get the head muscles of a humanoid character and rotate them by giving values through a script? (Or any other way how to rotate the head using head rotation values, without another object in the scene). Any help would be appreciated.

Edit 1 & 2: Sample code

I receive a JSON formatted message from which I extract the radian values and change it into degrees:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Newtonsoft.Json.Linq;  // JSON reader; https://assetstore.unity.com/packages/tools/input-management/json-net-for-unity-11347

public class HeadRotator : MonoBehaviour {

    Quaternion rotation = Quaternion.identity;

    // Radians to degree
    float Rad2Degree = 180 / Mathf.PI;

    // Human muscle stuff
    HumanPoseHandler humanPoseHandler;
    HumanPose humanPose;
    Animator anim;
    //Transform head;

    // Use this for initialization
    void Start () {
        // get attached Animator controller
        anim = GetComponent<Animator>();

        //head = anim.GetBoneTransform(HumanBodyBones.Head);
        //Debug.Log (head);
    }

    // Use JSON message to set head rotation and facial expressions;
    // IEnumerator to run in main thread (needed for SetBlendShapeWeight)
    public IEnumerator RequestHeadRotation(JObject head_pose)
    {
        // rotate head of character with received x, y, z rotations in radian
        List<float> head_rotation = new List<float> ();
        foreach (KeyValuePair<string, JToken> pair in head_pose) {
            //Debug.Log(pair);
            // store head rotation in degrees
            head_rotation.Add(float.Parse(pair.Value.ToString())*Rad2Degree*10);
        }

        Debug.Log ("" + head_rotation[0] + ", " + head_rotation[1] + ", " + head_rotation[2]);
        //Quaternion rotation = Quaternion.Euler(new Vector3(head_rotation[0], head_rotation[1], head_rotation[2]));
        //Debug.Log ("" + rotation[0] + ", " + rotation[1] + ", " + rotation[2] + ", " + rotation[3]);
        // head.Rotate (rotation);

        // https://docs.unity3d.com/ScriptReference/Quaternion-eulerAngles.html
        rotation.eulerAngles = new Vector3 (head_rotation[0], head_rotation[1], head_rotation[2]);

        // Animator.GetBoneTransform()
        anim.SetBoneLocalRotation(HumanBodyBones.Head, rotation);

        yield return null;
    }
}

Head rotation data: 3.208564, 0.4583662, 0.1145916

Quaternion data: 0.0280001, 0.003970424, 0.0008876149, 0.9995997

I don't really know well how to set either the head bone or the muscles. Most examples provide only a snippet of the code, so I'm struggling in figuring out how it works.

Edit 2: I feel I'm getting close, but anim.SetBoneLocalRotation(HumanBodyBones.Head, rotation); seems to get ignored.

Edit 4: I put on Github a simple version of my head rotation attempt: https://github.com/NumesSanguis/Basic-Unity-Head-Rotation

Body:
Two addition to the muscle answer

1, To solve the problem:

The character to which it was applied moved quite far from where he was supposed to be when humanPoseHandler.SetHumanPose(ref humanPose); was set.

You need to add:

humanPose.bodyPosition = transform.position;
humanPose.bodyRotation = transform.rotation;

That will keep your character exactly where it is located.

2, Actually the muscle solution is still valid when an AnimatorController is attached to current humanoid character. You just need to switch Update Mode to Animate Physics and put your muscle code in Update(). That will make your muscle code (which executes in Update()) executes after the AnimationController effects (which executes in FixedUpdate(), which is called earlier than the Update()).

This approach will allow you directly control some muscle, and use Unity IK effect at the same time.


问:
How to add '-whole-archive' in gn
I am using gn as my build system, and I want to some target deps another with " -whole-archive", but I found seem no way to do that?

What I need is something like:

```<code>clang++ -o libmy.so -Wl,--start-group libA.a libB.a -Wl,-whole-archive libC.a -Wl,-no-whole-archive -Wl,--end-group
</code>```

libA.a and libB.a in --start-group and --end-group

libC.a in -whole-archive and -no-whole-archive

Thanks

答:
GN doesn't appear to support this use case. However, try building libC as a source_set instead of a static_library.

https://gn.googlesource.com/gn/+/master/docs/reference.md#func_source_set

```<code>A source set is a collection of sources that get compiled, but are not
linked to produce any kind of library. Instead, the resulting object files
are implicitly added to the linker line of all targets that depend on the
source set.
</code>```

Putting every object file from libC directly on the link line has the same effect as using -Wl,--whole-archive.

Title: How to add '-whole-archive' in gn

Body:
I am using gn as my build system, and I want to some target deps another with " -whole-archive", but I found seem no way to do that?

What I need is something like:

clang++ -o libmy.so -Wl,--start-group libA.a libB.a -Wl,-whole-archive libC.a -Wl,-no-whole-archive -Wl,--end-group

libA.a and libB.a in --start-group and --end-group

libC.a in -whole-archive and -no-whole-archive

Thanks

Body:
GN doesn't appear to support this use case. However, try building libC as a source_set instead of a static_library.

https://gn.googlesource.com/gn/+/master/docs/reference.md#func_source_set

A source set is a collection of sources that get compiled, but are not
linked to produce any kind of library. Instead, the resulting object files
are implicitly added to the linker line of all targets that depend on the
source set.

Putting every object file from libC directly on the link line has the same effect as using -Wl,--whole-archive.


问:
refresh form with change in select option
So I want to refresh the update form with the change in the select option (which will be year).

This is my form:

```<code>         <select class="form-control" id="year_select" name="year_select">
            @foreach($pickyear as $key=>$unique)
                <option value= "{!! $unique !!}"> {!! $unique !!} </option>
            @endforeach
        </select>

    {!! Form::open(['url' => 'form', 'class' => 'form-horizontal']) !!}
        //form is included here
    {!! Form::close() !!}
</code>```

So I want to reload or refresh the form with every change in select value or ajax call.

Ajax call:

```<code> $('select[name="year_select" ]).change(function(e) {
        // e.preventDefault();
        const year = $(this).val();
        window.location.reload();
        const url = `/form/${year}`;

        $.ajax({
            url,
            type: 'PUT',
            success: function(res) {
                window.location.reload();
            }
        });
    })
</code>```

Edit: Refreshing / reloading whole page would do too.

Update:  The imput parameter should be updatable and should change value according to the year from select option.

答:
Use onchange="this.form.submit()" for page reload when Select Option change

on blade

<select name="year_select" onchange="this.form.submit()">
    @foreach($pickyear as $key=>$unique)
        <option value= "{!! $unique !!}"> {!! $unique !!} </option>
    @endforeach
</select>
```
<p>now url should be <code>form_url?year_select=2022</code> and you can filter data from controller</p>
<p>On controller</p>
<pre class="lang-php prettyprint-override"><code>$model = Model::query();

if (request('year_select')) {
    $model->whereYear('your_year_column', request('year_select'));
}
// else
// {
//     // if you need current year as default
//     $model->whereYear('your_year_column', date('Y'));
// }

$data = $model->get();
</code>```

Body:
So I want to refresh the update form with the change in the select option (which will be year).

This is my form:

         <select class="form-control" id="year_select" name="year_select">
            @foreach($pickyear as $key=>$unique)
                <option value= "{!! $unique !!}"> {!! $unique !!} </option>
            @endforeach
        </select>

    {!! Form::open(['url' => 'form', 'class' => 'form-horizontal']) !!}
        //form is included here
    {!! Form::close() !!}

So I want to reload or refresh the form with every change in select value or ajax call.

Ajax call:

 $('select[name="year_select" ]).change(function(e) {
        // e.preventDefault();
        const year = $(this).val();
        window.location.reload();
        const url = `/form/${year}`;

        $.ajax({
            url,
            type: 'PUT',
            success: function(res) {
                window.location.reload();
            }
        });
    })

Edit: Refreshing / reloading whole page would do too.

Update:  The imput parameter should be updatable and should change value according to the year from select option.

Body:
Use onchange="this.form.submit()" for page reload when Select Option change

on blade

<select name="year_select" onchange="this.form.submit()">
    @foreach($pickyear as $key=>$unique)
        <option value= "{!! $unique !!}"> {!! $unique !!} </option>
    @endforeach
</select>

now url should be form_url?year_select=2022 and you can filter data from controller

On controller

$model = Model::query();

if (request('year_select')) {
    $model->whereYear('your_year_column', request('year_select'));
}
// else
// {
//     // if you need current year as default
//     $model->whereYear('your_year_column', date('Y'));
// }

$data = $model->get();


问:
How to retrieve data from firebase to Google chart?
Sorry but it's my first project with Firebase. I try this solution in my project but to no avail (from antoher post on Stack overflow). Data for this database are from ESP8266. My Firebase looks like this:

```<code>"MOIST" : {
    "-MvDCD_qVJUZtZ9Pe98p" : {
      "data" : "2022-2-6",
      "time" : "09:44:40",
      "value" : 5
    },
    "-MvDCE56y_4aXngGtQJx" : {
      "data" : "2022-2-6",
      "time" : "09:44:42",
      "value" : 5
    },
</code>```

This is the code I am using:

```<code> <html>
 <head>

    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script src="https://www.gstatic.com/firebasejs/3.7.8/firebase.js"></script>
    <script src=" http://www.google.com/uds/modules/gviz/gviz-api.js"></script>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

    <script src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
        // Initialize Firebase
        var config = {
            apiKey: "AIzaSyD0y-idPsXKkqOI8333yQE9NTTvF5cDh0M",
            authDomain: "podlewanie-2.firebaseapp.com",
            databaseURL: "https://podlewanie-2-default-rtdb.europe-west1.firebasedatabase.app",
            projectId: "podlewanie-2",
            storageBucket: "podlewanie-2.appspot.com",
            messagingSenderId: "266746962201",
            appId: "1:266746962201:web:1a4c60a5824162c560a588",
            measurementId: "G-7QW1Z2DD7W"
        };
        firebase.initializeApp(config);

        var database = firebase.database();

        firebase.database().ref('/MOIST').once('value').then(function(snapshot) {
            temps = snapshot.val();
            console.log(temps);

            google.charts.load('current', {
                'packages': ['corechart', 'line']
            });
            google.charts.setOnLoadCallback(drawChart(temps));
        });

        function parse(temp) {
            return (new Date(temp.replace(/-/g, '/'))).getTime()
        }

        function drawChart(temps) {
            var array = $.map(temps, function(value, index) {
                return [value];
            });

            var data = new google.visualization.DataTable();
            data.addColumn('number', 'date');
            data.addColumn('number', 'time');
            data.addColumn('number', 'value');

            var sort = function(a, b) {
                return parse(a.time) - parse(b.time)
            };
            var tempData = array.sort(sort);
            var output = [];

            for (var i = 0; i < tempData.length; i++) {
                var item = tempData[i];
                output.push([
                    //  parseFloat(parse(item.time)),
                    parseFloat(item.time),
                    parseFloat(item.date),
                    parseFloat(item.value)
                ]);
            }
            console.log(output);
            data.addRows(output);

            var options = {
                chart: {
                    title: 'title',
                    subtitle: 'subtitle'
                },
                width: 900,
                height: 500
            };

            var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
            console.log("data + options: " + data, options)
            chart.draw(data, options);
        }

        google.charts.load('current', {
            'packages': ['corechart', 'line']
        });
        google.charts.setOnLoadCallback(drawChart);
    </script>
</head>
      <body>
        <div id="curve_chart" style="width: 900px; height: 500px"></div>
      </body>
</html>
</code>```

After run this code i see only white page. I will be grateful for your help.

答:
When you see a white screen, check your browser's console (Ctrl+Shift+J/⌘+⌥+J in most browsers, or F12 in LegacyEdge/IE) for errors. In this case, you get this error:

Uncaught Error: FIREBASE FATAL ERROR: Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com

This indicates that the version of the Firebase SDK you are using doesn't understand the value you gave for databaseURL in your configuration:

var config = {
  /* ... */
  databaseURL: "https://podlewanie-2-default-rtdb.europe-west1.firebasedatabase.app"
  /* ... */
}
```
<p>Because this was probably copied straight from the Firebase Console, ask yourself <em>why</em> doesn't the SDK understand this URL? The answer to that is because you are using Firebase SDK v3.7.8 (from April 2017).</p>
<pre class="lang-html prettyprint-override"><code><script src="https://www.gstatic.com/firebasejs/3.7.8/firebase.js"></script>
</code>```

You should be using the latest version to make sure you are up-to-date on any security fixes, corrected flaws, updated server APIs or new product updates.

The latest legacy SDK (as of the time of writing) is 8.10.1 (January 2022):

```
<p>However, for all new projects you should use the new modular SDK by following the upgrade guide. The latest version for that SDK is 9.6.6 (February 2022).</p>
<h2>Other issues</h2>
<p>Aside from that, you also need to correct this line, that should be setting a callback function:</p>
```google.charts.setOnLoadCallback(drawChart(temps));
```
<p>to the following:</p>
```google.charts.setOnLoadCallback(() => drawChart(temps));
```
<p>Additionally, in that <code>drawChart</code> function, you are also targetting an element with the ID <code>chart_div</code> instead of the correct <code>curve_chart</code> on this line:</p>
<pre class="lang-js prettyprint-override"><code>var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
</code>```

That line should be:

var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
```

Body:
Sorry but it's my first project with Firebase. I try this solution in my project but to no avail (from antoher post on Stack overflow). Data for this database are from ESP8266. My Firebase looks like this:

"MOIST" : {
    "-MvDCD_qVJUZtZ9Pe98p" : {
      "data" : "2022-2-6",
      "time" : "09:44:40",
      "value" : 5
    },
    "-MvDCE56y_4aXngGtQJx" : {
      "data" : "2022-2-6",
      "time" : "09:44:42",
      "value" : 5
    },

This is the code I am using:

After run this code i see only white page. I will be grateful for your help.

Body:
When you see a white screen, check your browser's console (Ctrl+Shift+J/⌘+⌥+J in most browsers, or F12 in LegacyEdge/IE) for errors. In this case, you get this error:

Uncaught Error: FIREBASE FATAL ERROR: Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com

This indicates that the version of the Firebase SDK you are using doesn't understand the value you gave for databaseURL in your configuration:

var config = {
  /* ... */
  databaseURL: "https://podlewanie-2-default-rtdb.europe-west1.firebasedatabase.app"
  /* ... */
}

Because this was probably copied straight from the Firebase Console, ask yourself why doesn't the SDK understand this URL? The answer to that is because you are using Firebase SDK v3.7.8 (from April 2017).

<script src="https://www.gstatic.com/firebasejs/3.7.8/firebase.js"></script>

You should be using the latest version to make sure you are up-to-date on any security fixes, corrected flaws, updated server APIs or new product updates.

The latest legacy SDK (as of the time of writing) is 8.10.1 (January 2022):

<script src="https://www.gstatic.com/firebasejs/8.10.1/firebase.js"></script>

However, for all new projects you should use the new modular SDK by following the upgrade guide. The latest version for that SDK is 9.6.6 (February 2022).

Other issues

Aside from that, you also need to correct this line, that should be setting a callback function:

google.charts.setOnLoadCallback(drawChart(temps));

to the following:

google.charts.setOnLoadCallback(() => drawChart(temps));

Additionally, in that drawChart function, you are also targetting an element with the ID chart_div instead of the correct curve_chart on this line:

var chart = new google.visualization.LineChart(document.getElementById('chart_div'));

That line should be:

var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));


答:
Either:

Something wrong and you have to refactor wrong dependencies/references

The time to introduce new project called smth like Common (assuming you already have 4 pretty high level projects I would bet for #1 - try to figure out why Synchronizaiton references logic and logic references synchronization in the same time)

Title: Circular dependency best practice

Body:
What is the best way to solve this.

I have projects the following projects:

Model

Logic (references model)

Synchronization (references both model and logic)

Web (references all projects)

All runs fine, the web project fires the synchronization project, which uses model and logic, and does it's work.
But now, some times, the logic project also has to call a method in the synchronization project, but this reference cannot be added because of the circular dependency that is not allowed.

What would be the easiest way to make this whole thing work?

A bit more on the synchronization project.
Synchronization works on it's own. It runs processes that bring data from an external database to the database in my application. It does this by creating objects based on the model and saves them by using the logic.
This works fine, and gives us the ability to simply create another synchronization project/assembly that could do the same thing, but targeted at a completely different type of database.

The problem is, that we now, from time to time, want to call a method in the sychronization project to update some data in the other direction / to the external database.


问:
Why is Thread.Sleep so harmful
I often see it mentioned that Thread.Sleep(); should not be used, but I can't understand why this is so. If Thread.Sleep(); can cause trouble, are there any alternative solutions with the same result that would be safe?

eg.

```<code>while(true)
{
    doSomework();
    i++;
    Thread.Sleep(5000);
}
</code>```

another one is:

```<code>while (true)
{
    string[] images = Directory.GetFiles(@"C:\Dir", "*.png");

    foreach (string image in images)
    {
        this.Invoke(() => this.Enabled = true);
        pictureBox1.Image = new Bitmap(image);
        Thread.Sleep(1000);
    }
}
</code>```

答: I think using timers is a good alternative. If you want a certain action to be performed once every x milliseconds if you you use Thread.sleep(x) your action will be performed every x+y seconds, where y is the time needed for your action to be performed.</p>

Title: Why is Thread.Sleep so harmful

Body:
I often see it mentioned that Thread.Sleep(); should not be used, but I can't understand why this is so. If Thread.Sleep(); can cause trouble, are there any alternative solutions with the same result that would be safe?

eg.

while(true)
{
    doSomework();
    i++;
    Thread.Sleep(5000);
}

another one is:

while (true)
{
    string[] images = Directory.GetFiles(@"C:\Dir", "*.png");

    foreach (string image in images)
    {
        this.Invoke(() => this.Enabled = true);
        pictureBox1.Image = new Bitmap(image);
        Thread.Sleep(1000);
    }
}


问:
Jump functionality for a 2D Top Down Unity game?
I am struggling to find an efficient way to let my player jump in a 2D Top Down world. I can see a lot of tutorials about platformer views where the camera is oriented at the side of the player, but nothing really working for a top down view like startdew Valley.

I am not using physics, so I move the character on the tilemap using a Couroutine which moves the player to the next position on grid, here it is my Update and DoMove methods:

```<code>    private void Update()
    {
        if (!isMoving)
        {
            input.x = Input.GetAxisRaw("Horizontal");
            input.y = Input.GetAxisRaw("Vertical");

            if (input.x != 0)
                input.y = 0;

            if (input != Vector2.zero)
            {
                animator.SetFloat("Horizontal", input.x);
                animator.SetFloat("Vertical", input.y);

                var targetPos =  transform.position + new Vector3(input.x, input.y, 0f);

                // obstacle detection
                Vector3Int obstaclesMapTile = obstacles.WorldToCell(targetPos - new Vector3(0, .5f, 0));

                if (obstacles.GetTile(obstaclesMapTile) == null)
                {
                    StartCoroutine(DoMove(targetPos));
                }
            }

            animator.SetFloat("Speed", input.sqrMagnitude);
        }
    }

    private IEnumerator DoMove(Vector3 newPos)
    {
        isMoving = true;

        while ((newPos - transform.position).sqrMagnitude > Mathf.Epsilon)
        {
            transform.position = Vector3.MoveTowards(transform.position, newPos, moveSpeed * Time.fixedDeltaTime);
            yield return null;
        }

        transform.position = newPos;
        isMoving = false;
    }
</code>```

Is there anybody which could give me an hint on how to add a jumping feature? ( ideally with animation support?) I am kind of running out of ideas.

Thanks in advance.

答:
Just think of it as animation only. Since it is 2D top down, it's more about it looking like it jumps, and then if it has to go over something while in the jump animation, test for just that.
For example; if over hole and jump animation is playing, then allow movement over the whole, otherwise fall. So if the player presses the button for jump, the animation would play, and there should be some variable storing what animation the player is currently in.</p>

Body:
I am struggling to find an efficient way to let my player jump in a 2D Top Down world. I can see a lot of tutorials about platformer views where the camera is oriented at the side of the player, but nothing really working for a top down view like startdew Valley.

I am not using physics, so I move the character on the tilemap using a Couroutine which moves the player to the next position on grid, here it is my Update and DoMove methods:

    private void Update()
    {
        if (!isMoving)
        {
            input.x = Input.GetAxisRaw("Horizontal");
            input.y = Input.GetAxisRaw("Vertical");

            if (input.x != 0)
                input.y = 0;

            if (input != Vector2.zero)
            {
                animator.SetFloat("Horizontal", input.x);
                animator.SetFloat("Vertical", input.y);

                var targetPos =  transform.position + new Vector3(input.x, input.y, 0f);

                // obstacle detection
                Vector3Int obstaclesMapTile = obstacles.WorldToCell(targetPos - new Vector3(0, .5f, 0));

                if (obstacles.GetTile(obstaclesMapTile) == null)
                {
                    StartCoroutine(DoMove(targetPos));
                }
            }

            animator.SetFloat("Speed", input.sqrMagnitude);
        }
    }

    private IEnumerator DoMove(Vector3 newPos)
    {
        isMoving = true;

        while ((newPos - transform.position).sqrMagnitude > Mathf.Epsilon)
        {
            transform.position = Vector3.MoveTowards(transform.position, newPos, moveSpeed * Time.fixedDeltaTime);
            yield return null;
        }

        transform.position = newPos;
        isMoving = false;
    }

Is there anybody which could give me an hint on how to add a jumping feature? ( ideally with animation support?) I am kind of running out of ideas.

Thanks in advance.


问:
Solana Anchor Error: failed to send transaction: invalid transaction: Transaction failed to sanitize accounts offsets correctly
I am trying to run the following code in Anchor Solana, with program in rust as follows:

```<code>        use anchor_lang::prelude::*;

        declare_id!("RnbXAWg5mCvmSafjd1CnYaz32qLgZHdeHK6xzHDi1yU");

        #[program]
        pub mod sol_proj_1 {
            use super::*;
            pub fn initialize(ctx: Context<Initialize>, data: u64) -> ProgramResult {
                let my_account = &mut ctx.accounts.my_account;
                my_account.data = data;
                println!("hello there!");

                Ok(())
            }
            pub fn update(ctx: Context<Update>, data: u64) -> ProgramResult {
                let my_account = &mut ctx.accounts.my_account;
                my_account.data = data;
                Ok(())
            }
        }
        // #[derive(Accounts)]
        // pub struct Initialize {}
        #[derive(Accounts)]
        pub struct Initialize<'info> {
            #[account(init, payer = user, space = 8 + 8)]
            pub my_account: Account<'info, MyAccount>,
            #[account(mut)]
            pub user: Signer<'info>,
            pub system_program: Program<'info, System>,
        }

        #[derive(Accounts)]
        pub struct Update<'info> {
            #[account(mut)]
            pub my_account: Account<'info, MyAccount>,
        }

        #[account]
        pub struct MyAccount {
            pub data: u64,
        }
</code>```

The test program is as follow:

```<code>        import * as anchor from '@project-serum/anchor';
        import { Program } from '@project-serum/anchor';
        import { SolProj1 } from '../target/types/sol_proj_1';
        const assert = require("assert");

        describe('sol_proj_1', () => {

          // Configure the client to use the local cluster.
          const provider = anchor.Provider.local();

           anchor.setProvider(provider);

          // The Account to create.
          const myAccount = anchor.web3.Keypair.generate();

          const program = anchor.workspace.SolProj1 as Program<SolProj1>;

          it('Is initialized!', async () => {

            // Add your test here.
            const tx = await program.rpc.initialize(new anchor.BN(1234), {
              accounts: {
                myAccount: myAccount.publicKey,
                user: provider.wallet.publicKey,
                systemProgram: program.programId,
              },
              signers: [myAccount],
            });

            /
            console.log("Your transaction signature", tx);
          });

        });
</code>```

With error when I run the following command

Anchor test

```<code>  1) sol_proj_1
       Is initialized!:
     Error: failed to send transaction: invalid transaction: Transaction failed to sanitize accounts offsets correctly
      at Connection.sendEncodedTransaction (node_modules/@solana/web3.js/src/connection.ts:3740:13)
      at processTicksAndRejections (node:internal/process/task_queues:96:5)
      at Connection.sendRawTransaction (node_modules/@solana/web3.js/src/connection.ts:3700:20)
      at sendAndConfirmRawTransaction (node_modules/@solana/web3.js/src/util/send-and-confirm-raw-transaction.ts:27:21)
      at Provider.send (node_modules/@project-serum/anchor/src/provider.ts:118:18)
      at Object.rpc [as initialize] (node_modules/@project-serum/anchor/src/program/namespace/rpc.ts:25:23)
</code>```

I tried the following

change the program ownership as I found that this can cause the issue but that did not work.

I also added entries in Anchor.toml, the tests are running on localhost

I found that empty wallet may also cause this issue but I have airdrop 100 sols in it

The Rust code deploys correctly but the test is failing the 'sanitizationfailure' is listed as follow "Transaction failed to sanitize accounts offsets correctly implies that account locks are not taken for this TX, and should not be unlocked." I couldn't find any info how to take out the locks
source: https://docs.rs/solana-sdk/1.9.2/solana_sdk/transaction/enum.TransactionError.html

Any help is appreciated!

答:
The only thing I can see obvious is maybe the way you're passing in the system program from the frontend.  You're passing in your program's id, when you should be passing the in system program id.  So instead, try:</p>
```<code>const tx = await program.rpc.initialize(new anchor.BN(1234), {
     accounts: {
         myAccount: myAccount.publicKey,
         user: provider.wallet.publicKey,
         systemProgram: SystemProgram.programId,
     },
     signers: [myAccount],
});
</code>```

Body:
I am trying to run the following code in Anchor Solana, with program in rust as follows:

        use anchor_lang::prelude::*;

        declare_id!("RnbXAWg5mCvmSafjd1CnYaz32qLgZHdeHK6xzHDi1yU");

        #[program]
        pub mod sol_proj_1 {
            use super::*;
            pub fn initialize(ctx: Context<Initialize>, data: u64) -> ProgramResult {
                let my_account = &mut ctx.accounts.my_account;
                my_account.data = data;
                println!("hello there!");

                Ok(())
            }
            pub fn update(ctx: Context<Update>, data: u64) -> ProgramResult {
                let my_account = &mut ctx.accounts.my_account;
                my_account.data = data;
                Ok(())
            }
        }
        // #[derive(Accounts)]
        // pub struct Initialize {}
        #[derive(Accounts)]
        pub struct Initialize<'info> {
            #[account(init, payer = user, space = 8 + 8)]
            pub my_account: Account<'info, MyAccount>,
            #[account(mut)]
            pub user: Signer<'info>,
            pub system_program: Program<'info, System>,
        }

        #[derive(Accounts)]
        pub struct Update<'info> {
            #[account(mut)]
            pub my_account: Account<'info, MyAccount>,
        }

        #[account]
        pub struct MyAccount {
            pub data: u64,
        }

The test program is as follow:

        import * as anchor from '@project-serum/anchor';
        import { Program } from '@project-serum/anchor';
        import { SolProj1 } from '../target/types/sol_proj_1';
        const assert = require("assert");

        describe('sol_proj_1', () => {

          // Configure the client to use the local cluster.
          const provider = anchor.Provider.local();

           anchor.setProvider(provider);

          // The Account to create.
          const myAccount = anchor.web3.Keypair.generate();

          const program = anchor.workspace.SolProj1 as Program<SolProj1>;

          it('Is initialized!', async () => {

            // Add your test here.
            const tx = await program.rpc.initialize(new anchor.BN(1234), {
              accounts: {
                myAccount: myAccount.publicKey,
                user: provider.wallet.publicKey,
                systemProgram: program.programId,
              },
              signers: [myAccount],
            });

            /
            console.log("Your transaction signature", tx);
          });

        });

With error when I run the following command

Anchor test

  1) sol_proj_1
       Is initialized!:
     Error: failed to send transaction: invalid transaction: Transaction failed to sanitize accounts offsets correctly
      at Connection.sendEncodedTransaction (node_modules/@solana/web3.js/src/connection.ts:3740:13)
      at processTicksAndRejections (node:internal/process/task_queues:96:5)
      at Connection.sendRawTransaction (node_modules/@solana/web3.js/src/connection.ts:3700:20)
      at sendAndConfirmRawTransaction (node_modules/@solana/web3.js/src/util/send-and-confirm-raw-transaction.ts:27:21)
      at Provider.send (node_modules/@project-serum/anchor/src/provider.ts:118:18)
      at Object.rpc [as initialize] (node_modules/@project-serum/anchor/src/program/namespace/rpc.ts:25:23)

I tried the following

change the program ownership as I found that this can cause the issue but that did not work.

I also added entries in Anchor.toml, the tests are running on localhost

I found that empty wallet may also cause this issue but I have airdrop 100 sols in it

The Rust code deploys correctly but the test is failing the 'sanitizationfailure' is listed as follow "Transaction failed to sanitize accounts offsets correctly implies that account locks are not taken for this TX, and should not be unlocked." I couldn't find any info how to take out the locks
source: https://docs.rs/solana-sdk/1.9.2/solana_sdk/transaction/enum.TransactionError.html

Any help is appreciated!

Body:
The only thing I can see obvious is maybe the way you're passing in the system program from the frontend.  You're passing in your program's id, when you should be passing the in system program id.  So instead, try:

const tx = await program.rpc.initialize(new anchor.BN(1234), {
     accounts: {
         myAccount: myAccount.publicKey,
         user: provider.wallet.publicKey,
         systemProgram: SystemProgram.programId,
     },
     signers: [myAccount],
});


问:
How to change text on mouse event in React
I'm trying to use the onMouseDown event in react to change the text but it doesn't work.
I saw a similar code which actually worked so I have no idea what could be wrong.

```<code>import React, { Component } from "react";

import "./ContentComponent.css";

class Content extends Component{
    constructor(){
        super()

        this.onClickForward = this.onClickForward.bind(this)
        this.onClickBack = this.onClickBack.bind(this)

        const img0 = require('./images/dog1.jpg');
        const img1 = require('./images/dog2.jpg');
        const img2 = require('./images/dog3.jpg');
        const img3 = require('./images/dog4.jpg');

        this.state={
            index: 0,
            imgList: [img0, img1, img2, img3]
        }

        this.state2 = {
            tekst: "Pies"
        }

    }
 onClickForward(){
            if (this.state.index + 1 === this.state.imgList.lenght) {
                this.setState({
                    index: 0
                })
            } else{
                this.setState({
                    index: this.state.index +1
                })
            }
        }

        onClickBack(){
            if (this.state.index - 1 === -1) {
                this.setState({
                    index: this.state.imgList.lenght -1
                })
            } else{
                this.setState({
                    index: this.state.index - 1
                })
            }
        }

        zmianaTekstu() {
            this.setState2({
                tekst: "Pies domowy - udomowiony gatunek ssaka drapieżnego z rodziny psowatych, traktowany przez niektóre ujęcia systematyczne za podgatunek wilka."
            })
        }

    render(){
        return(
            <div className="info">
                <img src={this.state.imgList[this.state.index]} alt="" className="mainImage" />
                <div className="btns">
                <button onClick={this.onClickBack}>Poprzednie</button>
                <button onClick={this.onClickForward}>Następne</button>
                </div>
                <div className="textInfo">
                    <h3 onMouseDown={() => this.zmianaTekstu()}>Click to change text</h3>
                    <p>{this.state2.tekst}</p>
                </div>
            </div>
        )
    }

}

export default Content;
</code>```

Console says

Uncaught TypeError: this.setState2 is not a function

The first state which changes images on button click actually works but I've pasted the whole code since maybe there is some interaction.

答: the setState method is specific to your component, you cannot use another method to modify another state in your component, you could put all your data in the first state object or also use state hooks ?</p>

Body:
I'm trying to use the onMouseDown event in react to change the text but it doesn't work.
I saw a similar code which actually worked so I have no idea what could be wrong.

import React, { Component } from "react";

import "./ContentComponent.css";

class Content extends Component{
    constructor(){
        super()

        this.onClickForward = this.onClickForward.bind(this)
        this.onClickBack = this.onClickBack.bind(this)

        const img0 = require('./images/dog1.jpg');
        const img1 = require('./images/dog2.jpg');
        const img2 = require('./images/dog3.jpg');
        const img3 = require('./images/dog4.jpg');

        this.state={
            index: 0,
            imgList: [img0, img1, img2, img3]
        }

        this.state2 = {
            tekst: "Pies"
        }

    }
 onClickForward(){
            if (this.state.index + 1 === this.state.imgList.lenght) {
                this.setState({
                    index: 0
                })
            } else{
                this.setState({
                    index: this.state.index +1
                })
            }
        }

        onClickBack(){
            if (this.state.index - 1 === -1) {
                this.setState({
                    index: this.state.imgList.lenght -1
                })
            } else{
                this.setState({
                    index: this.state.index - 1
                })
            }
        }

        zmianaTekstu() {
            this.setState2({
                tekst: "Pies domowy - udomowiony gatunek ssaka drapieżnego z rodziny psowatych, traktowany przez niektóre ujęcia systematyczne za podgatunek wilka."
            })
        }

    render(){
        return(

                <button onClick={this.onClickBack}>Poprzednie</button>
                <button onClick={this.onClickForward}>Następne</button>

 this.zmianaTekstu()}>Click to change text

{this.state2.tekst}

        )
    }

}

export default Content;

Console says

Uncaught TypeError: this.setState2 is not a function

The first state which changes images on button click actually works but I've pasted the whole code since maybe there is some interaction.


问:
Change div content on mouse hover with default content fallback
I've implemented the accepted answer to Change div content based on mouse hover on different divs across a lot of links, so I don't really want to go with another solution if it can be avoided. I'm trying to figure out one more piece of the puzzle though...

I can't seem to get it to where it defaults back to the original text of the content div when not hovering over an item.

```<code><div id="content">
    Stuff should be placed here.
</div>

<br/>
<br/>
<br/>
<ul>
    <li onmouseover="hover('Apples are delicious')">Apple</li>
    <li onmouseover="hover('oranges are healthy')">Orange</li>
    <li onmouseover="hover('Candy is the best')">Candy</li>
</ul>

<script>
    function hover(description) {
        console.log(description);
        document.getElementById('content').innerHTML = description;
    }
</script>
</code>```

答:
You can achieve the same without any Javascript:

li::before { content: attr(data-text); }
li:hover::before { content: attr(data-text-hover); }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
    <li data-text-hover="Apples are delicious" data-text="Apple"></li>
    <li data-text-hover="Oranges are healthy" data-text="Orange"></li>
    <li data-text-hover="Candy is the best" data-text="Candy"></li>
</ul></code>```

Body:
I've implemented the accepted answer to Change div content based on mouse hover on different divs across a lot of links, so I don't really want to go with another solution if it can be avoided. I'm trying to figure out one more piece of the puzzle though...

I can't seem to get it to where it defaults back to the original text of the content div when not hovering over an item.

    Stuff should be placed here.

Apple

Orange

Candy

Body:
You can achieve the same without any Javascript:

li::before { content: attr(data-text); }
li:hover::before { content: attr(data-text-hover); }

<ul>
    <li data-text-hover="Apples are delicious" data-text="Apple"></li>
    <li data-text-hover="Oranges are healthy" data-text="Orange"></li>
    <li data-text-hover="Candy is the best" data-text="Candy"></li>
</ul>


问:
C# panel background image splitting on scrolling
I'm working on a winforms application using C#. I have a form with background image, and a panel on that with transparent background. Some data and controls will be dynamically created on this panel.

This panel has a scroll bar, when I scrolls that background image is splitting and page and data is looking very odd.

Can anyone help me in fixing this issue? All I need that background image should not split on scrolling of the panel...

Thanks in Advance.
Suhasini

答: This seems to be a limitation on winforms. Check out this post for an explanation.</p>


问:
Firebase authorisation and registration
I am trying to create a basic app for my small educational business.

We supply English teachers to schools and I want a way for parents to access the progress reports and other data about their children.

I'm using Android Studio and Flutter as well as Firebase to store the data. I don't want parents to be able to access the data of every child, obviously, but they may have more than one child at the school.

So I need to limit their read privileges to just the records that relate to their children. I'd like to do that by giving them some sort of registration code that they could use the first time they access the app so that we can ensure that they are only being given access to the correct records. Subsequent logins would then be via email and password.

Is there a way to do this with Firebase?

答:
Your use-case sounds feasible, but it is really broad which makes it impossible to answer it completely-yet-succinctly.

Specific on what to do with the registration code that associates a parent with their children, when you generate the registration code, you write that code and the associated children to a database. Then when the parent registers with that code, you associate their account (UID) with the code. You'll just have to ensure that the code is sufficiently long and random that it can't be reasonably guessed by another user.

Title: Firebase authorisation and registration


问:
How to update model fields from views with values from a href/url?
I'm making a events website, I need to show the event history of a user logged in.

Currently I'm only passing Event instance to below template not User instance

So when he clicks on Register for Event button on a certain event with id event.id.

```<code>{%for event in events%}
        <div class='card-event'>
                <div style="font-weight: 600; margin-top:5px;font-size: 20px;">{{event.name}}</div>
                <div style="margin:10px 0 5px 0;">{{event.event_desc}}</div>
                <div style="margin:5px 0 10px 0;">Entry Fee: {{event.entry_fee}}</div>
                <a href="{%url 'update-event' value1=user.id value2=event.id%}"><button class='register-button'>Register for Event</button></a>
        </div>
        {%endfor%}
</code>```

He is redirected to url

```<code>path('update-event/<value1>/<value2>/',web_views.update_event,name='update-event')
</code>```

Then the update_event view where database is updated,and is redirected to a simple stable template my_events.html

```<code>def update_event(request,value1,value2):
    user= User.objects.get(id=value1)
    ev=Event.objects.get(id=value2)
    data=Participated(user_id=user,event_id=ev)
    data.save()
    return redirect(request,'webpage/my_events.html')
</code>```

This is the Participated model

```<code>class Participated(models.Model):
    user_id=models.ForeignKey(User,on_delete=models.CASCADE)
    event_id=models.ForeignKey(Event,on_delete=models.PROTECT)
</code>```

I'm getting an error

```<code>Reverse for '<WSGIRequest: GET '/update-event/1/4/'>' not found. '<WSGIRequest: GET '/update-event/1/4/'>' is not a valid view function or pattern name.
</code>```

So how to insert values to Partcipated model?

Edit: Even after changing the path as below it's not working

```<code>path('update-event/<int:value1>/<int:value2>/',web_views.update_event,name='update-event')
</code>```

Edit2: My complete urls.py(I'm using only the main urls.py for all urls)

```<code>from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.urls import path,include
from django.conf import settings
from django.conf.urls.static import static
from webpage import views as web_views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('webpage.urls')),
    path('college/',web_views.college,name='college'),
    path('fest/',web_views.fest,name='fest'),
    path('fest/college/',web_views.fest_college,name='fest-college'),
    path('fest/technical/',web_views.fest_technical,name='fest-technical'),
    path('fest/cultural/',web_views.fest_cultural,name='fest-cultural'),
    path('fest/sports/',web_views.fest_sports,name='fest-sports'),
    path('fest/<value>/',web_views.fest_clg,name='fest-clg'),
    path('event/',web_views.event,name='event'),
    path('event/<value>/',web_views.event_fest,name='event-fest'),
    path('my-events/',web_views.my_events,name='my-events'),
    path('update-event/<int:value1>/<int:value2>/',web_views.update_event,name='update-event'),
    path('register/',web_views.register,name='register'),
    path('login/',auth_views.LoginView.as_view(template_name='webpage/login.html'),name='login'),
    path('logout/',auth_views.LogoutView.as_view(template_name='webpage/logout.html'),name='logout')
]

if settings.DEBUG:
    urlpatterns+=static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
</code>```

I also added user instance to my event view like this

```<code>def event(request):
    cur=request.user
    context={
        'events':Event.objects.all(),
        'user': User.objects.get(id=cur.id)
    }
    return render(request,'webpage/event.html',context)
</code>```

This is django-project in github https://github.com/GaganKaranth/fests-bangalore/tree/main

答:
The path will try to find patterns that have ints for user_id and event_id if you do this:

# urls.py

urlpatterns = [
    ...
    path('update-event/<int:user_id>/<int:event_id>/',web_views.update_event,name='update-event'),
    ...
]
```
<p>Then in your view, you can grab those, but they must have the same names you gave them in the url patterns, like this:</p>
<pre class="lang-py prettyprint-override"><code># views.py
def update_event(request, user_id, event_id):
    user= User.objects.get(id=user_id)
    ev=Event.objects.get(id=event_id)
    ...
</code>```

Then your html url anchor tage will pass these two ints, in order:

href="{% url 'update-event' user.id event.id %}">
```

Body:
I'm making a events website, I need to show the event history of a user logged in.

Currently I'm only passing Event instance to below template not User instance

So when he clicks on Register for Event button on a certain event with id event.id.

{%for event in events%}

{{event.name}}

{{event.event_desc}}

Entry Fee: {{event.entry_fee}}

                <button class='register-button'>Register for Event</button>

        {%endfor%}

He is redirected to url

path('update-event/<value1>/<value2>/',web_views.update_event,name='update-event')

Then the update_event view where database is updated,and is redirected to a simple stable template my_events.html

def update_event(request,value1,value2):
    user= User.objects.get(id=value1)
    ev=Event.objects.get(id=value2)
    data=Participated(user_id=user,event_id=ev)
    data.save()
    return redirect(request,'webpage/my_events.html')

This is the Participated model

class Participated(models.Model):
    user_id=models.ForeignKey(User,on_delete=models.CASCADE)
    event_id=models.ForeignKey(Event,on_delete=models.PROTECT)

I'm getting an error

Reverse for '<WSGIRequest: GET '/update-event/1/4/'>' not found. '<WSGIRequest: GET '/update-event/1/4/'>' is not a valid view function or pattern name.

So how to insert values to Partcipated model?

Edit: Even after changing the path as below it's not working

path('update-event/<int:value1>/<int:value2>/',web_views.update_event,name='update-event')

Edit2: My complete urls.py(I'm using only the main urls.py for all urls)

from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.urls import path,include
from django.conf import settings
from django.conf.urls.static import static
from webpage import views as web_views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('webpage.urls')),
    path('college/',web_views.college,name='college'),
    path('fest/',web_views.fest,name='fest'),
    path('fest/college/',web_views.fest_college,name='fest-college'),
    path('fest/technical/',web_views.fest_technical,name='fest-technical'),
    path('fest/cultural/',web_views.fest_cultural,name='fest-cultural'),
    path('fest/sports/',web_views.fest_sports,name='fest-sports'),
    path('fest/<value>/',web_views.fest_clg,name='fest-clg'),
    path('event/',web_views.event,name='event'),
    path('event/<value>/',web_views.event_fest,name='event-fest'),
    path('my-events/',web_views.my_events,name='my-events'),
    path('update-event/<int:value1>/<int:value2>/',web_views.update_event,name='update-event'),
    path('register/',web_views.register,name='register'),
    path('login/',auth_views.LoginView.as_view(template_name='webpage/login.html'),name='login'),
    path('logout/',auth_views.LogoutView.as_view(template_name='webpage/logout.html'),name='logout')
]

if settings.DEBUG:
    urlpatterns+=static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)

I also added user instance to my event view like this

def event(request):
    cur=request.user
    context={
        'events':Event.objects.all(),
        'user': User.objects.get(id=cur.id)
    }
    return render(request,'webpage/event.html',context)

This is django-project in github https://github.com/GaganKaranth/fests-bangalore/tree/main

Body:
The path will try to find patterns that have ints for user_id and event_id if you do this:

# urls.py

urlpatterns = [
    ...
    path('update-event/<int:user_id>/<int:event_id>/',web_views.update_event,name='update-event'),
    ...
]

Then in your view, you can grab those, but they must have the same names you gave them in the url patterns, like this:

# views.py
def update_event(request, user_id, event_id):
    user= User.objects.get(id=user_id)
    ev=Event.objects.get(id=event_id)
    ...

Then your html url anchor tage will pass these two ints, in order:

<a href="{% url 'update-event' user.id event.id %}">


问:
Akka: issue with Timer
I'm trying to create actor, which perform some action on timer. So I seek a way to schedule actor messages to self.

For this aim I use Behaviors.withTimers

```<code>object Consumer {
     sealed trait Command
     private object Timeout extends Command
     private case object TimerKey

     def apply(): Behavior[Command] = {
            Behaviors.withTimers(timers => new Consumer(timers).idle())
     }
  }
</code>```

Method idle() must start sending messages Timeout to self in regular intervals.

```<code>  class Consumer(timers: TimerScheduler[Command]) {

       private def idle(): Behavior[Command] = {
           timers.startTimerWithFixedDelay(TimerKey, Timeout, FiniteDuration.apply(1, SECONDS))
           action()
           Behaviors.same
       }

       def action(): Behavior[Command] = {
             Behaviors.receiveMessage[Command] {
                case Timeout => println(" Consumer action done")
                Behaviors.same
         }
      }
    }
</code>```

And action() must hook this messages against Behavior[Command]. But this is not happening. For some reasons, as I understand, timers not started. But what are that reasons?

答:
The timers are being started and the Timeout message is being sent, but your Consumer actor isn't handling it, so the println never executes.

Your apply injects timers into Consumer.  In idle, you're starting the timer, then calling action to construct a new Behavior, but you then throw it away and actually use the same behavior your actor has (which won't respond to any messages).

idle should probably be defined along these lines (I'm also using the duration DSL: import scala.concurrent.duration._)

timers.startTimerWithFixedDelay(TimerKey, Timeout, 1.second)
action()
```

Title: Akka: issue with Timer

Body:
I'm trying to create actor, which perform some action on timer. So I seek a way to schedule actor messages to self.

For this aim I use Behaviors.withTimers

object Consumer {
     sealed trait Command
     private object Timeout extends Command
     private case object TimerKey

     def apply(): Behavior[Command] = {
            Behaviors.withTimers(timers => new Consumer(timers).idle())
     }
  }

Method idle() must start sending messages Timeout to self in regular intervals.

  class Consumer(timers: TimerScheduler[Command]) {

       private def idle(): Behavior[Command] = {
           timers.startTimerWithFixedDelay(TimerKey, Timeout, FiniteDuration.apply(1, SECONDS))
           action()
           Behaviors.same
       }

       def action(): Behavior[Command] = {
             Behaviors.receiveMessage[Command] {
                case Timeout => println(" Consumer action done")
                Behaviors.same
         }
      }
    }

And action() must hook this messages against Behavior[Command]. But this is not happening. For some reasons, as I understand, timers not started. But what are that reasons?