问:
HTML/JS - Start timer on load
All works great. At the moment, I don't have to press the button to start the timer, it start automatically on page load. Problem is the start, stop and reset buttons still appeared. When I hide the button code the timer not working. When the page load the buttons should not be appeared and timer should work fine.

Here is my code:

```<code><!DOCTYPE html>
<html>
  <head>
    <title>30 second countdown timer</title>
  </head>
  <body onload="startTimer();">
    <div id="countdown">
      <div id="countdown-number">30</div>
    </div>
    <div class="action-list">
      <button id="stop">
        <img src="https://img.icons8.com/ios-glyphs/30/000000/pause--v1.png" />
      </button>
      <button id="start">
        <img src="https://img.icons8.com/ios-glyphs/30/000000/play--v1.png" />
      </button>
      <button id="reset">
        <img src="https://img.icons8.com/ios-glyphs/30/000000/stop.png" />
      </button>
    </div>
    <audio id="timeout_audio"></audio>
  </body>
</html>

<script>
  // Select Countdown container
const countContainer = document.getElementById("countdown-number");

// Select action buttons
const startButton = document.getElementById("start");
const stopButton = document.getElementById("stop");
const resetButton = document.getElementById("reset");

// Select timeout Audio element
const timeoutAudio = document.getElementById("timeout_audio");

// variable to store count
var remainingTime = 30;

// variable to store time interval
var timer;

// Variable to track whether timer is running or not
var isStopped = true;

// Function to start Timer
const startTimer = () => {
  if (isStopped) {
    isStopped = false;
    countContainer.innerHTML = remainingTime;
    timer = setInterval(renderTime, 1000);
  }
};

// Function to stop Timer
const stopTimer = () => {
  isStopped = true;
  if (timer) {
    clearInterval(timer);
  }
};

// Function to reset Timer
const resetTimer = () => {
  isStopped = true;
  clearInterval(timer);
  remainingTime = 30;
  countContainer.innerHTML = remainingTime;
};

// Initialize timeout sound
timeoutAudio.src = "http://soundbible.com/grab.php?id=1252&type=mp3";
timeoutAudio.load();

// Attach onclick event to buttons
startButton.onclick = startTimer;
resetButton.onclick = resetTimer;
stopButton.onclick = stopTimer;

// function to display time
const renderTime = () => {
  // decement time
  remainingTime -= 1;
  // render count on the screen
  countContainer.innerHTML = remainingTime;
  // timeout on zero
  if (remainingTime === 0) {
    isStopped = true;
    clearInterval(timer);
    // Play audio on timeout
    timeoutAudio.play();
    remainingTime = 30;
  }
};
</script>
<style>
  body {
  font-family: sans-serif;
  height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-image: url("https://img4.goodfon.com/wallpaper/nbig/1/2e/multfilm-shou-simpsons-personazh-20th-century-fox-art-ris-15.jpg");
}
#countdown {
  display: flex;
  justify-content: center;
  align-items: center;
  color: #0e2c4c;
  font-size: 70px;
  width: 200px;
  height: 200px;
  background-color: #e7d9fc;
  border-radius: 50%;
}
.action-list {
  display: flex;
  gap: 30px;
  margin-top: 30px;
}
button {
  border: none;
  background-color: #e7d9fc;
  border-radius: 50%;
  width: 60px;
  height: 60px;
  cursor: pointer;
}
</style>
</code>```

答:
Try this:
This will not show buttons after loading and highlight the button last pressed and the play button is highlighted by default.</p>
```<code><!DOCTYPE html>
<html>

<head>
  <title>30 second countdown timer</title>
  <style>
    body {
      font-family: sans-serif;
      height: 100vh;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      background-image: url("https://img4.goodfon.com/wallpaper/nbig/1/2e/multfilm-shou-simpsons-personazh-20th-century-fox-art-ris-15.jpg");
    }

    #countdown {
      display: flex;
      justify-content: center;
      align-items: center;
      color: #0e2c4c;
      font-size: 70px;
      width: 200px;
      height: 200px;
      background-color: #e7d9fc;
      border-radius: 50%;
    }

    .action-list {
      display: flex;
      gap: 30px;
      margin-top: 30px;
    }

    button {
      border: none;
      background-color: #e7d9fc;
      border-radius: 50%;
      width: 60px;
      height: 60px;
      cursor: pointer;
    }
  </style>

</head>

<body>
  <div id="countdown">
    <div id="countdown-number">30</div>
  </div>
  <div class="action-list">
    <button id="stop">
      <img src="https://img.icons8.com/ios-glyphs/30/000000/pause--v1.png" />
    </button>
    <button id="start">
      <img src="https://img.icons8.com/ios-glyphs/30/000000/play--v1.png" />
    </button>
    <button id="reset">
      <img src="https://img.icons8.com/ios-glyphs/30/000000/stop.png" />
    </button>
  </div>
  <audio id="timeout_audio"></audio>

  <script>

       var x = document.getElementsByClassName('action-list')[0];

       const countContainer = document.getElementById("countdown-number");

      // Select action buttons
      const startButton = document.getElementById("start");
      const stopButton = document.getElementById("stop");
      const resetButton = document.getElementById("reset");

      // Select timeout Audio element
      const timeoutAudio = document.getElementById("timeout_audio");

      // variable to store count
      var remainingTime = 30;

      // variable to store time interval
      var timer;

      // Variable to track whether timer is running or not
      var isStopped = true;

      // Function to start Timer
      const startTimer = () => {

        startButton.style.background = "green";
        stopButton.style.background = "#e7d9fc"
        x.style.display = "none";
        if (isStopped) {
          isStopped = false;
          countContainer.innerHTML = remainingTime;
          timer = setInterval(renderTime, 1000);
        }
      };

      // Function to stop Timer
      const stopTimer = () => {
        startButton.style.background = "#e7d9fc";
        stopButton.style.background = "green"
        isStopped = true;
        if (timer) {
          clearInterval(timer);
        }
      };

      // Function to reset Timer
      const resetTimer = () => {
        isStopped = true;
        clearInterval(timer);
        remainingTime = 30;
        countContainer.innerHTML = remainingTime;
      };

      // Initialize timeout sound
      timeoutAudio.src = "http://soundbible.com/grab.php?id=1252&type=mp3";
      timeoutAudio.load();

      // Attach onclick event to buttons
      startButton.onclick = startTimer;
      resetButton.onclick = resetTimer;
      stopButton.onclick = stopTimer;

      // function to display time
      const renderTime = () => {
        // decement time
        remainingTime -= 1;
        // render count on the screen
        countContainer.innerHTML = remainingTime;
        // timeout on zero
        if (remainingTime === 0) {
          isStopped = true;
          clearInterval(timer);
          x.style.display = "block";
          // Play audio on timeout
          timeoutAudio.play();
          remainingTime = 30;
        }
      };

      startTimer();

  </script>

</body>

</html>
</code>```

Title: HTML/JS - Start timer on load

Body:
All works great. At the moment, I don't have to press the button to start the timer, it start automatically on page load. Problem is the start, stop and reset buttons still appeared. When I hide the button code the timer not working. When the page load the buttons should not be appeared and timer should work fine.

Here is my code:

<!DOCTYPE html>

    <title>30 second countdown timer</title>

30

      <button id="stop">

      </button>
      <button id="start">

      </button>
      <button id="reset">

      </button>

    <audio id="timeout_audio"></audio>

Body:
Try this:
This will not show buttons after loading and highlight the button last pressed and the play button is highlighted by default.

<!DOCTYPE html>
<html>

<head>
  <title>30 second countdown timer</title>
  <style>
    body {
      font-family: sans-serif;
      height: 100vh;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      background-image: url("https://img4.goodfon.com/wallpaper/nbig/1/2e/multfilm-shou-simpsons-personazh-20th-century-fox-art-ris-15.jpg");
    }

    #countdown {
      display: flex;
      justify-content: center;
      align-items: center;
      color: #0e2c4c;
      font-size: 70px;
      width: 200px;
      height: 200px;
      background-color: #e7d9fc;
      border-radius: 50%;
    }

    .action-list {
      display: flex;
      gap: 30px;
      margin-top: 30px;
    }

    button {
      border: none;
      background-color: #e7d9fc;
      border-radius: 50%;
      width: 60px;
      height: 60px;
      cursor: pointer;
    }
  </style>

</head>

<body>
  <div id="countdown">
    <div id="countdown-number">30</div>
  </div>
  <div class="action-list">
    <button id="stop">
      <img src="https://img.icons8.com/ios-glyphs/30/000000/pause--v1.png" />
    </button>
    <button id="start">
      <img src="https://img.icons8.com/ios-glyphs/30/000000/play--v1.png" />
    </button>
    <button id="reset">
      <img src="https://img.icons8.com/ios-glyphs/30/000000/stop.png" />
    </button>
  </div>
  <audio id="timeout_audio"></audio>

  <script>

       var x = document.getElementsByClassName('action-list')[0];

       const countContainer = document.getElementById("countdown-number");

      // Select action buttons
      const startButton = document.getElementById("start");
      const stopButton = document.getElementById("stop");
      const resetButton = document.getElementById("reset");

      // Select timeout Audio element
      const timeoutAudio = document.getElementById("timeout_audio");

      // variable to store count
      var remainingTime = 30;

      // variable to store time interval
      var timer;

      // Variable to track whether timer is running or not
      var isStopped = true;

      // Function to start Timer
      const startTimer = () => {

        startButton.style.background = "green";
        stopButton.style.background = "#e7d9fc"
        x.style.display = "none";
        if (isStopped) {
          isStopped = false;
          countContainer.innerHTML = remainingTime;
          timer = setInterval(renderTime, 1000);
        }
      };

      // Function to stop Timer
      const stopTimer = () => {
        startButton.style.background = "#e7d9fc";
        stopButton.style.background = "green"
        isStopped = true;
        if (timer) {
          clearInterval(timer);
        }
      };

      // Function to reset Timer
      const resetTimer = () => {
        isStopped = true;
        clearInterval(timer);
        remainingTime = 30;
        countContainer.innerHTML = remainingTime;
      };

      // Initialize timeout sound
      timeoutAudio.src = "http://soundbible.com/grab.php?id=1252&type=mp3";
      timeoutAudio.load();

      // Attach onclick event to buttons
      startButton.onclick = startTimer;
      resetButton.onclick = resetTimer;
      stopButton.onclick = stopTimer;

      // function to display time
      const renderTime = () => {
        // decement time
        remainingTime -= 1;
        // render count on the screen
        countContainer.innerHTML = remainingTime;
        // timeout on zero
        if (remainingTime === 0) {
          isStopped = true;
          clearInterval(timer);
          x.style.display = "block";
          // Play audio on timeout
          timeoutAudio.play();
          remainingTime = 30;
        }
      };

      startTimer();

  </script>

</body>

</html>


来源: stackexchange

问:
How to Use jinja to render HTML without flask?
I need to render HTML page using jinja but without flask I read some other questions here but none had clear answer kindly let me know how can i achieve the same

```<code>File structre

1.py

HTML folder

1.html

templates
show persons.txt
</code>```

Here I need to render 1.html using 1.py - is it possble to do it in ofline mode

current 1.py

```<code>  from jinja2 import Environment, FileSystemLoader

persons = [
    {'name': 'Andrej', 'age': 34},
    {'name': 'Mark', 'age': 17},
    {'name': 'Thomas', 'age': 44},
    {'name': 'Lucy', 'age': 14},
    {'name': 'Robert', 'age': 23},
    {'name': 'Dragomir', 'age': 54}
]

file_loader = FileSystemLoader('templates')
env = Environment(loader=file_loader)

template = env.get_template('show persons.txt')

template = env.get_template('1.html ') #  how can i do the same with html here
output = template.render(persons=persons)
print(output)
</code>```

currently with this I am able to print output but if I need to get same data on a html file what can be done here  ?

Also if possible if also can we open the html page when run

updated code after Corralien comments is der a way to open this in browser directly

```<code>from jinja2 import Environment, FileSystemLoader

persons = [
    {'name': 'Andrej', 'age': 34},
    {'name': 'Mark', 'age': 17},
    {'name': 'Thomas', 'age': 44},
    {'name': 'Lucy', 'age': 14},
    {'name': 'Robert', 'age': 23},
    {'name': 'Dragomir', 'age': 54}
]

file_loader = FileSystemLoader('templates')
env = Environment(loader=file_loader)

template = env.get_template('1.html')

output = template.render(persons=persons)
print(output)
</code>```

Output

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
Andrej -  34
Mark -  17
Thomas -  44
Lucy -  14
Robert -  23
Dragomir -  54

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

答:
Assuming the template already has valid html structure, sounds like you just want to write a file

```<code>template = env.get_template('show persons.txt')
with open('HTML folder/1.html', 'w') as f:
    f.write(template.render(persons=persons))
</code>```

To load the file in the browser, you can try using os.startfile method. Otherwise, use a specific browser executable with the subprocess module

ContentLicense: CC BY-SA 4.0

Body:
I need to render HTML page using jinja but without flask I read some other questions here but none had clear answer kindly let me know how can i achieve the same

File structre

1.py

HTML folder

1.html

templates
show persons.txt

Here I need to render 1.html using 1.py - is it possble to do it in ofline mode

current 1.py

  from jinja2 import Environment, FileSystemLoader

persons = [
    {'name': 'Andrej', 'age': 34},
    {'name': 'Mark', 'age': 17},
    {'name': 'Thomas', 'age': 44},
    {'name': 'Lucy', 'age': 14},
    {'name': 'Robert', 'age': 23},
    {'name': 'Dragomir', 'age': 54}
]

file_loader = FileSystemLoader('templates')
env = Environment(loader=file_loader)

template = env.get_template('show persons.txt')

template = env.get_template('1.html ') #  how can i do the same with html here
output = template.render(persons=persons)
print(output)

currently with this I am able to print output but if I need to get same data on a html file what can be done here  ?

Also if possible if also can we open the html page when run

updated code after Corralien comments is der a way to open this in browser directly

from jinja2 import Environment, FileSystemLoader

persons = [
    {'name': 'Andrej', 'age': 34},
    {'name': 'Mark', 'age': 17},
    {'name': 'Thomas', 'age': 44},
    {'name': 'Lucy', 'age': 14},
    {'name': 'Robert', 'age': 23},
    {'name': 'Dragomir', 'age': 54}
]

file_loader = FileSystemLoader('templates')
env = Environment(loader=file_loader)

template = env.get_template('1.html')

output = template.render(persons=persons)
print(output)

Output

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

Andrej -  34
Mark -  17
Thomas -  44
Lucy -  14
Robert -  23
Dragomir -  54

Body:
Assuming the template already has valid html structure, sounds like you just want to write a file

template = env.get_template('show persons.txt')
with open('HTML folder/1.html', 'w') as f:
    f.write(template.render(persons=persons))

To load the file in the browser, you can try using os.startfile method. Otherwise, use a specific browser executable with the subprocess module


问:
How can I shorten the next repeated statement?
How can I shorten the next repeated statement?
I want to show 4~7, 5~7, 6~7, 7 for case 1,2,3,4.

The code below is very messy and I was wondering if there is a way to reduce it.

```<code>function selectTeeShotCount() {
    console.log(document.teeShotInfoForm.TeeCount);
    const radioTeeShot = document.teeShotInfoForm.TeeCount;
    let prev = null;
    for (const radioTeeShotElement of radioTeeShot) {
        radioTeeShotElement.addEventListener('change', event => {
            (prev) ? console.log(prev.value): null;
            if (this !== prev) {
                prev = this;
            }

            document.querySelector('#teeShotInfoForm > div:nth-child(3)').classList.remove('d-none');
            document.querySelector('#teeShotInfoForm > div:nth-child(4)').classList.remove('d-none');
            document.querySelector('#teeShotInfoForm > div:nth-child(5)').classList.remove('d-none');
            document.querySelector('#teeShotInfoForm > div:nth-child(6)').classList.remove('d-none');
            document.querySelector('#teeShotInfoForm > div:nth-child(7)').classList.remove('d-none');

            switch (parseInt(radioTeeShot.value)) {
                case 1:
                    document.querySelector('#teeShotInfoForm > div:nth-child(4)').classList.add('d-none');
                    document.querySelector('#teeShotInfoForm > div:nth-child(5)').classList.add('d-none');
                    document.querySelector('#teeShotInfoForm > div:nth-child(6)').classList.add('d-none');
                    document.querySelector('#teeShotInfoForm > div:nth-child(7)').classList.add('d-none');
                    break;
                case 2:
                    document.querySelector('#teeShotInfoForm > div:nth-child(5)').classList.add('d-none');
                    document.querySelector('#teeShotInfoForm > div:nth-child(6)').classList.add('d-none');
                    document.querySelector('#teeShotInfoForm > div:nth-child(7)').classList.add('d-none');
                    break;
                case 3:
                    document.querySelector('#teeShotInfoForm > div:nth-child(6)').classList.add('d-none');
                    document.querySelector('#teeShotInfoForm > div:nth-child(7)').classList.add('d-none');
                    break;
                case 4:
                    document.querySelector('#teeShotInfoForm > div:nth-child(7)').classList.add('d-none');
                    break;
            }
        });
    }
}
</code>```

答:
Another Idea is to save querySelectors result in a variable, or an array like below ( which will prevent some extra unnecessary DOM selection as well )</p>
```<code>function selectTeeShotCount() {
    console.log(document.teeShotInfoForm.TeeCount);
    const radioTeeShot = document.teeShotInfoForm.TeeCount;
    let prev = null;
    for (const radioTeeShotElement of radioTeeShot) {
        radioTeeShotElement.addEventListener('change', event => {
            (prev) ? console.log(prev.value): null;
            if (this !== prev) {
                prev = this;
            }
            const teeShotInfoFormChilds = [
                document.querySelector('#teeShotInfoForm > div:nth-child(3)'),
                document.querySelector('#teeShotInfoForm > div:nth-child(4)'),
                document.querySelector('#teeShotInfoForm > div:nth-child(5)'),
                document.querySelector('#teeShotInfoForm > div:nth-child(6)'),
                document.querySelector('#teeShotInfoForm > div:nth-child(7)')
            ];

            teeShotInfoFormChilds.forEach(el => el.classList.remove('d-none'));

            switch (parseInt(radioTeeShot.value)) {
                case 1:
                    teeShotInfoFormChilds.slice(1).forEach(el => el.classList.add('d-none'));
                    break;
                case 2:
                    teeShotInfoFormChilds.slice(2).forEach(el => el.classList.add('d-none'));
                    break;
                case 3:
                    teeShotInfoFormChilds.slice(3).forEach(el => el.classList.add('d-none'));
                    break;
                case 4:
                    teeShotInfoFormChilds.slice(4).forEach(el => el.classList.add('d-none'));
                    break;
            }
        });
    }
}
</code>```

Body:
How can I shorten the next repeated statement?
I want to show 4~7, 5~7, 6~7, 7 for case 1,2,3,4.

The code below is very messy and I was wondering if there is a way to reduce it.

function selectTeeShotCount() {
    console.log(document.teeShotInfoForm.TeeCount);
    const radioTeeShot = document.teeShotInfoForm.TeeCount;
    let prev = null;
    for (const radioTeeShotElement of radioTeeShot) {
        radioTeeShotElement.addEventListener('change', event => {
            (prev) ? console.log(prev.value): null;
            if (this !== prev) {
                prev = this;
            }

            document.querySelector('#teeShotInfoForm > div:nth-child(3)').classList.remove('d-none');
            document.querySelector('#teeShotInfoForm > div:nth-child(4)').classList.remove('d-none');
            document.querySelector('#teeShotInfoForm > div:nth-child(5)').classList.remove('d-none');
            document.querySelector('#teeShotInfoForm > div:nth-child(6)').classList.remove('d-none');
            document.querySelector('#teeShotInfoForm > div:nth-child(7)').classList.remove('d-none');

            switch (parseInt(radioTeeShot.value)) {
                case 1:
                    document.querySelector('#teeShotInfoForm > div:nth-child(4)').classList.add('d-none');
                    document.querySelector('#teeShotInfoForm > div:nth-child(5)').classList.add('d-none');
                    document.querySelector('#teeShotInfoForm > div:nth-child(6)').classList.add('d-none');
                    document.querySelector('#teeShotInfoForm > div:nth-child(7)').classList.add('d-none');
                    break;
                case 2:
                    document.querySelector('#teeShotInfoForm > div:nth-child(5)').classList.add('d-none');
                    document.querySelector('#teeShotInfoForm > div:nth-child(6)').classList.add('d-none');
                    document.querySelector('#teeShotInfoForm > div:nth-child(7)').classList.add('d-none');
                    break;
                case 3:
                    document.querySelector('#teeShotInfoForm > div:nth-child(6)').classList.add('d-none');
                    document.querySelector('#teeShotInfoForm > div:nth-child(7)').classList.add('d-none');
                    break;
                case 4:
                    document.querySelector('#teeShotInfoForm > div:nth-child(7)').classList.add('d-none');
                    break;
            }
        });
    }
}

Body:
Another Idea is to save querySelectors result in a variable, or an array like below ( which will prevent some extra unnecessary DOM selection as well )

function selectTeeShotCount() {
    console.log(document.teeShotInfoForm.TeeCount);
    const radioTeeShot = document.teeShotInfoForm.TeeCount;
    let prev = null;
    for (const radioTeeShotElement of radioTeeShot) {
        radioTeeShotElement.addEventListener('change', event => {
            (prev) ? console.log(prev.value): null;
            if (this !== prev) {
                prev = this;
            }
            const teeShotInfoFormChilds = [
                document.querySelector('#teeShotInfoForm > div:nth-child(3)'),
                document.querySelector('#teeShotInfoForm > div:nth-child(4)'),
                document.querySelector('#teeShotInfoForm > div:nth-child(5)'),
                document.querySelector('#teeShotInfoForm > div:nth-child(6)'),
                document.querySelector('#teeShotInfoForm > div:nth-child(7)')
            ];

            teeShotInfoFormChilds.forEach(el => el.classList.remove('d-none'));

            switch (parseInt(radioTeeShot.value)) {
                case 1:
                    teeShotInfoFormChilds.slice(1).forEach(el => el.classList.add('d-none'));
                    break;
                case 2:
                    teeShotInfoFormChilds.slice(2).forEach(el => el.classList.add('d-none'));
                    break;
                case 3:
                    teeShotInfoFormChilds.slice(3).forEach(el => el.classList.add('d-none'));
                    break;
                case 4:
                    teeShotInfoFormChilds.slice(4).forEach(el => el.classList.add('d-none'));
                    break;
            }
        });
    }
}


问:
Blazor - JavaScript Interop - No .NET call dispatcher has been set
I am experimenting with a Blazor WebAssembly app. When my page (i.e. index.html) loads, I want to pass a JavaScript array to the Blazor app when it loads. While trying to call a method from JavaScript, I've run into an error that says:

```<code>Uncaught (in promise) Error: No .NET call dispatcher has been set
</code>```

My code looks like this:

index.html

```<code><body>
    <app>Loading...</app>

    <div id="blazor-error-ui">
        An unhandled error has occurred.
        <a href="" class="reload">Reload</a>
        <a class="dismiss"></a>
    </div>
    <script src="_framework/blazor.webassembly.js"></script>

    <script>
        let items = [
            { name:'Item 1', description:'This is a description of the first item' },
            { name:'Item 2', description:'This is a description of the second item' },
            { name:'Item 3', description:'This is a description of the third item' },
        ];

        try
        {
            DotNet
                .invokeMethodAsync('MyOrg.MyApp.Index', 'LoadItems')
                .then(results => {
                    console.log(results);
                })
            ;
        }
        catch (ex)
        {
            console.log(ex);
        }
    </script>
</body>
</code>```

Index.razor

```<code>@page "/"

@using System.Threading.Tasks;
@using Microsoft.Extensions.Logging;

@inject ILogger<Index> logger;

<p>
    Items loaded: <span>@items.Count</span>
</p>

@code {
    List<object> items = new List<object>();

    [JSInvokable]
    private Task LoadSnippets()
    {
        try
        {
            logger.LogInformation("Loading items...");
            items = new List<object>();
        }
        catch (Exception ex)
        {
            logger.LogError(ex, $"Failed to load items.");
        }
        return Task.CompletedTask;
    }
}
</code>```

The first difference I noticed was that the example shown in the docs relied on a static method. Is this a requirement? If so, that would imply there's not a way to perform logging for example. Logging aside, even if I add static to the LoadItems method, I still get the error listed above. I don't understand why.

In short, I'm trying to create a "headless" Blazor app. I'd like to use the richness of C# to work with the data, I need to pass the results to the UI, which relies on HTML/CSS. Thank you!

答:
// Error I faced

blazor.webassembly.js:1 Uncaught (in promise) Error: No .NET call
dispatcher has been set.    at m (blazor.webassembly.js:1:2655)
at h (blazor.webassembly.js:1:2548)   at Object.e.invokeMethodAsync (blazor.webassembly.js:1:3389)   at
HTMLDocument. (CropHelper.js:73:12)

// Solution

```<code><script>
</code>```

```<code>    window.Blazor.start()
        .then(function () {
            var fileref = document.createElement('script')
            fileref.setAttribute("type", "text/javascript")
            fileref.setAttribute("src", "js/CropHelper.js")
            if (typeof fileref != "undefined")
                document.getElementsByTagName("head")[0].appendChild(fileref)
        })
        .then(results => console.log(results))
        .catch(ex => console.log(ex));

</script>
</code>```

Body:
I am experimenting with a Blazor WebAssembly app. When my page (i.e. index.html) loads, I want to pass a JavaScript array to the Blazor app when it loads. While trying to call a method from JavaScript, I've run into an error that says:

Uncaught (in promise) Error: No .NET call dispatcher has been set

My code looks like this:

index.html

    <app>Loading...</app>

        An unhandled error has occurred.
        Reload

Index.razor

@page "/"

@using System.Threading.Tasks;
@using Microsoft.Extensions.Logging;

@inject ILogger<Index> logger;

    Items loaded: @items.Count

@code {
    List<object> items = new List<object>();

    [JSInvokable]
    private Task LoadSnippets()
    {
        try
        {
            logger.LogInformation("Loading items...");
            items = new List<object>();
        }
        catch (Exception ex)
        {
            logger.LogError(ex, $"Failed to load items.");
        }
        return Task.CompletedTask;
    }
}

The first difference I noticed was that the example shown in the docs relied on a static method. Is this a requirement? If so, that would imply there's not a way to perform logging for example. Logging aside, even if I add static to the LoadItems method, I still get the error listed above. I don't understand why.

In short, I'm trying to create a "headless" Blazor app. I'd like to use the richness of C# to work with the data, I need to pass the results to the UI, which relies on HTML/CSS. Thank you!

Body:
// Error I faced

blazor.webassembly.js:1 Uncaught (in promise) Error: No .NET call
dispatcher has been set.    at m (blazor.webassembly.js:1:2655)
at h (blazor.webassembly.js:1:2548)   at Object.e.invokeMethodAsync (blazor.webassembly.js:1:3389)   at
HTMLDocument. (CropHelper.js:73:12)

// Solution

<script>

    window.Blazor.start()
        .then(function () {
            var fileref = document.createElement('script')
            fileref.setAttribute("type", "text/javascript")
            fileref.setAttribute("src", "js/CropHelper.js")
            if (typeof fileref != "undefined")
                document.getElementsByTagName("head")[0].appendChild(fileref)
        })
        .then(results => console.log(results))
        .catch(ex => console.log(ex));

</script>


问:
I want to get the data from a json file
I want get the data from the json file. I have this list with the keywords.
I tried this:

```<code>def get_information(self, path):
   data = get_data() #loads the hole json file
   keywords = get_keywords(path)
</code>```

Here is my problem because i dont know the lenght and the keywords. So I dont know how to get the information from the path.
kewords could look like this:
['files','important','folder1']

If the keywords are this, then the path should look like this.

```<code>   information = data["storage"]["files"]["important"]["folder1"]
</code>```

This works but i dont know how to do it if the key words are diffrent.

Thanks for your help.

Edit:

```<code>{
  "storage":{
    "files":{
      "important":{
        "folder1":{"age":"25", "gender":"male"}
      }
    }
    "someotherdata":{"age":"5", "gender":"female"}
  }
}
</code>```

答:
You can check if key in the data.keys():

```<code>if some_key in data["storage"]["files"]["important"].keys():
    do_something
</code>```

or use try block:

```<code>try:
    res = data["storage"]["files"]["important"][key]
except KeyError:
    ....
</code>```

or use get() method:

```<code>res = data["storage"]["files"]["important"].get(key)
if not res:
    res = data["storage"]["files"]["important"].get(other_key)
</code>```

To get all values in data["storage"]["files"]["important"] you can try:

```<code>res = {}
for v in data["storage"]["files"]["important"].values():
    res.update(**v)
print(res)
</code>```

Output:

```<code>{'age': '25', 'gender': 'male'}
</code>```

Title: I want to get the data from a json file

Body:
I want get the data from the json file. I have this list with the keywords.
I tried this:

def get_information(self, path):
   data = get_data() #loads the hole json file
   keywords = get_keywords(path)

Here is my problem because i dont know the lenght and the keywords. So I dont know how to get the information from the path.
kewords could look like this:
['files','important','folder1']

If the keywords are this, then the path should look like this.

   information = data["storage"]["files"]["important"]["folder1"]

This works but i dont know how to do it if the key words are diffrent.

Thanks for your help.

Edit:

{
  "storage":{
    "files":{
      "important":{
        "folder1":{"age":"25", "gender":"male"}
      }
    }
    "someotherdata":{"age":"5", "gender":"female"}
  }
}

Body:
You can check if key in the data.keys():

if some_key in data["storage"]["files"]["important"].keys():
    do_something

or use try block:

try:
    res = data["storage"]["files"]["important"][key]
except KeyError:
    ....

or use get() method:

res = data["storage"]["files"]["important"].get(key)
if not res:
    res = data["storage"]["files"]["important"].get(other_key)

To get all values in data["storage"]["files"]["important"] you can try:

res = {}
for v in data["storage"]["files"]["important"].values():
    res.update(**v)
print(res)

Output:

{'age': '25', 'gender': 'male'}


问:
how to view pixelation through camera2D?
I'm trying to create a pixelation shader which I can view through the camera2D node

something like this but instead of black and white I need pixelation

using this answer I got a pixelation shader but how do I view it through the camera?

```<code>shader_type canvas_item;

uniform float size_x = 32.0; // blocks by x direction
uniform float size_y = 32.0; // blocks by y direction

void fragment() {
    COLOR = texture(TEXTURE, vec2(floor(UV.x * size_x) / (size_x - 1.0), floor(UV.y * size_y) / (size_y - 1.0)));
}
</code>```

the structure of my nodes is same as in the above video link:

The end product should maybe look something like this:

答:
ah I found my mistake, I accidentally had use parent material selected

the shader code was the same:

```<code>shader_type canvas_item;

uniform float size_x = 0.008;
uniform float size_y = 0.008;

void fragment() {
    vec2 uv = SCREEN_UV;
    uv -= mod(uv, vec2(size_x, size_y));

    COLOR.rgb = textureLod(SCREEN_TEXTURE, uv, 0.0).rgb;
}
</code>```

Body:
I'm trying to create a pixelation shader which I can view through the camera2D node

something like this but instead of black and white I need pixelation

using this answer I got a pixelation shader but how do I view it through the camera?

shader_type canvas_item;

uniform float size_x = 32.0; // blocks by x direction
uniform float size_y = 32.0; // blocks by y direction

void fragment() {
    COLOR = texture(TEXTURE, vec2(floor(UV.x * size_x) / (size_x - 1.0), floor(UV.y * size_y) / (size_y - 1.0)));
}

the structure of my nodes is same as in the above video link:

The end product should maybe look something like this:

Body:
ah I found my mistake, I accidentally had use parent material selected

the shader code was the same:

shader_type canvas_item;

uniform float size_x = 0.008;
uniform float size_y = 0.008;

void fragment() {
    vec2 uv = SCREEN_UV;
    uv -= mod(uv, vec2(size_x, size_y));

    COLOR.rgb = textureLod(SCREEN_TEXTURE, uv, 0.0).rgb;
}


问:
How to pass a dynamic column name in a pipe in custom function in R
I've created a dynamic column name w/ dplyr::mutate() based on this thread Use dynamic variable names in `dplyr` and now I want to sort the new column.... but I'm not correctly passing the column name</p>
```<code>library(glue)
library(dplyr)

# data
set.seed(123)
df <- data.frame(distance = sample(1:100, size = 10))

# custom function
multiply_function <- function(df, metric, multiplier){

  df %>%
    mutate(., "{{metric}}_x{{multiplier}}" := {{metric}} * multiplier) %>%
    arrange(desc("{{metric}}_x{{multiplier}}")) # <--- this is not working
}

df %>%
  multiply_function(., metric = distance, multiplier = 3)

   distance distance_x3
1        31          93
2        79         237
3        51         153
4        14          42
5        67         201
6        42         126
7        50         150
8        43         129
9        97         291
10       25          75
</code>```

答:
I'm not sure this arranging step is best placed within a function if that function is part of a pipe itself. Problems may emerge if trying to make several variables. For one new variable:</p>
```<code>multiply_function <- function(df, metric, multiplier){
  df %>%
    mutate("{{metric}}_x{{multiplier}}" := {{metric}} * multiplier) %>%
    arrange(desc(!!rlang::sym(setdiff(names(.), names(df)))))
}
</code>```

Body:
I've created a dynamic column name w/ dplyr::mutate() based on this thread Use dynamic variable names in `dplyr` and now I want to sort the new column.... but I'm not correctly passing the column name

library(glue)
library(dplyr)

# data
set.seed(123)
df <- data.frame(distance = sample(1:100, size = 10))

# custom function
multiply_function <- function(df, metric, multiplier){

  df %>%
    mutate(., "{{metric}}_x{{multiplier}}" := {{metric}} * multiplier) %>%
    arrange(desc("{{metric}}_x{{multiplier}}")) # <--- this is not working
}

df %>%
  multiply_function(., metric = distance, multiplier = 3)

   distance distance_x3
1        31          93
2        79         237
3        51         153
4        14          42
5        67         201
6        42         126
7        50         150
8        43         129
9        97         291
10       25          75

Body:
I'm not sure this arranging step is best placed within a function if that function is part of a pipe itself. Problems may emerge if trying to make several variables. For one new variable:

multiply_function <- function(df, metric, multiplier){
  df %>%
    mutate("{{metric}}_x{{multiplier}}" := {{metric}} * multiplier) %>%
    arrange(desc(!!rlang::sym(setdiff(names(.), names(df)))))
}


问:
How to change the color of a icon among multiple icons one at a time using click event in angular
I have an angular application In that I have added 6 icons .My requirement is when I click on any button the particular icon color should changed from gray red color, and when I click on other icon the other icon changed to red color and previous color changed button should changed to gray color.

and my angular code is:

.component.html

```<code><div class="container">
<span class="icon-number"></span><i class="smiley  icon-face-1"></i>
        <span class="icon-number"></span><i class="smiley  icon-face-2"></i>
        <span class="icon-number"></span><i class="smiley  icon-face-3"></i>
        <span class="icon-number"></span><i class="smiley  icon-4"></i>
        <span class="icon-number"></span><i class="smiley icon-face-5"></i>
        <span class="icon-number"></span><i class="smiley icon-face-6"></i>
</div>

</code>```

So Can any one help me how to change the color of particular icon using click event in angular.

答:
```<code><div class="container">
    <button *ngFor="let btn of btnArr" type="button" class="buttonstyle"
        [style.background-color]="selectedButton === btn ? '#FF0000' : 'grey'" (click)="selectedButton = btn">
        {{btn}}
    </button>
</div>

<div class="container">
    <i (click)="selectedIcon = icon.id" class="smiley" [ngClass]="icon.class"
        [style.color]="selectedIcon === icon.id ? '#FF0000' : '#000000'" *ngFor="let icon of iconsArr"></i>
</div>
</code>```

In component ts file

```<code>btnArr = ["BUTTON-1", "BUTTON-2", "BUTTON-3", "BUTTON-4", "BUTTON-5", "BUTTON-6"];
selectedButton = "";

iconsArr = [
        { id: 1, class: "icon-face-1" },
        { id: 2, class: "icon-face-2" },
        { id: 3, class: "icon-face-3" },
        { id: 4, class: "icon-face-4" },
        { id: 5, class: "icon-face-5" },
        { id: 6, class: "icon-face-6" }
    ];
    selectedIcon = 0;
</code>```

Body:
I have an angular application In that I have added 6 icons .My requirement is when I click on any button the particular icon color should changed from gray red color, and when I click on other icon the other icon changed to red color and previous color changed button should changed to gray color.

and my angular code is:

.component.html

So Can any one help me how to change the color of particular icon using click event in angular.

Body:
<div class="container">
    <button *ngFor="let btn of btnArr" type="button" class="buttonstyle"
        [style.background-color]="selectedButton === btn ? '#FF0000' : 'grey'" (click)="selectedButton = btn">
        {{btn}}
    </button>
</div>

<div class="container">
    <i (click)="selectedIcon = icon.id" class="smiley" [ngClass]="icon.class"
        [style.color]="selectedIcon === icon.id ? '#FF0000' : '#000000'" *ngFor="let icon of iconsArr"></i>
</div>

In component ts file

btnArr = ["BUTTON-1", "BUTTON-2", "BUTTON-3", "BUTTON-4", "BUTTON-5", "BUTTON-6"];
selectedButton = "";

iconsArr = [
        { id: 1, class: "icon-face-1" },
        { id: 2, class: "icon-face-2" },
        { id: 3, class: "icon-face-3" },
        { id: 4, class: "icon-face-4" },
        { id: 5, class: "icon-face-5" },
        { id: 6, class: "icon-face-6" }
    ];
    selectedIcon = 0;


问:
Javascript error - document.getElementsById is not a function
Since I am calling this code in loop. But following code is giving me error as document.getElementsById  is not a function. What should I do how can I call doc.getbyid in loop.

```<code>for (var z=1; z < i; z++){
       var textbox = document.getElementsById("a"+z).value;
       var textbox2 = document.getElementsById("b").value;
       var textbox3 = document.getElementsById("c").value;
       alert(textbox);
       alert(textbox2);
       alert(textbox3);
}
</code>```

答: document.getElementsById() is not the function but document.getElementById() is. If you want to get all of the tag names, you can use document.getElementsByTagName() and if you want to get specific class elements you can use document.getElementsByClassName().

ContentLicense: CC BY-SA 3.0

Body:
Since I am calling this code in loop. But following code is giving me error as document.getElementsById  is not a function. What should I do how can I call doc.getbyid in loop.

for (var z=1; z < i; z++){
       var textbox = document.getElementsById("a"+z).value;
       var textbox2 = document.getElementsById("b").value;
       var textbox3 = document.getElementsById("c").value;
       alert(textbox);
       alert(textbox2);
       alert(textbox3);
}


问:
Regex Conditional validation
I have a input field, and I want to create a regex that only receive input value from 0.00 to 100.00(include both). I have created a regex check:

```<code>^1?\d{0,2}(\.\d{1,2})?$
</code>```

But with this one, it not only accept values from 0.00 to 100.00 but also accept the input from 100.01 to 199.99.

How can I set a condition that if there are three digital before the dot, it can be only 100 and the decimals part is 00 or 0 only if having decimals?

So 100.00, 100.0 or 100 are the only accept for the values over 99.99 and the input between 100.01 to 199.99 is not pass.

Here are some passed input:

```<code>100
100.00
100.0
3
0
0.00
5.2
8.21
37.23
</code>```

Here are some not passed:

```<code>40.323
100.50
101.50
199.99
40.
100.
</code>```

答:
You can match 0 - 99 with 1 or 2 optional decimals or 100 with optional .0 or .00

```<code>^(?:\d\d?(?:\.\d\d?)?|100(?:\.00?)?)$
</code>```

The pattern in parts:

^ Start of string

(?: Non capture group

\d\d? Match 1-2 digits

(?:\.\d\d?)? Optionally match . and 1-2 digits

| or

100(?:\.00?)? Match 100 or 100.0 or 100.00

) Close non capture group

$ End of string

Regex demo

Title: Regex Conditional validation

Body:
I have a input field, and I want to create a regex that only receive input value from 0.00 to 100.00(include both). I have created a regex check:

^1?\d{0,2}(\.\d{1,2})?$

But with this one, it not only accept values from 0.00 to 100.00 but also accept the input from 100.01 to 199.99.

How can I set a condition that if there are three digital before the dot, it can be only 100 and the decimals part is 00 or 0 only if having decimals?

So 100.00, 100.0 or 100 are the only accept for the values over 99.99 and the input between 100.01 to 199.99 is not pass.

Here are some passed input:

100
100.00
100.0
3
0
0.00
5.2
8.21
37.23

Here are some not passed:

40.323
100.50
101.50
199.99
40.
100.

Body:
You can match 0 - 99 with 1 or 2 optional decimals or 100 with optional .0 or .00

^(?:\d\d?(?:\.\d\d?)?|100(?:\.00?)?)$

The pattern in parts:

^ Start of string

(?: Non capture group

\d\d? Match 1-2 digits

(?:\.\d\d?)? Optionally match . and 1-2 digits

| or

100(?:\.00?)? Match 100 or 100.0 or 100.00

) Close non capture group

$ End of string

Regex demo


问:
Import error: DLL load failed in Jupyter notebook but working in .py file
I installed BreakoutDetection the module in Anaconda environment. When I tried to import the module using import breakout_detection in jupyter notebook, I get the below error

```<code>---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-18-96c0fdb15b96> in <module>()
----> 1 import breakout_detection

C:\Users\sgadiyar\AppData\Local\Continuum\Anaconda2\lib\site-packages\breakout_detection.py in <module>()
     15         except ImportError:
     16             return importlib.import_module('_breakout_detection')
---> 17     _breakout_detection = swig_import_helper()
     18     del swig_import_helper
     19 elif _swig_python_version_info >= (2, 6, 0):

C:\Users\sgadiyar\AppData\Local\Continuum\Anaconda2\lib\site-packages\breakout_detection.py in swig_import_helper()
     14             return importlib.import_module(mname)
     15         except ImportError:
---> 16             return importlib.import_module('_breakout_detection')
     17     _breakout_detection = swig_import_helper()
     18     del swig_import_helper

C:\Users\sgadiyar\AppData\Local\Continuum\Anaconda2\lib\importlib\__init__.pyc in import_module(name, package)
     35             level += 1
     36         name = _resolve_name(name[level:], package, level)
---> 37     __import__(name)
     38     return sys.modules[name]

ImportError: DLL load failed: The specified procedure could not be found.
</code>```

I could import the same module in python shell

I looked at the system paths (print sys.path) and  in both python shell and jupyter notebook. They both are the same. Executable path (print sys.executable) is also the same for the both.

Can someone help me out on the steps I should take to resolve this issue? Thanks!

答:
In whichever virtual environment its breaking out, just activate the environment using:

conda activate <env-name>

and then re-install the notebook using:

pip install notebook

It was working fine for me in both Base as well as virtual environment until I upgraded from windows 10 to windows 11.

Body:
I installed BreakoutDetection the module in Anaconda environment. When I tried to import the module using import breakout_detection in jupyter notebook, I get the below error

---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-18-96c0fdb15b96> in <module>()
----> 1 import breakout_detection

C:\Users\sgadiyar\AppData\Local\Continuum\Anaconda2\lib\site-packages\breakout_detection.py in <module>()
     15         except ImportError:
     16             return importlib.import_module('_breakout_detection')
---> 17     _breakout_detection = swig_import_helper()
     18     del swig_import_helper
     19 elif _swig_python_version_info >= (2, 6, 0):

C:\Users\sgadiyar\AppData\Local\Continuum\Anaconda2\lib\site-packages\breakout_detection.py in swig_import_helper()
     14             return importlib.import_module(mname)
     15         except ImportError:
---> 16             return importlib.import_module('_breakout_detection')
     17     _breakout_detection = swig_import_helper()
     18     del swig_import_helper

C:\Users\sgadiyar\AppData\Local\Continuum\Anaconda2\lib\importlib\__init__.pyc in import_module(name, package)
     35             level += 1
     36         name = _resolve_name(name[level:], package, level)
---> 37     __import__(name)
     38     return sys.modules[name]

ImportError: DLL load failed: The specified procedure could not be found.

I could import the same module in python shell

I looked at the system paths (print sys.path) and  in both python shell and jupyter notebook. They both are the same. Executable path (print sys.executable) is also the same for the both.

Can someone help me out on the steps I should take to resolve this issue? Thanks!


问:
SQL - Selecting parent/top nodes and children in a data hierarchy/tree
I'm dealing with a data structure that I haven't encountered before.  The table is a tree hierarchy and looks something like this:

```<code>CREATE TABLE Tree (
    TreeID INT, -- Primary key id
    TreeLevel INT, -- Level in the tree
    TreeDown INT, -- TreeID of first node at the next lower level
    TreeRight INT -- TreeID of the next node at the same level with 0 being the end
)
</code>```

I then have a list of items that are linked to various nodes in the hierarchy by the TreeID.  E.g.:

```<code>CREATE TABLE Items (
    ItemID INT,
    TreeID INT, -- Node in the tree hierarchy
    Value INT
)
</code>```

I'd like to do a select and group by the top level in the tree so with all the children included.  For example:

```<code>SELECT Tree.TreeID, SUM(Items.Value) FROM Items
JOIN Tree ON Tree.TreeID = Items.TreeID AND Tree.TreeLevel = 0
GROUP BY Tree.TreeID
</code>```

Of course, this wouldn't actually work, just giving this as an example.  In reality, this would only include the items explicitly assigned to tree nodes that happen to have the level 0, but not their children.  How do I include their children?

I'm using SQL Server 2008 if it matters, but an agnostic solution would be great.

答:
Take a look at this related question. You're going to need to create a recursive-cte and this has a similar problem/solution.

CTE to traverse back up a hierarchy?

Body:
I'm dealing with a data structure that I haven't encountered before.  The table is a tree hierarchy and looks something like this:

CREATE TABLE Tree (
    TreeID INT, -- Primary key id
    TreeLevel INT, -- Level in the tree
    TreeDown INT, -- TreeID of first node at the next lower level
    TreeRight INT -- TreeID of the next node at the same level with 0 being the end
)

I then have a list of items that are linked to various nodes in the hierarchy by the TreeID.  E.g.:

CREATE TABLE Items (
    ItemID INT,
    TreeID INT, -- Node in the tree hierarchy
    Value INT
)

I'd like to do a select and group by the top level in the tree so with all the children included.  For example:

SELECT Tree.TreeID, SUM(Items.Value) FROM Items
JOIN Tree ON Tree.TreeID = Items.TreeID AND Tree.TreeLevel = 0
GROUP BY Tree.TreeID

Of course, this wouldn't actually work, just giving this as an example.  In reality, this would only include the items explicitly assigned to tree nodes that happen to have the level 0, but not their children.  How do I include their children?

I'm using SQL Server 2008 if it matters, but an agnostic solution would be great.


问:
How to get numbers after some particular word using regex in c#?
Below is my sample text

```<code>Pick Ticket 81091 Reference 109437
Issuing Date/Time  27/Jan/2022 10:19:10AM Status 35-Pick in Progress
</code>```

I need to get the 6 digits number after this word "Reference". The text will be always like this "Reference ******"

答:
You might simply use

```<code>Reference\s+(\d+)$
</code>```

and use the first capturing group (switch on the multiline modifier).

See a demo on regex101.com.

In C#:

```<code>using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"Reference\s+(\d+)$";
        string input = @"Pick Ticket 81091 Reference 109437
Issuing Date/Time  27/Jan/2022 10:19:10AM Status 35-Pick in Progress
";
        RegexOptions options = RegexOptions.Multiline;

        foreach (Match m in Regex.Matches(input, pattern, options))
        {
            Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
        }
    }
}
</code>```

Body:
Below is my sample text

Pick Ticket 81091 Reference 109437
Issuing Date/Time  27/Jan/2022 10:19:10AM Status 35-Pick in Progress

I need to get the 6 digits number after this word "Reference". The text will be always like this "Reference ******"

Body:
You might simply use

Reference\s+(\d+)$

and use the first capturing group (switch on the multiline modifier).

See a demo on regex101.com.

In C#:

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"Reference\s+(\d+)$";
        string input = @"Pick Ticket 81091 Reference 109437
Issuing Date/Time  27/Jan/2022 10:19:10AM Status 35-Pick in Progress
";
        RegexOptions options = RegexOptions.Multiline;

        foreach (Match m in Regex.Matches(input, pattern, options))
        {
            Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
        }
    }
}


问:
Is there a way to remove the N/A boxplots when you select specific rows to visualize?
So I made a boxplot using ggplot with the code below

```<code>ggplot(df, aes(x = factor(Letters, level = c("A", "B", "C", "D")), y = Expression)) + geom_boxplot() +
  scale_x_discrete(guide = guide_axis(n.dodge=3)) + xlab("Letters") + ylab("Expression")

</code>```

The plot that is generated is good except that all the Letters in the dataframe that haven't been called "E-Z" also are shown in the plot under the category NA. But I don't want the NA category to be shown. You may be thinking why don't I just delete those rows that I don't want visualize. The issue is I'm making 6 of these plots with different rows and I was wondering if there's a way of doing it that doesn't involving making 6 dataframes and removing the rows I don't want each and everytime. First 6 rows of the dataframe are shown below

Letter
Expression

A
10

B
20

C
15

D
12

E
16

F
18

答:
You can pipe your df into a filter() and then pipe it to ggplot. This will not change the content of your original dataframe.

```<code>library(tidyverse)

df %>% filter(Letters %in% c("A", "B", "C", "D")) %>%
  ggplot(., aes(x = Letters, y = Expression)) +
  geom_boxplot() +
  scale_x_discrete(guide = guide_axis(n.dodge=3)) +
  xlab("Letters") +
  ylab("Expression")
</code>```

Body:
So I made a boxplot using ggplot with the code below

ggplot(df, aes(x = factor(Letters, level = c("A", "B", "C", "D")), y = Expression)) + geom_boxplot() +
  scale_x_discrete(guide = guide_axis(n.dodge=3)) + xlab("Letters") + ylab("Expression")

The plot that is generated is good except that all the Letters in the dataframe that haven't been called "E-Z" also are shown in the plot under the category NA. But I don't want the NA category to be shown. You may be thinking why don't I just delete those rows that I don't want visualize. The issue is I'm making 6 of these plots with different rows and I was wondering if there's a way of doing it that doesn't involving making 6 dataframes and removing the rows I don't want each and everytime. First 6 rows of the dataframe are shown below

Letter
Expression

A
10

B
20

C
15

D
12

E
16

F
18

Body:
You can pipe your df into a filter() and then pipe it to ggplot. This will not change the content of your original dataframe.

library(tidyverse)

df %>% filter(Letters %in% c("A", "B", "C", "D")) %>%
  ggplot(., aes(x = Letters, y = Expression)) +
  geom_boxplot() +
  scale_x_discrete(guide = guide_axis(n.dodge=3)) +
  xlab("Letters") +
  ylab("Expression")


问:
How to make ref arrays work in Vue 3 composition API when passing them to child components?
I have the following todo app with these two components: App and Todo

App.vue

<template>

      <Todo :todo="todo" :state="state" />

</template>

```
<p><strong>Todo.vue</strong></p>
<pre class="lang-js prettyprint-override"><code><template>
  <div class="todo">{{ todo.text }}<button @click="deleteTodo">x</button></div>
</template>

<script>
export default {
  props: ['todo', 'state'],
  setup({ todo, state }) {
    const deleteTodo = () => {
      state.todos = state.todos.filter(t => t != todo);
    };

    return {
      deleteTodo
    };
  }
};
</script>
</code>```

The deleteTodo function works fine in the Todo.vue component, however, I would like to know if it's possible not to pass a state object but rather use a ref() like so and pass the  todos...

So in App.vue

//...
    let todos = ref({[
        { text: 'Learn about Vue', isCompleted: false },
        { text: 'Meet friend for lunch', isCompleted: false },
        { text: 'Build really cool todo app', isCompleted: false }
      ]);
//...
```
<p>Instead of:</p>
<pre class="lang-js prettyprint-override"><code>//...
   let state = reactive({
      todos: [
        { text: 'Learn about Vue', isCompleted: false },
        { text: 'Meet friend for lunch', isCompleted: false },
        { text: 'Build really cool todo app', isCompleted: false }
      ]
    });
//...
</code>```

However, when I try to do this... the child is unable to filter the deleted todo and re-assign to the todos variable. This doesn't work.

Any ideas how I can make it work with ref?

答:
you are using ref in wrong way. ref means to be used with reactive primitive values like numbers and string etc. while reactive means to be used for reactive objects.

you can use arrays as well with ref. but you should not wrap arrays within an object to use inside ref

The correct statement would be

let todos = ref([
        { text: 'Learn about Vue', isCompleted: false },
        { text: 'Meet friend for lunch', isCompleted: false },
        { text: 'Build really cool todo app', isCompleted: false }
    ])
```

then you can filter as you were doing it. only now you have to refer arrays like todos.value. kind of you already doing state variable.

https://v3.vuejs.org/guide/reactivity-fundamentals.html#declaring-reactive-state

Body:
I have the following todo app with these two components: App and Todo

App.vue

<template>

      <Todo :todo="todo" :state="state" />

</template>

Todo.vue

<template>

{{ todo.text }}<button @click="deleteTodo">x</button>

</template>

The deleteTodo function works fine in the Todo.vue component, however, I would like to know if it's possible not to pass a state object but rather use a ref() like so and pass the  todos...

So in App.vue

//...
    let todos = ref({[
        { text: 'Learn about Vue', isCompleted: false },
        { text: 'Meet friend for lunch', isCompleted: false },
        { text: 'Build really cool todo app', isCompleted: false }
      ]);
//...

Instead of:

//...
   let state = reactive({
      todos: [
        { text: 'Learn about Vue', isCompleted: false },
        { text: 'Meet friend for lunch', isCompleted: false },
        { text: 'Build really cool todo app', isCompleted: false }
      ]
    });
//...

However, when I try to do this... the child is unable to filter the deleted todo and re-assign to the todos variable. This doesn't work.

Any ideas how I can make it work with ref?

Body:
you are using ref in wrong way. ref means to be used with reactive primitive values like numbers and string etc. while reactive means to be used for reactive objects.

you can use arrays as well with ref. but you should not wrap arrays within an object to use inside ref

The correct statement would be

let todos = ref([
        { text: 'Learn about Vue', isCompleted: false },
        { text: 'Meet friend for lunch', isCompleted: false },
        { text: 'Build really cool todo app', isCompleted: false }
    ])

then you can filter as you were doing it. only now you have to refer arrays like todos.value. kind of you already doing state variable.

https://v3.vuejs.org/guide/reactivity-fundamentals.html#declaring-reactive-state


问:
Android Studio - Where is 'anim' folder?

The picture above is my default project structure of Android Studio.

I want to add my own animation xml file to anim folder and use it.
So I try to create a folder called 'anim' but it says that folder already exists
But I can not see ... how can I 'see' and 'access' anim folder?

答:
right click on res file

click on New the click on Android Resource Directory

then on Resource Type select anim

click Ok


问:
How to combine two tables into one using my sql statement
i'm new in Database, i want to get a result from both sql table.
Here is the example

Table 1

Item Code
Price

A001
5 Dollar

A002
6 Dollar

Table 2 - Item Code Information

Item Code
Item Description

A001
Fish

A002
Chicken

And my question i want to get result with table 1 combine with 2 with item code, item description and price

Item Code
Item Description
Price

A001
Fish
5 Dollar

A002
Chicken
6 Dollar

Does anyone know how to do the SQL statement? Please help Thank you

答:
Use this codes:</p>
```<code>SELECT T1.ItemCode,ItemDescription, Price
FROM TABLE1 T1 INNER JOIN TABLE2 T2 ON T1.ItemCode = T2.ItemCode
</code>```

Body:
Use this codes:

SELECT T1.ItemCode,ItemDescription, Price
FROM TABLE1 T1 INNER JOIN TABLE2 T2 ON T1.ItemCode = T2.ItemCode


问:
Null Pointer Exception for read properties file in Idea
after define a property file in idea 10.5 when i try to use it,compiler show me Null Pointer Exception!I try anything that i think fix it among change property file path,...
here is the code that i write:
thanks.
beginner programmer!!!</p>

```<code>public class MainDlg{
    Properties properties=new Properties();
    public MainDlg() {
        try {
            InputStream reader=MainDlg.class.getResourceAsStream("propFile");
            properties.load(reader);
</code>```

答: getResourceAsStream is case sensitive. Make sure that your file-name matches exactly.

Body:
after define a property file in idea 10.5 when i try to use it,compiler show me Null Pointer Exception!I try anything that i think fix it among change property file path,...
here is the code that i write:
thanks.
beginner programmer!!!

public class MainDlg{
    Properties properties=new Properties();
    public MainDlg() {
        try {
            InputStream reader=MainDlg.class.getResourceAsStream("propFile");
            properties.load(reader);


问:
Is there a simple way to convert a CSV with 0-indexed paths as keys to JSON with Miller?
Consider the following CSV:

```<code>email/1,email/2
abc@xyz.org,bob@pass.com
</code>```

You can easily convert it to JSON (taking into account the paths defined by the keys) with Miller:

mlr --icsv --ojson --jflatsep '/' cat file.csv
```
<pre class="lang-json prettyprint-override"><code>[ { "email": ["abc@xyz.org", "bob@pass.com"] } ]
</code>```

Now, if the paths are 0-indexed in the CSV (which is surely more common):

```<code>email/0,email/1
abc@xyz.org,bob@pass.com
</code>```

Then, without prior knowledge of the fields names, it seams that you'll have to rewrite the whole conversion:

edit: replaced the hard-coded / with FLATSEP builtin variable:

mlr --icsv --flatsep '/' put -q '
    begin { @labels = []; print "[" }

    # translate the original CSV header from 0-indexed to 1-indexed
    NR == 1 {
        i = 1;
        for (k in $*) {
            @labels[i] = joinv( apply( splita(k,FLATSEP), func(e) {
                return typeof(e) == "int" ? e+1 : e
            }), FLATSEP );
            i += 1;
        }
    }

    NR > 1 { print @object, "," }

    # create an object from the translated labels and the row values
    o = {};
    i = 1;
    for (k,v in $*) {
        o[@labels[i]] = v;
        i += 1;
    }
    @object = arrayify( unflatten(o,FLATSEP) );

    end { if (NR > 0) { print @object } print "]" }
' file.csv
```
<p>I would like to know if I'm missing something obvious, like a command line option or a way to rename the fields with the <code>put</code> verb, or maybe something else? You're also welcome to give your insights about the previous code, as I'm not really confident in my Miller's programming skills.</p>
<hr />
<p><strong>Update:</strong></p>
<p>With @aborruso approach of pre-processing the CSV header, this could be reduced to:<br>
<sup><strong>note:</strong> I didn't keep the <code>regextract</code> part because it means knowing the CSV header in advance.</sup></p>
<pre class="lang-sh prettyprint-override"><code>mlr --csv -N --flatsep '/' put '
    NR == 1 {
        for (i,k in $*) {
            $[i] = joinv( apply( splita(k,FLATSEP), func(e) {
                return typeof(e) == "int" ? e+1 : e
            }), FLATSEP );
        }
    }
' file.csv |
mlr --icsv --flatsep '/' --ojson cat
</code>```

Even if there are workarounds like using the rename verb (when you know the header in advance) or pre-processing the CSV header, I still hope that Miller's author could add an extra command-line option that would deal with this kind of 0‑indexed external data; adding a DSL function like arrayify0 (and flatten0) could also prove useful in some cases.

答:
I would like to know if I'm missing something obvious, like a command line option or a way to rename the fields with put verb, or maybe something else?

Starting from this

```<code>email/0,email/1
abc@xyz.org,bob@pass.com
</code>```

you can use implicit CSV header and run

```<code>mlr --csv -N put 'if (NR == 1) {for (k in $*) {$[k] = "email/".string(int(regextract($[k],"[0-9]+"))+1)}}' input.csv
</code>```

to have

```<code>email/1,email/2
abc@xyz.org,bob@pass.com
</code>```

Body:
Consider the following CSV:

email/1,email/2
abc@xyz.org,bob@pass.com

You can easily convert it to JSON (taking into account the paths defined by the keys) with Miller:

mlr --icsv --ojson --jflatsep '/' cat file.csv

[ { "email": ["abc@xyz.org", "bob@pass.com"] } ]

Now, if the paths are 0-indexed in the CSV (which is surely more common):

email/0,email/1
abc@xyz.org,bob@pass.com

Then, without prior knowledge of the fields names, it seams that you'll have to rewrite the whole conversion:

edit: replaced the hard-coded / with FLATSEP builtin variable:

mlr --icsv --flatsep '/' put -q '
    begin { @labels = []; print "[" }

    # translate the original CSV header from 0-indexed to 1-indexed
    NR == 1 {
        i = 1;
        for (k in $*) {
            @labels[i] = joinv( apply( splita(k,FLATSEP), func(e) {
                return typeof(e) == "int" ? e+1 : e
            }), FLATSEP );
            i += 1;
        }
    }

    NR > 1 { print @object, "," }

    # create an object from the translated labels and the row values
    o = {};
    i = 1;
    for (k,v in $*) {
        o[@labels[i]] = v;
        i += 1;
    }
    @object = arrayify( unflatten(o,FLATSEP) );

    end { if (NR > 0) { print @object } print "]" }
' file.csv

I would like to know if I'm missing something obvious, like a command line option or a way to rename the fields with the put verb, or maybe something else? You're also welcome to give your insights about the previous code, as I'm not really confident in my Miller's programming skills.

Update:

With @aborruso approach of pre-processing the CSV header, this could be reduced to:

note: I didn't keep the regextract part because it means knowing the CSV header in advance.

mlr --csv -N --flatsep '/' put '
    NR == 1 {
        for (i,k in $*) {
            $[i] = joinv( apply( splita(k,FLATSEP), func(e) {
                return typeof(e) == "int" ? e+1 : e
            }), FLATSEP );
        }
    }
' file.csv |
mlr --icsv --flatsep '/' --ojson cat

Even if there are workarounds like using the rename verb (when you know the header in advance) or pre-processing the CSV header, I still hope that Miller's author could add an extra command-line option that would deal with this kind of 0‑indexed external data; adding a DSL function like arrayify0 (and flatten0) could also prove useful in some cases.

Body:
I would like to know if I'm missing something obvious, like a command line option or a way to rename the fields with put verb, or maybe something else?

Starting from this

email/0,email/1
abc@xyz.org,bob@pass.com

you can use implicit CSV header and run

mlr --csv -N put 'if (NR == 1) {for (k in $*) {$[k] = "email/".string(int(regextract($[k],"[0-9]+"))+1)}}' input.csv

to have

email/1,email/2
abc@xyz.org,bob@pass.com


问:
Save or Retrieve the data in Rstudio
Sir,i am a student, learning R,I have a question about how to store data in R, or how to retrieve data that has been erased.</p>

答:
Sir,

Using RStudio is not much different than using, say, Word or Notepad, but with some differences.
First the similarities:

If you do not save your Rscript or data, it might not be available after you restart RStudio or if you overwrite/erase your data.

The advantage of using R and Rstudio is that you can script how you load and manipulate your data, hence recreate the data. If you use a script and do not rely only on the console (interactive) part.

For the differences, Rstudio can be set to save your current workspace. This is were all data and variables loaded reside. To change the settings, go to "Tools" --> "Global options" and you should see the options as depicted below.

However, if you erase your data by overwriting with other values or using the command unset, the data is lost. Your only recourse is to retrace how it was loaded/modified, using either your script or going through the "history".

For saving data, see e.g. http://www.sthda.com/english/wiki/saving-data-into-r-data-format-rds-and-rdata. Note the difference between save and saveRDS where the former saves data with their variable names, whereas saveRDS saves the data without and must be loaded into a variable.

Title: Save or Retrieve the data in Rstudio


问:
Why does changing state (useState) break my p5.js code? (React + p5.js application)
I created an Audio visualizer using p5.js and React and i need some help.

I am trying to change the state of my button input text from Play to Stop when the song starts playing & from Stop back to Play when the user decides to stop the song at that moment.

I am using react-p5 library and everything works great until i setState when a user clicks the play button. Since that causes a re render it breaks my canvas.

Is there a way to only re-render the button element? I am not too sure how i would go about changing the inner text of my button without a state change?

```<code>import React, { useState } from 'react';
import Sketch from 'react-p5';
import 'p5/lib/addons/p5.sound';
import Beat from '../../instrumental.mp3';

const App = () => {

  let width = 900;
  let height = 600;
  let song;
  let fft;

  const [flag, setFlag] = useState(true);

  const preload = (p) => {
    p.soundFormats('mp3');
    song = p.loadSound(Beat);
  }

  const setup = (p, canvasParentRef) => {
    // react-p5 conveniently initializes window.p5 thats why all the other p5's
    // have been changed to p in order to create an FFT object
    fft = new p5.FFT();
    // console.log(p.point)
    // use parent to render the canvas in this ref
        // without it p5 will render the canvas outside of this component
    const canvas = p.createCanvas(width, height).parent(canvasParentRef);
  }

  const playStop = () => {
    if (song.isPlaying()) {
      song.pause();
      setFlag(true);
      //p.noLoop();
    } else {
      song.play();
      setFlag(false);
      //p.loop();
    }
  }

  const draw = p => {
    p.background(0);
    // by default the stroke color is black
    // we need to change this in order to see the wave
    p.stroke(255, 204, 0);

    // no fill in between waves
    p.noFill();
    // returns an array with 1024 elements
    let wave = fft.waveform();

    p.beginShape();
    // By looping through the waveform data, we are able
    // to draw the waveform across the canvas
    for (let i = 0; i < width; i++) {
      // create an index that maps the for loop variable
      // to the index of the wave we want
      // value must be integer thats we we use floor
      let index = p.floor(p.map(i, 0, width, 0, wave.length));

      let x = i;
      let y = wave[index] * 100 + height / 2;
      p.vertex(x, y);
    }
    p.endShape();
  }

  return (
    <div className='outerbox'>
      <h1>Audio Visualizer</h1>
      <Sketch preload={preload} setup={setup} draw={draw}/>
      {flag ? <button onClick={playStop}>Play</button> : <button onClick={playStop}>Stop</button>}
    </div>
  );
}

export default App;
</code>```

The sad thing is there aren't many resources available that includes react + p5.js

If anyone would like to take the time and clone this repository down in order to see what the problem might be, i would very much appreciate that.

Repo link: https://github.com/imperium11/audio-visualizer

npm i

npm run dev-build

npm start

答:
The issue here is that each time you update state in a functional component the function gets called again. As a result each time state changes you re-declare your preload/setup/draw, because of the way react-p5 work, the running sketch will start using your updated draw function. However, the updated draw function expects fft to be defined, but the version of the fft variable referenced by the new draw function is undefined.

In order to fix this you can make any local variables that you sketch uses into state variables. In this example I've packed all the locals into one object:

const { useState } = React;
const Sketch = reactP5;

let v = 0;

const App = () => {
  const width = 500;
  const height = 300;

  const [flag, setFlag] = useState(true);
  const [locals, setLocals] = useState({});

  const preload = (p) => {
    p.soundFormats('mp3');
    setLocals({
      song: p.loadSound('https://www.paulwheeler.us/files/Ipu.wav')
    });
  }

  const setup = (p, canvasParentRef) => {
    // react-p5 conveniently initializes window.p5 thats why all the other p5's
    // have been changed to p in order to create an FFT object
    setLocals({
      ...locals,
      fft: new p5.FFT()
    });
    // console.log(p.point)
    // use parent to render the canvas in this ref
        // without it p5 will render the canvas outside of this component
    p.createCanvas(width, height).parent(canvasParentRef);
  };

  setup.version = v++;

  const playStop = () => {
    if (locals.song.isPlaying()) {
      locals.song.pause();
      setFlag(true);
      //p.noLoop();
    } else {
      locals.song.play();
      setFlag(false);
      //p.loop();
    }
  }

  const draw = p => {
    p.background(0);
    p.text(setup.version.toString(), 20, 20);
    // by default the stroke color is black
    // we need to change this in order to see the wave
    p.stroke(255, 204, 0);

    // no fill in between waves
    p.noFill();
    // returns an array with 1024 elements
    let wave = locals.fft.waveform();

    p.beginShape();
    // By looping through the waveform data, we are able
    // to draw the waveform across the canvas
    for (let i = 0; i < width; i++) {
      // create an index that maps the for loop variable
      // to the index of the wave we want
      // value must be integer thats we we use floor
      let index = p.floor(p.map(i, 0, width, 0, wave.length));

      let x = i;
      let y = wave[index] * 100 + height / 2;
      p.vertex(x, y);
    }
    p.endShape();
  }

  return (

      Audio Visualizer
      {flag ? <button onClick={playStop}>Play</button> : <button onClick={playStop}>Stop</button>}
      <Sketch preload={preload} setup={setup} draw={draw}/>

  );
}

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/react-p5@1.3.27/build/index.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.1/addons/p5.sound.min.js"></script>

<div id="root"></div></code>```

Another way to go would be to actually make the functions that use those local variables into state variables. That way they would only be declared the first time your component function is called for each instance of it. This may be a bit of a hack, but it has the advantage of working for rapidly updating local variables (if you were changing local variables in your draw() function, my understanding is that you would not want to make those into state variables, since high frequency state updates may impact performance.

const { useState } = React;
const Sketch = reactP5;

const App = () => {
  const width = 500;
  const height = 300;
  let song;
  let fft;

  const [flag, setFlag] = useState(true);

  const [sketchFns] = useState({
    preload: (p) => {
      p.soundFormats('mp3');
      song = p.loadSound('https://www.paulwheeler.us/files/Ipu.wav');
    },
    setup: (p, canvasParentRef) => {
      // react-p5 conveniently initializes window.p5 thats why all the other p5's
      // have been changed to p in order to create an FFT object
      fft = new p5.FFT();
      // console.log(p.point)
      // use parent to render the canvas in this ref
        // without it p5 will render the canvas outside of this component
      p.createCanvas(width, height).parent(canvasParentRef);
    },
    playStop: () => {
      if (song.isPlaying()) {
        song.pause();
        setFlag(true);
        //p.noLoop();
      } else {
        song.play();
        setFlag(false);
        //p.loop();
      }
    },
    draw: p => {
      p.background(0);
      // by default the stroke color is black
      // we need to change this in order to see the wave
      p.stroke(255, 204, 0);

      // no fill in between waves
      p.noFill();
      // returns an array with 1024 elements
      let wave = fft.waveform();

      p.beginShape();
      // By looping through the waveform data, we are able
      // to draw the waveform across the canvas
      for (let i = 0; i < width; i++) {
        // create an index that maps the for loop variable
        // to the index of the wave we want
        // value must be integer thats we we use floor
        let index = p.floor(p.map(i, 0, width, 0, wave.length));

        let x = i;
        let y = wave[index] * 100 + height / 2;
        p.vertex(x, y);
      }
      p.endShape();
    }
  });

  return (

      Audio Visualizer
      {flag ? <button onClick={sketchFns.playStop}>Play</button> : <button onClick={sketchFns.playStop}>Stop</button>}
      <Sketch preload={sketchFns.preload} setup={sketchFns.setup} draw={sketchFns.draw}/>

  );
}

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/react-p5@1.3.27/build/index.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.1/addons/p5.sound.min.js"></script>

<div id="root"></div></code>```

Body:
I created an Audio visualizer using p5.js and React and i need some help.

I am trying to change the state of my button input text from Play to Stop when the song starts playing & from Stop back to Play when the user decides to stop the song at that moment.

I am using react-p5 library and everything works great until i setState when a user clicks the play button. Since that causes a re render it breaks my canvas.

Is there a way to only re-render the button element? I am not too sure how i would go about changing the inner text of my button without a state change?

import React, { useState } from 'react';
import Sketch from 'react-p5';
import 'p5/lib/addons/p5.sound';
import Beat from '../../instrumental.mp3';

const App = () => {

  let width = 900;
  let height = 600;
  let song;
  let fft;

  const [flag, setFlag] = useState(true);

  const preload = (p) => {
    p.soundFormats('mp3');
    song = p.loadSound(Beat);
  }

  const setup = (p, canvasParentRef) => {
    // react-p5 conveniently initializes window.p5 thats why all the other p5's
    // have been changed to p in order to create an FFT object
    fft = new p5.FFT();
    // console.log(p.point)
    // use parent to render the canvas in this ref
        // without it p5 will render the canvas outside of this component
    const canvas = p.createCanvas(width, height).parent(canvasParentRef);
  }

  const playStop = () => {
    if (song.isPlaying()) {
      song.pause();
      setFlag(true);
      //p.noLoop();
    } else {
      song.play();
      setFlag(false);
      //p.loop();
    }
  }

  const draw = p => {
    p.background(0);
    // by default the stroke color is black
    // we need to change this in order to see the wave
    p.stroke(255, 204, 0);

    // no fill in between waves
    p.noFill();
    // returns an array with 1024 elements
    let wave = fft.waveform();

    p.beginShape();
    // By looping through the waveform data, we are able
    // to draw the waveform across the canvas
    for (let i = 0; i < width; i++) {
      // create an index that maps the for loop variable
      // to the index of the wave we want
      // value must be integer thats we we use floor
      let index = p.floor(p.map(i, 0, width, 0, wave.length));

      let x = i;
      let y = wave[index] * 100 + height / 2;
      p.vertex(x, y);
    }
    p.endShape();
  }

  return (

Audio Visualizer

      <Sketch preload={preload} setup={setup} draw={draw}/>
      {flag ? <button onClick={playStop}>Play</button> : <button onClick={playStop}>Stop</button>}

  );
}

export default App;

The sad thing is there aren't many resources available that includes react + p5.js

If anyone would like to take the time and clone this repository down in order to see what the problem might be, i would very much appreciate that.

Repo link: https://github.com/imperium11/audio-visualizer

npm i

npm run dev-build

npm start

Body:
The issue here is that each time you update state in a functional component the function gets called again. As a result each time state changes you re-declare your preload/setup/draw, because of the way react-p5 work, the running sketch will start using your updated draw function. However, the updated draw function expects fft to be defined, but the version of the fft variable referenced by the new draw function is undefined.

In order to fix this you can make any local variables that you sketch uses into state variables. In this example I've packed all the locals into one object:

const { useState } = React;
const Sketch = reactP5;

let v = 0;

const App = () => {
  const width = 500;
  const height = 300;

  const [flag, setFlag] = useState(true);
  const [locals, setLocals] = useState({});

  const preload = (p) => {
    p.soundFormats('mp3');
    setLocals({
      song: p.loadSound('https://www.paulwheeler.us/files/Ipu.wav')
    });
  }

  const setup = (p, canvasParentRef) => {
    // react-p5 conveniently initializes window.p5 thats why all the other p5's
    // have been changed to p in order to create an FFT object
    setLocals({
      ...locals,
      fft: new p5.FFT()
    });
    // console.log(p.point)
    // use parent to render the canvas in this ref
        // without it p5 will render the canvas outside of this component
    p.createCanvas(width, height).parent(canvasParentRef);
  };

  setup.version = v++;

  const playStop = () => {
    if (locals.song.isPlaying()) {
      locals.song.pause();
      setFlag(true);
      //p.noLoop();
    } else {
      locals.song.play();
      setFlag(false);
      //p.loop();
    }
  }

  const draw = p => {
    p.background(0);
    p.text(setup.version.toString(), 20, 20);
    // by default the stroke color is black
    // we need to change this in order to see the wave
    p.stroke(255, 204, 0);

    // no fill in between waves
    p.noFill();
    // returns an array with 1024 elements
    let wave = locals.fft.waveform();

    p.beginShape();
    // By looping through the waveform data, we are able
    // to draw the waveform across the canvas
    for (let i = 0; i < width; i++) {
      // create an index that maps the for loop variable
      // to the index of the wave we want
      // value must be integer thats we we use floor
      let index = p.floor(p.map(i, 0, width, 0, wave.length));

      let x = i;
      let y = wave[index] * 100 + height / 2;
      p.vertex(x, y);
    }
    p.endShape();
  }

  return (
    <div className='outerbox'>
      <span>Audio Visualizer</span>
      {flag ? <button onClick={playStop}>Play</button> : <button onClick={playStop}>Stop</button>}
      <Sketch preload={preload} setup={setup} draw={draw}/>
    </div>
  );
}

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/react-p5@1.3.27/build/index.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.1/addons/p5.sound.min.js"></script>

<div id="root"></div>

Another way to go would be to actually make the functions that use those local variables into state variables. That way they would only be declared the first time your component function is called for each instance of it. This may be a bit of a hack, but it has the advantage of working for rapidly updating local variables (if you were changing local variables in your draw() function, my understanding is that you would not want to make those into state variables, since high frequency state updates may impact performance.

const { useState } = React;
const Sketch = reactP5;

const App = () => {
  const width = 500;
  const height = 300;
  let song;
  let fft;

  const [flag, setFlag] = useState(true);

  const [sketchFns] = useState({
    preload: (p) => {
      p.soundFormats('mp3');
      song = p.loadSound('https://www.paulwheeler.us/files/Ipu.wav');
    },
    setup: (p, canvasParentRef) => {
      // react-p5 conveniently initializes window.p5 thats why all the other p5's
      // have been changed to p in order to create an FFT object
      fft = new p5.FFT();
      // console.log(p.point)
      // use parent to render the canvas in this ref
        // without it p5 will render the canvas outside of this component
      p.createCanvas(width, height).parent(canvasParentRef);
    },
    playStop: () => {
      if (song.isPlaying()) {
        song.pause();
        setFlag(true);
        //p.noLoop();
      } else {
        song.play();
        setFlag(false);
        //p.loop();
      }
    },
    draw: p => {
      p.background(0);
      // by default the stroke color is black
      // we need to change this in order to see the wave
      p.stroke(255, 204, 0);

      // no fill in between waves
      p.noFill();
      // returns an array with 1024 elements
      let wave = fft.waveform();

      p.beginShape();
      // By looping through the waveform data, we are able
      // to draw the waveform across the canvas
      for (let i = 0; i < width; i++) {
        // create an index that maps the for loop variable
        // to the index of the wave we want
        // value must be integer thats we we use floor
        let index = p.floor(p.map(i, 0, width, 0, wave.length));

        let x = i;
        let y = wave[index] * 100 + height / 2;
        p.vertex(x, y);
      }
      p.endShape();
    }
  });

  return (
    <div className='outerbox'>
      <span>Audio Visualizer</span>
      {flag ? <button onClick={sketchFns.playStop}>Play</button> : <button onClick={sketchFns.playStop}>Stop</button>}
      <Sketch preload={sketchFns.preload} setup={sketchFns.setup} draw={sketchFns.draw}/>
    </div>
  );
}

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/react-p5@1.3.27/build/index.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.1/addons/p5.sound.min.js"></script>

<div id="root"></div>


问:
How to change color in TextButton.icon
I want to have an icon with text, so I used TextButton.icon but I can not change the color of the text or icon!
Please suggest if anyone has a solution
this is my code:

```<code>SizedBox(height: 8,),
        TextButton.icon(
          icon: Icon(Icons.delete),
          label: Text('delete'),

          onPressed: (){},
        ),
</code>```

答:
Try below code hope its helpful to you.

Refer TextButton here

```<code>TextButton.icon(
  icon: Icon(
    Icons.delete,
    color: Colors.red,//for icon color
  ),
  label: Text(
    'Delete',
    style: TextStyle(
      color: Colors.red,//for text color
    ),
  ),
  onPressed: () {},
),
</code>```

Result Screen->

Title: How to change color in TextButton.icon

Body:
I want to have an icon with text, so I used TextButton.icon but I can not change the color of the text or icon!
Please suggest if anyone has a solution
this is my code:

SizedBox(height: 8,),
        TextButton.icon(
          icon: Icon(Icons.delete),
          label: Text('delete'),

          onPressed: (){},
        ),

Body:
Try below code hope its helpful to you.

Refer TextButton here

TextButton.icon(
  icon: Icon(
    Icons.delete,
    color: Colors.red,//for icon color
  ),
  label: Text(
    'Delete',
    style: TextStyle(
      color: Colors.red,//for text color
    ),
  ),
  onPressed: () {},
),

Result Screen->


问:
WIX installer with Multiple Entries in Add/Remove Programs
I am developing installer for a Application Suite using WIX, and the structure is
follows:

Application Core

    |_ _ Flavor1

    |_ _ Flavor2

    |_ _ Flavor3

Application Core is a product like Visual Studio and, Flavors 1,2,3 are sub products under it.

Here is my problem,

 - In Add remove programs should have 4 entries for Application Core, Flavor1, Flavor2 and, Flavor3.

 - I should be able to relaunch installer for Add/remove Flavor1, Flavor2 and Flavor3.

答:
It does sound like you want features, so Sander gets my +1.

But sometimes you may want different installs of the same product, e.g. a training and test version installed on the same server. In those cases you need to find a different approach, here's one I came up with (see answer Create Live, ...). Take note of the edit about creating a component per file and wildcarding the guid, since this simplifies the process, i.e. no BeforeBuild/AfterBuild tricks required.

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Si


问:
Should or should not strong password contain user name
So the question is is good practice to have such rule to deny users to have UserName in Passwords?

For example if user type UserName User so he can not have password which would contain User, or is it would be too hard to users?

May be better to just deny users to have UserName equal to Password but allow password to contain UserName?

What do you think?

According with that MS link http://windows.microsoft.com/en-AU/windows-vista/Tips-for-creating-a-strong-password strong passwords should not contain username.

答:
If the password is user-generated, then almost certainly yes if you are at all concerned about the security of the account.  Given the choice, users are much more likely to choose their username as a password than a random password, and consequently, one of the first passwords an attacker is going to try.  (The same goes for passwords like password 123456, abc123, and so on.)

This alludes to the concept of min-entropy.  Essentially, if an attacker wants to guess a single password and doesn't care which password, the min-entropy is the expected number of attempts required.  (This differs from slightly from standard password entropy, which is essentially: if an attacker wants to attack a specific credential, what is the expected number of attempts required?)  If very simple passwords are allowed, the min-entropy value would be lower than it would be without complexity rules in place.

If the password is randomly generated, disallowing the username slightly decreases the entropy of the credential since it reduces the number of allowable password combinations.  In practice, however, an attacker is likely to still try common passwords first, so detecting and restricting common passwords is probably good practice even so.