问:
Quantify goodnes of non-linear fit - Python
I have a dataset with different quality data. There are A-grade, B-grade, C-grade and D-grade data, being the A-grade the best ones and the D-grade the ones with more scatter and uncertainty.

The data comes from a quasi periodic signal and, taking into consideration all the data, it covers just one cycle. If we only take into account the best data (A and B graded, in green and yellow) we don't cover the whole cycle but we are sure that we are only using the best data points.

After computing a periodogram to determine the period of the signal for both, the whole sample and only the A and B graded, I ended up with the following results: 5893 days and 4733 days respectively.
Using those values I fit the data to a sine and I plot them in the following plot:

Plot with the data

In the attached file the green points are the best ones and the red ones are the worst.
As you can see, the data only cover one cycle, and the red points (the worst ones) are crucial to cover that cycle, but they are not as good in quality. So I would like to know if the curve fit is better with those points or not.

I was trying to use the R² parameter but I have read that it only works properly for lineal functions...

How can I quantify which of those fits is better?

Thank you


来源: stackexchange

问:
Angular KendoGrid excelExport event. Add custom column
I'm using the excelExport event for KendoGrid to manipulate some column data before exporting it. Is it possible to add a new column in between two existing columns?

This is the code I have right now to manipulate some dates. I want to add a new column after the first one.

```<code>    exportDataToExcel(e)
    {
        const sheet = e.workbook.sheets[0];
        const datePipe = new DatePipe('es-AR');
        for (let rowIndex = 1; rowIndex < sheet.rows.length; rowIndex++) {
            const row = sheet.rows[rowIndex];
            const timestamp = new Date(row.cells[0].value);
            row.cells[0].value = datePipe.transform(timestamp, this.dateFormatColumns);
        }
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm using the excelExport event for KendoGrid to manipulate some column data before exporting it. Is it possible to add a new column in between two existing columns?

This is the code I have right now to manipulate some dates. I want to add a new column after the first one.

    exportDataToExcel(e)
    {
        const sheet = e.workbook.sheets[0];
        const datePipe = new DatePipe('es-AR');
        for (let rowIndex = 1; rowIndex < sheet.rows.length; rowIndex++) {
            const row = sheet.rows[rowIndex];
            const timestamp = new Date(row.cells[0].value);
            row.cells[0].value = datePipe.transform(timestamp, this.dateFormatColumns);
        }
    }


问:
HTML Table export with jsPDF not responsive
why my table in pdf file like this ? i really confused about this.

table in pdf

table in html

package used: jsPDF

function for generate pdf

```<code>function generatePdf() {
    var doc = new jsPDF("p", "pt", "a4");

    var pdfjs = document.querySelector("#toPDF");

    doc.html(pdfjs, {
      callback: function (doc) {
        doc.save("output.pdf");
      },
    });
  }
</code>```

table code

```<code><table class="w-full mt-1">
  <thead>
    <tr>
      <th>No</th>
      <th>Jenis Saham</th>
      <th>Pemilik</th>
      <th>Jumlah Saham</th>
      <th>Persentase Saham (%)</th>
      <th>Nilai (dalam Rupiah)</th>
    </tr>
  </thead>
  <tbody>
    <tr class="w-full text-center">
      <td>1</td>
      <td>asd</td>
      <td>10</td>
      <td>10</td>
      <td>10</td>
      <td>Rp. 100</td>
    </tr>
  </tbody>
</table>
</code>```

i expect normal table

expect result

Body:
why my table in pdf file like this ? i really confused about this.

table in pdf

table in html

package used: jsPDF

function for generate pdf

function generatePdf() {
    var doc = new jsPDF("p", "pt", "a4");

    var pdfjs = document.querySelector("#toPDF");

    doc.html(pdfjs, {
      callback: function (doc) {
        doc.save("output.pdf");
      },
    });
  }

table code

      No
      Jenis Saham
      Pemilik
      Jumlah Saham
      Persentase Saham (%)
      Nilai (dalam Rupiah)

      1
      asd
      10
      10
      10
      Rp. 100

i expect normal table

expect result


问:
GPU for TensorFlow detected in conda environment, but not in Jupyter notebook (vscode)
I installed TensorFlow as described on this page in WSL.

The final test after installing is succesfull and the GPU is detected by TensorFlow:

python3 -c "import tensorflow as tf; print(tf.config.list_physical_devices('GPU'))"
2022-12-14 15:40:40.633322: I tensorflow/core/platform/cpu_feature_guard.cc:193] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations:  AVX2 FMA
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
2022-12-14 15:40:41.288334: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libnvinfer.so.7'; dlerror: libnvinfer.so.7: cannot open shared object file: No such file or directory; LD_LIBRARY_PATH: :/home/miepi/miniconda3/envs/tf/lib/
2022-12-14 15:40:41.288439: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libnvinfer_plugin.so.7'; dlerror: libnvinfer_plugin.so.7: cannot open shared object file: No such file or directory; LD_LIBRARY_PATH: :/home/miepi/miniconda3/envs/tf/lib/
2022-12-14 15:40:41.288485: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Cannot dlopen some TensorRT libraries. If you would like to use Nvidia GPU with TensorRT, please make sure the missing libraries mentioned above are installed properly.
2022-12-14 15:40:41.778389: I tensorflow/compiler/xla/stream_executor/cuda/cuda_gpu_executor.cc:967] could not open file to read NUMA node: /sys/bus/pci/devices/0000:01:00.0/numa_node
Your kernel may have been built without NUMA support.
2022-12-14 15:40:41.786330: I tensorflow/compiler/xla/stream_executor/cuda/cuda_gpu_executor.cc:967] could not open file to read NUMA node: /sys/bus/pci/devices/0000:01:00.0/numa_node
Your kernel may have been built without NUMA support.
2022-12-14 15:40:41.786752: I tensorflow/compiler/xla/stream_executor/cuda/cuda_gpu_executor.cc:967] could not open file to read NUMA node: /sys/bus/pci/devices/0000:01:00.0/numa_node
Your kernel may have been built without NUMA support.
[PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')]
```
<p>But using the same conda environment in vscode the gpu isn't detected:</p>
<pre class="lang-py prettyprint-override"><code>import tensorflow as tf
</code>```

Output:

```<code>2022-12-14 15:52:40.605584: I tensorflow/core/platform/cpu_feature_guard.cc:193] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations:  AVX2 FMA
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
2022-12-14 15:52:40.702419: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libcudart.so.11.0'; dlerror: libcudart.so.11.0: cannot open shared object file: No such file or directory
2022-12-14 15:52:40.702451: I tensorflow/compiler/xla/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.
2022-12-14 15:52:41.280631: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libnvinfer.so.7'; dlerror: libnvinfer.so.7: cannot open shared object file: No such file or directory
2022-12-14 15:52:41.280716: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libnvinfer_plugin.so.7'; dlerror: libnvinfer_plugin.so.7: cannot open shared object file: No such file or directory
2022-12-14 15:52:41.280726: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Cannot dlopen some TensorRT libraries. If you would like to use Nvidia GPU with TensorRT, please make sure the missing libraries mentioned above are installed properly.
</code>```

# Check if GPU is available
print(tf.config.list_physical_devices('GPU'))
print("Num GPUs Available: ", len(tf.config.experimental.list_physical_devices('GPU')))
```
<p>Output:</p>
```[]
Num GPUs Available:  0
2022-12-14 15:52:43.871361: I tensorflow/compiler/xla/stream_executor/cuda/cuda_gpu_executor.cc:967] could not open file to read NUMA node: /sys/bus/pci/devices/0000:01:00.0/numa_node
Your kernel may have been built without NUMA support.
2022-12-14 15:52:43.871484: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libcudart.so.11.0'; dlerror: libcudart.so.11.0: cannot open shared object file: No such file or directory
2022-12-14 15:52:43.871536: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libcublas.so.11'; dlerror: libcublas.so.11: cannot open shared object file: No such file or directory
2022-12-14 15:52:43.871577: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libcublasLt.so.11'; dlerror: libcublasLt.so.11: cannot open shared object file: No such file or directory
2022-12-14 15:52:43.871617: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libcufft.so.10'; dlerror: libcufft.so.10: cannot open shared object file: No such file or directory
2022-12-14 15:52:43.871656: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libcurand.so.10'; dlerror: libcurand.so.10: cannot open shared object file: No such file or directory
2022-12-14 15:52:43.871694: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libcusolver.so.11'; dlerror: libcusolver.so.11: cannot open shared object file: No such file or directory
2022-12-14 15:52:43.871734: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libcusparse.so.11'; dlerror: libcusparse.so.11: cannot open shared object file: No such file or directory
2022-12-14 15:52:43.871772: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libcudnn.so.8'; dlerror: libcudnn.so.8: cannot open shared object file: No such file or directory
2022-12-14 15:52:43.871781: W tensorflow/core/common_runtime/gpu/gpu_device.cc:1934] Cannot dlopen some GPU libraries. Please make sure the missing libraries mentioned above are installed properly if you would like to use GPU. Follow the guide at https://www.tensorflow.org/install/gpu for how to download and setup the required libraries for your platform.
Skipping registering GPU devices...
```
<p>Does anybody have an idea, what I could try to fix this issue? Or what I could have done wrong?</p>
<ul>
<li>I already checked if the correct kernel is selected in vscode.</li>
<li>And the correct interpreter is set for the workspace as well.</li>
<li>Jupyter is installed in the environment</li>
</ul>
<p>Could it be possible that this step from the tutorial is not working for the jupyter kernel in vscode?</p>
<pre class="lang-bash prettyprint-override"><code>mkdir -p $CONDA_PREFIX/etc/conda/activate.d
echo 'export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$CONDA_PREFIX/lib/' > $CONDA_PREFIX/etc/conda/activate.d/env_vars.sh
</code>```

But I don't know how to set that up in vscode.

Body:
I installed TensorFlow as described on this page in WSL.

The final test after installing is succesfull and the GPU is detected by TensorFlow:

python3 -c "import tensorflow as tf; print(tf.config.list_physical_devices('GPU'))"
2022-12-14 15:40:40.633322: I tensorflow/core/platform/cpu_feature_guard.cc:193] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations:  AVX2 FMA
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
2022-12-14 15:40:41.288334: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libnvinfer.so.7'; dlerror: libnvinfer.so.7: cannot open shared object file: No such file or directory; LD_LIBRARY_PATH: :/home/miepi/miniconda3/envs/tf/lib/
2022-12-14 15:40:41.288439: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libnvinfer_plugin.so.7'; dlerror: libnvinfer_plugin.so.7: cannot open shared object file: No such file or directory; LD_LIBRARY_PATH: :/home/miepi/miniconda3/envs/tf/lib/
2022-12-14 15:40:41.288485: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Cannot dlopen some TensorRT libraries. If you would like to use Nvidia GPU with TensorRT, please make sure the missing libraries mentioned above are installed properly.
2022-12-14 15:40:41.778389: I tensorflow/compiler/xla/stream_executor/cuda/cuda_gpu_executor.cc:967] could not open file to read NUMA node: /sys/bus/pci/devices/0000:01:00.0/numa_node
Your kernel may have been built without NUMA support.
2022-12-14 15:40:41.786330: I tensorflow/compiler/xla/stream_executor/cuda/cuda_gpu_executor.cc:967] could not open file to read NUMA node: /sys/bus/pci/devices/0000:01:00.0/numa_node
Your kernel may have been built without NUMA support.
2022-12-14 15:40:41.786752: I tensorflow/compiler/xla/stream_executor/cuda/cuda_gpu_executor.cc:967] could not open file to read NUMA node: /sys/bus/pci/devices/0000:01:00.0/numa_node
Your kernel may have been built without NUMA support.
[PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')]

But using the same conda environment in vscode the gpu isn't detected:

import tensorflow as tf

Output:

2022-12-14 15:52:40.605584: I tensorflow/core/platform/cpu_feature_guard.cc:193] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations:  AVX2 FMA
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
2022-12-14 15:52:40.702419: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libcudart.so.11.0'; dlerror: libcudart.so.11.0: cannot open shared object file: No such file or directory
2022-12-14 15:52:40.702451: I tensorflow/compiler/xla/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.
2022-12-14 15:52:41.280631: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libnvinfer.so.7'; dlerror: libnvinfer.so.7: cannot open shared object file: No such file or directory
2022-12-14 15:52:41.280716: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libnvinfer_plugin.so.7'; dlerror: libnvinfer_plugin.so.7: cannot open shared object file: No such file or directory
2022-12-14 15:52:41.280726: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Cannot dlopen some TensorRT libraries. If you would like to use Nvidia GPU with TensorRT, please make sure the missing libraries mentioned above are installed properly.

# Check if GPU is available
print(tf.config.list_physical_devices('GPU'))
print("Num GPUs Available: ", len(tf.config.experimental.list_physical_devices('GPU')))

Output:

[]
Num GPUs Available:  0
2022-12-14 15:52:43.871361: I tensorflow/compiler/xla/stream_executor/cuda/cuda_gpu_executor.cc:967] could not open file to read NUMA node: /sys/bus/pci/devices/0000:01:00.0/numa_node
Your kernel may have been built without NUMA support.
2022-12-14 15:52:43.871484: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libcudart.so.11.0'; dlerror: libcudart.so.11.0: cannot open shared object file: No such file or directory
2022-12-14 15:52:43.871536: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libcublas.so.11'; dlerror: libcublas.so.11: cannot open shared object file: No such file or directory
2022-12-14 15:52:43.871577: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libcublasLt.so.11'; dlerror: libcublasLt.so.11: cannot open shared object file: No such file or directory
2022-12-14 15:52:43.871617: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libcufft.so.10'; dlerror: libcufft.so.10: cannot open shared object file: No such file or directory
2022-12-14 15:52:43.871656: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libcurand.so.10'; dlerror: libcurand.so.10: cannot open shared object file: No such file or directory
2022-12-14 15:52:43.871694: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libcusolver.so.11'; dlerror: libcusolver.so.11: cannot open shared object file: No such file or directory
2022-12-14 15:52:43.871734: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libcusparse.so.11'; dlerror: libcusparse.so.11: cannot open shared object file: No such file or directory
2022-12-14 15:52:43.871772: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libcudnn.so.8'; dlerror: libcudnn.so.8: cannot open shared object file: No such file or directory
2022-12-14 15:52:43.871781: W tensorflow/core/common_runtime/gpu/gpu_device.cc:1934] Cannot dlopen some GPU libraries. Please make sure the missing libraries mentioned above are installed properly if you would like to use GPU. Follow the guide at https://www.tensorflow.org/install/gpu for how to download and setup the required libraries for your platform.
Skipping registering GPU devices...

Does anybody have an idea, what I could try to fix this issue? Or what I could have done wrong?

I already checked if the correct kernel is selected in vscode.

And the correct interpreter is set for the workspace as well.

Jupyter is installed in the environment

Could it be possible that this step from the tutorial is not working for the jupyter kernel in vscode?

mkdir -p $CONDA_PREFIX/etc/conda/activate.d
echo 'export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$CONDA_PREFIX/lib/' > $CONDA_PREFIX/etc/conda/activate.d/env_vars.sh

But I don't know how to set that up in vscode.


问:
Error on fetch last message id without any changes
Im still on my way into python and discord api and I got an error I cannot really understand and hopefully you can explain it to me.

Yesterday this simple code worked totally fine, today I'm getting 'NotFound: 404 Not Found (error code: 10008): Unknown Message'.
Ofcourse there is a new msg in the channel, but why is that changing anything to last_message_id?

```<code>channel = bot.get_channel(fixedchannelid)
message = await channel.fetch_message(
    channel.last_message_id)

</code>```

I hope you can give me advise where i went wrong

/Edit:
I tried to react to D.L's comment as good as possible, but I wasn't ablt to reproduce the mistake.
What I did: I changed the channelID for testing and it worked. When I set it back to the channelID where the problem occured it still threw the error. So I simply wrote a new post in that channel and it worked again.
In the end it's not working for only that one post what just makes me confused what the basic problem could have been.

Body:
Im still on my way into python and discord api and I got an error I cannot really understand and hopefully you can explain it to me.

Yesterday this simple code worked totally fine, today I'm getting 'NotFound: 404 Not Found (error code: 10008): Unknown Message'.
Ofcourse there is a new msg in the channel, but why is that changing anything to last_message_id?

channel = bot.get_channel(fixedchannelid)
message = await channel.fetch_message(
    channel.last_message_id)

I hope you can give me advise where i went wrong

/Edit:
I tried to react to D.L's comment as good as possible, but I wasn't ablt to reproduce the mistake.
What I did: I changed the channelID for testing and it worked. When I set it back to the channelID where the problem occured it still threw the error. So I simply wrote a new post in that channel and it worked again.
In the end it's not working for only that one post what just makes me confused what the basic problem could have been.


问:
integrating 3d vuxiz glasses with wpf
I am trying to figure out how to integrate vuxiz glasses with wpf. to achieve it i will need explicit control on timing of rendering of the frames. e.g. in xna we can issue an explicit render call. is there anything like this in wpf. i want to achieve following workflow.

Switch to left eye ( vuxiz sdk call )

Ask wpf to render

switch to right eye

Ask wpf to render

how to i do 2 and 4?

ContentLicense: CC BY-SA 3.0

Title: integrating 3d vuxiz glasses with wpf


问:
Django can't catch all the values throwing an exception
I am trying to import excel data to a django model. So to test it, I used an excel file with more than 4000 rows. One of the fields in the model requires the entry to be unique, so I tried to catch all the entries that aren't. I have a try-catch block around the code that tries to add the values of each row to the model.

integrity_catches = {}
integrity_counts = 0

# loop start

try:
    new_student = Student(
        student_school = school,
        student_class = selected_class,
        student_stream = selected_stream,
        admission_number = admission_number_cell,
        student_name = student_name_cell,
        parent_phone = parent_phone_cell,
        kcpe_marks = kcpe_marks_cell
    )

    new_student.save()

except IntegrityError as e:
        integrity_catches[admission_number_cell] = student_name_cell
        integrity_counts = integrity_counts + 1
        continue

# loop end
```

The code runs well, but only imports 250 students, so I expect it to add the rest to the integrity_catches dictionary. The problem is, the dictionary contains 202 entries, while the integrity_counts is showing 4035. This means that more than 4000 entries raised an exception but didn't get stored in the dictionary. I am trying to make sure that when someone imports the data from an excel sheet, they can see all the entries that failed to be added to the database.
Also if I look at the successfully imported values, I notice some obvious numbers missing, but are in the excel. And if I look at the values that are caught in the dictionary, some values that are obviously repeating themselves are not added to it. How can OI fix this?

Body:
I am trying to import excel data to a django model. So to test it, I used an excel file with more than 4000 rows. One of the fields in the model requires the entry to be unique, so I tried to catch all the entries that aren't. I have a try-catch block around the code that tries to add the values of each row to the model.

integrity_catches = {}
integrity_counts = 0

# loop start

try:
    new_student = Student(
        student_school = school,
        student_class = selected_class,
        student_stream = selected_stream,
        admission_number = admission_number_cell,
        student_name = student_name_cell,
        parent_phone = parent_phone_cell,
        kcpe_marks = kcpe_marks_cell
    )

    new_student.save()

except IntegrityError as e:
        integrity_catches[admission_number_cell] = student_name_cell
        integrity_counts = integrity_counts + 1
        continue

# loop end

The code runs well, but only imports 250 students, so I expect it to add the rest to the integrity_catches dictionary. The problem is, the dictionary contains 202 entries, while the integrity_counts is showing 4035. This means that more than 4000 entries raised an exception but didn't get stored in the dictionary. I am trying to make sure that when someone imports the data from an excel sheet, they can see all the entries that failed to be added to the database.
Also if I look at the successfully imported values, I notice some obvious numbers missing, but are in the excel. And if I look at the values that are caught in the dictionary, some values that are obviously repeating themselves are not added to it. How can OI fix this?


问:
Undefined reference when trying to link libxc to fortran
I am trying to compile a simple fortran program that uses libxc.

```<code>PROGRAM example_basicF90

   USE xc_f90_lib_m ! XCs, types and functions

   IMPLICIT NONE

   INTEGER :: i, vmajor, vminor, vmicro

   CALL xc_f90_version(vmajor, vminor, vmicro)
   WRITE(*,100) vmajor, vminor, vmicro

100 FORMAT("Libxc version: ",I1,"."I1"."I1)

END PROGRAM
</code>```

I have compiled libxc using gcc/9.2.0 following the instructions provided on the git repo Without any issues

```<code>./configure --prefix=/scratch/Applications/libxc/libxc-6.0.0/GCC
make
make check
make install
</code>```

The issue I encounter is when I try to compile the simple code.

```<code>export LD_LIBXC=/scratch/Applications/libxc/libxc-6.0.0/GCC
gfortran -o example_basic -L${LD_LIBXC}/lib -lxcf90 -lxc -I${LD_LIBXC}/include example_basic.f90

example_basic.f90:(.text+0x1e): undefined reference to `__xc_f90_lib_m_MOD_xc_f90_version'
</code>```

I double checked the lib and include directories for the correct files, and everything seems appropriate:

```<code>ls ${LD_LIBXC}/lib
libxc.a  libxcf03.a  libxcf03.la  libxcf90.a  libxcf90.la  libxc.la  pkgconfig

$ ls ${LD_LIBXC}/include
libxc.bib  xc_f03_lib_m.mod  xc_f90_lib_m.mod  xc_funcs.h  xc_funcs_removed.h  xc_funcs_worker.h  xc.h  xc_version.h
</code>```

Any help is appreciated. Thanks

Body:
I am trying to compile a simple fortran program that uses libxc.

PROGRAM example_basicF90

   USE xc_f90_lib_m ! XCs, types and functions

   IMPLICIT NONE

   INTEGER :: i, vmajor, vminor, vmicro

   CALL xc_f90_version(vmajor, vminor, vmicro)
   WRITE(*,100) vmajor, vminor, vmicro

100 FORMAT("Libxc version: ",I1,"."I1"."I1)

END PROGRAM

I have compiled libxc using gcc/9.2.0 following the instructions provided on the git repo Without any issues

./configure --prefix=/scratch/Applications/libxc/libxc-6.0.0/GCC
make
make check
make install

The issue I encounter is when I try to compile the simple code.

export LD_LIBXC=/scratch/Applications/libxc/libxc-6.0.0/GCC
gfortran -o example_basic -L${LD_LIBXC}/lib -lxcf90 -lxc -I${LD_LIBXC}/include example_basic.f90

example_basic.f90:(.text+0x1e): undefined reference to `__xc_f90_lib_m_MOD_xc_f90_version'

I double checked the lib and include directories for the correct files, and everything seems appropriate:

ls ${LD_LIBXC}/lib
libxc.a  libxcf03.a  libxcf03.la  libxcf90.a  libxcf90.la  libxc.la  pkgconfig

$ ls ${LD_LIBXC}/include
libxc.bib  xc_f03_lib_m.mod  xc_f90_lib_m.mod  xc_funcs.h  xc_funcs_removed.h  xc_funcs_worker.h  xc.h  xc_version.h

Any help is appreciated. Thanks


问:
There was a problem in getting coordinates inside the image (not the main root window root tkinter
There was a problem in getting the coordinates inside the picture (not the main root window, the source code will be at the end), the image is loaded using cv2 and added to the application interface via label. How can I get coordinates when clicking the mouse only on the picture? If it is possible to do this through tkinter, again only inside the picture.

```<code>import tkinter as tk
from tkinter import ttk, filedialog
import cv2
from PIL import Image
from PIL import ImageTk

class interface:
    def __init__(self):
        self.panelA = None

        self.path = None
        self.s = None
        self.a = None

        self.root = tk.Tk()

        self.f1 = tk.Frame(self.root)
        self.f1.grid(row=0, column=0)

        self.f2 = tk.Frame(self.root)
        self.f2.grid(row=0, column=1)

        self.e = tk.Entry(self.f1)
        self.e.grid(column=1, row=1, sticky='ew')

        self.l1 = tk.Label(self.f1, text="Choose a picture")
        self.l1.grid(column=0, row=0, sticky='ew')

        self.l2 = tk.Label(self.f1, text="Введите напор H, м")
        self.l2.grid(column=0, row=1, sticky='ew')

        b1 = tk.Button(self.f1, text="Specify the file with the characteristic", command=self.select_image)
        b1.grid(column=0, row=0, sticky='ew', columnspan=3)

        b2 = tk.Button(self.f1, text="select the pressure")
        b2.grid(column=2, row=1, sticky='ew')

        columns = ['N', 'ny']
        self.table = ttk.Treeview(self.f1, columns=columns, show='headings', height=20)
        self.table.heading("N", text="N")
        self.table.heading("ny", text="%")
        self.table.grid(column=0, row=3, columnspan=3, sticky='ew')

        self.root.mainloop()

    def get_s(self):
        return self.s

    def select_image(self):
        self.path = filedialog.askopenfilename()

        if self.path:
            image = cv2.imread(self.path)

            image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
            image = Image.fromarray(image)

            image = ImageTk.PhotoImage(image)

            if self.panelA is None:
                self.panelA = tk.Label(self.f2, image=image)
                self.panelA.image = image
                self.panelA.grid()

            else:
                self.panelA.configure(image=image)
                self.panelA.image = image

obj_interface = interface()
</code>```

I tried it in tkinter, but it turned out to click only in the entire application

Body:
There was a problem in getting the coordinates inside the picture (not the main root window, the source code will be at the end), the image is loaded using cv2 and added to the application interface via label. How can I get coordinates when clicking the mouse only on the picture? If it is possible to do this through tkinter, again only inside the picture.

import tkinter as tk
from tkinter import ttk, filedialog
import cv2
from PIL import Image
from PIL import ImageTk

class interface:
    def __init__(self):
        self.panelA = None

        self.path = None
        self.s = None
        self.a = None

        self.root = tk.Tk()

        self.f1 = tk.Frame(self.root)
        self.f1.grid(row=0, column=0)

        self.f2 = tk.Frame(self.root)
        self.f2.grid(row=0, column=1)

        self.e = tk.Entry(self.f1)
        self.e.grid(column=1, row=1, sticky='ew')

        self.l1 = tk.Label(self.f1, text="Choose a picture")
        self.l1.grid(column=0, row=0, sticky='ew')

        self.l2 = tk.Label(self.f1, text="Введите напор H, м")
        self.l2.grid(column=0, row=1, sticky='ew')

        b1 = tk.Button(self.f1, text="Specify the file with the characteristic", command=self.select_image)
        b1.grid(column=0, row=0, sticky='ew', columnspan=3)

        b2 = tk.Button(self.f1, text="select the pressure")
        b2.grid(column=2, row=1, sticky='ew')

        columns = ['N', 'ny']
        self.table = ttk.Treeview(self.f1, columns=columns, show='headings', height=20)
        self.table.heading("N", text="N")
        self.table.heading("ny", text="%")
        self.table.grid(column=0, row=3, columnspan=3, sticky='ew')

        self.root.mainloop()

    def get_s(self):
        return self.s

    def select_image(self):
        self.path = filedialog.askopenfilename()

        if self.path:
            image = cv2.imread(self.path)

            image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
            image = Image.fromarray(image)

            image = ImageTk.PhotoImage(image)

            if self.panelA is None:
                self.panelA = tk.Label(self.f2, image=image)
                self.panelA.image = image
                self.panelA.grid()

            else:
                self.panelA.configure(image=image)
                self.panelA.image = image

obj_interface = interface()

I tried it in tkinter, but it turned out to click only in the entire application


问:
How to manage vcpkg across many projects?
I would love to use vcpkg to manage our dependencies with third party libraries, but I'm not sure how this is would work in our environment. We have hundreds of projects in our solution, and release new versions of our software over time. This is a very common situation for software development, but I don't understand how vcpkg can work effectively.

Global installation will not work. We need to tie our releases to specific versions of packages. So we're left with using manifests. In a manifest, you specify a "builtin-baseline" which is a great way to pin the build of a project to a point in time, with some guarantees that the dependencies between the different packages are correct.

This is all great for a project. How does one manage hundreds of projects?

We would like to use the same baseline across all projects. Is there a way to specify the builtin-baseline in one place?

Some packages are common to all projects. Is there a way to specify this in one place?

We use project files for building. By default, vcpkg uses a project-local install directory. We don't need 100s of copies of boost. There is a vcpkg project setting for "Installed Directory" which allows a global location. But again, this setting is per-project. I don't see any integration with .props files. Is there a way to manage this?

Is there a way to get a solution-wide listing of all packages?

Would using CMake make this all easier?


问:
Change the response status code for ngx.exec in Openresty
I am returning a stored custom HTML file for a particular request using ngx.exec function. I want to set the right HTTP response code. I am not able to figure out how to do that. Even if I set ngx.status before ngx.exec the response code returned is always 200 to the client.
Is there a way to set the response code?</p>


问:
Pynamodb Transaction not using local endpoint
Regardless of whatever I tried, pynamodb is not connecting to my local dynamodb.

Below is my model,

```<code>class OrderMarker(Model):
    class Meta:
        table_name = 'ddb_mrker_table'
        connection = TableConnection(table_name='ddb_mrker_table', host='http://localhost:8000')
    OrderUniqueueId = UnicodeAttribute(hash_key=True)
</code>```

Below is the exception,

```<code>Traceback (most recent call last):
  File "C:\backend\orders\snapshot\app.py", line 451, in <module>
    main()
  File "C:\backend\orders\snapshot\app.py", line 445, in main
    OrderMarker.create_table(wait=True)
  File "C:\Users\user1\AppData\Local\Programs\Python\Python39\lib\site-packages\pynamodb\models.py", line 798, in create_table
    if not cls.exists():
  File "C:\Users\user1\AppData\Local\Programs\Python\Python39\lib\site-packages\pynamodb\models.py", line 762, in exists
    cls._get_connection().describe_table()
  File "C:\Users\user1\AppData\Local\Programs\Python\Python39\lib\site-packages\pynamodb\connection\table.py", line 294, in describe_table
    return self.connection.describe_table(self.table_name)
  File "C:\Users\user1\AppData\Local\Programs\Python\Python39\lib\site-packages\pynamodb\connection\base.py", line 787, in describe_table
    raise TableError("Unable to describe table: {}".format(e), e)
pynamodb.exceptions.TableError: Unable to describe table: Could not connect to the endpoint URL: "https://dynamodb.us-east-1.amazonaws.com/"
</code>```

As you can see , pynamodb is trying to access https://dynamodb.us-east-1.amazonaws.com/ eventhough I have specified the local endpoint url. This is the case always, even when I try transactions too.

Local ddb server is run as shown below,

java -Djava.library.path=./DynamoDBLocal_lib -jar DynamoDBLocal.jar -inMemory -delayTransientStatuses

A quick check using aws dynamodb list-tables --endpoint-url http://localhost:8000 shows local server is running fine!

Any idea?

Body:
Regardless of whatever I tried, pynamodb is not connecting to my local dynamodb.

Below is my model,

class OrderMarker(Model):
    class Meta:
        table_name = 'ddb_mrker_table'
        connection = TableConnection(table_name='ddb_mrker_table', host='http://localhost:8000')
    OrderUniqueueId = UnicodeAttribute(hash_key=True)

Below is the exception,

Traceback (most recent call last):
  File "C:\backend\orders\snapshot\app.py", line 451, in <module>
    main()
  File "C:\backend\orders\snapshot\app.py", line 445, in main
    OrderMarker.create_table(wait=True)
  File "C:\Users\user1\AppData\Local\Programs\Python\Python39\lib\site-packages\pynamodb\models.py", line 798, in create_table
    if not cls.exists():
  File "C:\Users\user1\AppData\Local\Programs\Python\Python39\lib\site-packages\pynamodb\models.py", line 762, in exists
    cls._get_connection().describe_table()
  File "C:\Users\user1\AppData\Local\Programs\Python\Python39\lib\site-packages\pynamodb\connection\table.py", line 294, in describe_table
    return self.connection.describe_table(self.table_name)
  File "C:\Users\user1\AppData\Local\Programs\Python\Python39\lib\site-packages\pynamodb\connection\base.py", line 787, in describe_table
    raise TableError("Unable to describe table: {}".format(e), e)
pynamodb.exceptions.TableError: Unable to describe table: Could not connect to the endpoint URL: "https://dynamodb.us-east-1.amazonaws.com/"

As you can see , pynamodb is trying to access https://dynamodb.us-east-1.amazonaws.com/ eventhough I have specified the local endpoint url. This is the case always, even when I try transactions too.

Local ddb server is run as shown below,

java -Djava.library.path=./DynamoDBLocal_lib -jar DynamoDBLocal.jar -inMemory -delayTransientStatuses

A quick check using aws dynamodb list-tables --endpoint-url http://localhost:8000 shows local server is running fine!

Any idea?


问:
Real IP address + port from cloudflare over nginx proxy manager to apache
I'm looking for a way to "pipe" the clients real IP address and port from Cloudflare over NGINX Proxy Manager to the main webserver apache.

The system is implemented in docker. The domain is configurated by cloudflare with proxy. I got a docker container with nginx that pipe the users requests to the apache container.

I want to log the original, real IP addresses AND the ports of users. I don't care where I pick up the data, whether it's from NGINX or Apache or, if necessary, from cloudflare. Preferably with the apache.

In PHP you get with:

$_SERVER['REMOTE_ADDR'] -> the IP address of the NGINX container (sure)

$_SERVER['HTTP_CF_CONNECTING_IP'] -> the real IP address of the user (what I want)

I don't know whether the original port is behind $_SERVER['REMOTE_PORT']. Probably not.
With Cloudflare there is the possibility to define additional fields in which the port could be passed through. How do I get to the field / the port.

Thanks a lot and best greetings
Mtz

A wasy to pipe the users original IP addresses and ports through Cloudflare and NGINX to apache (to log them).


问:
How to write with pyautogui letters like ěščřžý with UTF-8, but i cannot use ctrl + v
I want to use letters like ěšřýáí with pyautogui.write or typewrite but pyautogui.write doesn't using UTF-8 and i cannot use ctrl + v.</p>
```<code>if(vyberpapir == "402"):
                txtopen = io.open("cctyrdva.txt", encoding="utf-8")

                vysledek = txtopen.read()
                print(vysledek)

                input("Po stisknutí enteru máš 5 sekund na přepnutí do zavu na cvičení. Pro pokračování zmáčkni enter: ")
                tm.sleep(5)
                pa.write(vysledek, interval=0.05)
</code>```

Body:
I want to use letters like ěšřýáí with pyautogui.write or typewrite but pyautogui.write doesn't using UTF-8 and i cannot use ctrl + v.

if(vyberpapir == "402"):
                txtopen = io.open("cctyrdva.txt", encoding="utf-8")

                vysledek = txtopen.read()
                print(vysledek)

                input("Po stisknutí enteru máš 5 sekund na přepnutí do zavu na cvičení. Pro pokračování zmáčkni enter: ")
                tm.sleep(5)
                pa.write(vysledek, interval=0.05)


问:
Android library to dynamically generate views from a given user file
I am trying to find a tool to automatically generate a set of view elements in the fragment.

The idea is to have a user input template file (xml or json), where the user can define the simple fields that he wants to see displayed in the fragment such as TextView, EditText, Buttons or spinner menus.
Then, the app can read that file and load/generate automatically the fields and show them in the fragment.

For example, a user defines the following json file, here define 2 TextFields and one checkbox with 2 options:

```<code>{
"sections": [
    {
        "rows": [
            {
                "items": [
                    {
                        "componentType": "TextField",
                        "inputType" "text",
                        "var": "user name"
                    }
                ]
            }
        ],
        "itemRank": "1",
        "title": "User Login Name",
        "shortTitle": "login"
    },
    {
        "rows": [
            {
                "items": [
                    {
                        "componentType": "TextField",
                        "inputType" "float",
                        "var": "0.0",
                        "min": "0.0",
                        "max": "100.0",
                        "format":"3.3f"
                    }
                ]
            }
        ],
        "itemRank": "2",
        "title": "Weather Temperature",
        "shortTitle": "temp"
    },
    {
        "rows": [
            {
                "items": [
                    {
                        "componentType": "multiSelect",
                        "inputType" "float",
                        "options": [
                            {
                                "text": "Checkbox option 1",
                                "var": "option1",
                                "selected": "false"
                            },
                            {
                                "text": "Checkbox option 2",
                                "var": "option2",
                                "selected": "false"
                            }
                        ]
                    }
                ]
            }
        ],
        "itemRank": "3",
        "title": "Weather Temperature",
        "shortTitle": "temp"
    },
    "name": "My json template view elements",
    "title": "My report"
}
</code>```

Having that json file as an input, generate these fields to attach them on the fragment as views and process them accordingly.

Is there a library that can do that?

Body:
I am trying to find a tool to automatically generate a set of view elements in the fragment.

The idea is to have a user input template file (xml or json), where the user can define the simple fields that he wants to see displayed in the fragment such as TextView, EditText, Buttons or spinner menus.
Then, the app can read that file and load/generate automatically the fields and show them in the fragment.

For example, a user defines the following json file, here define 2 TextFields and one checkbox with 2 options:

{
"sections": [
    {
        "rows": [
            {
                "items": [
                    {
                        "componentType": "TextField",
                        "inputType" "text",
                        "var": "user name"
                    }
                ]
            }
        ],
        "itemRank": "1",
        "title": "User Login Name",
        "shortTitle": "login"
    },
    {
        "rows": [
            {
                "items": [
                    {
                        "componentType": "TextField",
                        "inputType" "float",
                        "var": "0.0",
                        "min": "0.0",
                        "max": "100.0",
                        "format":"3.3f"
                    }
                ]
            }
        ],
        "itemRank": "2",
        "title": "Weather Temperature",
        "shortTitle": "temp"
    },
    {
        "rows": [
            {
                "items": [
                    {
                        "componentType": "multiSelect",
                        "inputType" "float",
                        "options": [
                            {
                                "text": "Checkbox option 1",
                                "var": "option1",
                                "selected": "false"
                            },
                            {
                                "text": "Checkbox option 2",
                                "var": "option2",
                                "selected": "false"
                            }
                        ]
                    }
                ]
            }
        ],
        "itemRank": "3",
        "title": "Weather Temperature",
        "shortTitle": "temp"
    },
    "name": "My json template view elements",
    "title": "My report"
}

Having that json file as an input, generate these fields to attach them on the fragment as views and process them accordingly.

Is there a library that can do that?


问:
Visual Studio 2019 and 2022, cannot add new web.config, missing 'add config transform' option
I want to create a new config file that should be used on the new Configuration i made.
But seems the option is missing when i right click most of the things out of google and say "right click on web.config and click on 'add config transform', but the thing is, that option is not available in VS2019 and VS2022".

So what are my options, how do i add a new web.config file?

From the screenshot above, i see that the old developer already created one, but he already left so i have nothing to ask.


问:
Sqlite database returning undefined in a electron / react app
I'm using Electron React Boilerplate. My goal lis to display a sqlite table, from a local database in my front-end. When I try to import and use sqlite3, any property cannot be used because I get this error:

historicoMgr.ts:3 Uncaught TypeError: Cannot read properties of undefined (reading 'Database')

```<code>at Object../src/db/models/historicoMgr.ts (historicoMgr.ts:3)
at Object.options.factory (react refresh:6)
at __webpack_require__ (bootstrap:24)
at fn (hot module replacement:62)
at Object../src/components/Table/Table.tsx (Table.tsx:5)
at Object.options.factory (react refresh:6)
at __webpack_require__ (bootstrap:24)
at fn (hot module replacement:62)
at Object../src/components/Pages/Historico.tsx (Historico.tsx:3)
at Object.options.factory (react refresh:6)
</code>```

The module where I import the sqlite3 is this:

```<code>import sqlite3 from 'sqlite3';

const db = new sqlite3.Database('./test.db');

export const getRowsFromHistorico: () => Promise<Array<any>> = async () => {
    return new Promise ((resolve, reject) => {
            db.all('SELECT * FROM historico', (err: Error, rows: any[]) => {
                if (err){
                    reject(err)
                };
                resolve(rows);
            })
        });
};
</code>```

I tried to use it in a test file and it worked perfectly. Also tried to import sqlite3 like:

 const sqlite3 = require('sqlite3').verbose();

But the same error continue.

Does somebody know why the database is returning undefined here? Thank you!

Body:
I'm using Electron React Boilerplate. My goal lis to display a sqlite table, from a local database in my front-end. When I try to import and use sqlite3, any property cannot be used because I get this error:

historicoMgr.ts:3 Uncaught TypeError: Cannot read properties of undefined (reading 'Database')

at Object../src/db/models/historicoMgr.ts (historicoMgr.ts:3)
at Object.options.factory (react refresh:6)
at __webpack_require__ (bootstrap:24)
at fn (hot module replacement:62)
at Object../src/components/Table/Table.tsx (Table.tsx:5)
at Object.options.factory (react refresh:6)
at __webpack_require__ (bootstrap:24)
at fn (hot module replacement:62)
at Object../src/components/Pages/Historico.tsx (Historico.tsx:3)
at Object.options.factory (react refresh:6)

The module where I import the sqlite3 is this:

import sqlite3 from 'sqlite3';

const db = new sqlite3.Database('./test.db');

export const getRowsFromHistorico: () => Promise<Array<any>> = async () => {
    return new Promise ((resolve, reject) => {
            db.all('SELECT * FROM historico', (err: Error, rows: any[]) => {
                if (err){
                    reject(err)
                };
                resolve(rows);
            })
        });
};

I tried to use it in a test file and it worked perfectly. Also tried to import sqlite3 like:

 const sqlite3 = require('sqlite3').verbose();

But the same error continue.

Does somebody know why the database is returning undefined here? Thank you!


问:
Developing a Google Action for Google Assistant with a Google Workspace account
I'm trying to develop a new Google Action. For this I'm using a Google account that is managed with Google Workspace. When I create a completely new Action project (I'm using the Hello World example), I cannot run/use the action in the simulator.

The error message I always see is: "We're sorry, but something went wrong. Please try again".

I did not modify the Hello World example action, so the action itself should be fine. I guess that is has something to do with my Workspace managed Google account.

The response details are here:

{
  "response": "We're sorry, but something went wrong. Please try again.",
  "expectUserResponse": false,
  "conversationToken": "",
  "audioResponse": "",
  "ssmlMarkList": [],
  "visualResponse": {
    "visualElementsList": [
      {
        "displayText": {
          "content": "Sorry, this action is not available in simulation"
        }
      }
    ],
    "suggestionsList": [],
    "agentLogoUrl": ""
  },
  "clientError": 8,
  "is3pResponse": false,
  "clientOperationList": [],
  "projectName": "",
  "renderedHtml": "",
  "previewStartTimeMicros": "",
  "isEmptyResponse": false,
  "agentName": "",
  "servingModelOutdated": false
}

```

I expected that the Action can be tested in the simulator right away.

Body:
I'm trying to develop a new Google Action. For this I'm using a Google account that is managed with Google Workspace. When I create a completely new Action project (I'm using the Hello World example), I cannot run/use the action in the simulator.

The error message I always see is: "We're sorry, but something went wrong. Please try again".

I did not modify the Hello World example action, so the action itself should be fine. I guess that is has something to do with my Workspace managed Google account.

The response details are here:

{
  "response": "We're sorry, but something went wrong. Please try again.",
  "expectUserResponse": false,
  "conversationToken": "",
  "audioResponse": "",
  "ssmlMarkList": [],
  "visualResponse": {
    "visualElementsList": [
      {
        "displayText": {
          "content": "Sorry, this action is not available in simulation"
        }
      }
    ],
    "suggestionsList": [],
    "agentLogoUrl": ""
  },
  "clientError": 8,
  "is3pResponse": false,
  "clientOperationList": [],
  "projectName": "",
  "renderedHtml": "",
  "previewStartTimeMicros": "",
  "isEmptyResponse": false,
  "agentName": "",
  "servingModelOutdated": false
}

I expected that the Action can be tested in the simulator right away.


问:
Add to DeadLetterQueue and retry based on status code in HttpOperationFailedException in camel
My camel route makes a API request which may throw HttpOperationFailedException with status code 400,404,500 etc.. On status code 400 i dont want to retry and also dont want that specific message to be added to dlq.But when exception status code is not 400 i want to retry and also add to dlq.I have a retry handler which is working for other exceptions like IOException,ConnectionException etc..Would like to use the same retry handler.

MyCamelRoute.java

```<code>public class MyCamelRoute extends RouteBuilder {

 @Override
 public void configure() {

  onException(ConnectException.class, UnknownHostException.class,
    ServiceUnavailableException.class, SocketException.class, NoHttpResponseException.class,
   IOException.class)
    .retryWhile(method(RetryHandler.class)).redeliveryDelay("15000").handled(true);//This works

  from("component:queue:MyQueue?concurrentConsumers=10&maxMessagesPerTask=100")
    .description("MyQueue").to("log:jms?showAll=true")
    .errorHandler(deadLetterChannel("component:queue:MyQueue.DLQ")
      .onPrepareFailure(new ExceptionProcessor())
      .maximumRedeliveries(0))
    .setHeader(Exchange.CONTENT_TYPE, constant("application/json"))
    .toD("http://localhost/restUriHere" + "?bridgeEndpoint=true");

 }
}

</code>```

I tried the solution provided here How to handle 4xx(without retry) and 5xx (with retry) exceptions in camel

But issue is, message gets added to dlq directly without even retying for status code like 503 (Service Unavailable),when i add this to MyCamelRoute.java

```<code>onException(HttpOperationFailedException.class)
 .choice()
  .when(simple("${exception.getStatusCode()} == '400'"))
   .throwException(new BadRequestException())
  .endChoice()
 .otherwise()
  .to("component:queue:MyQueue.DLQ")
  .bean(defaultErrorHandler()
   .retryWhile(method(RetryHandler.class))
   .redeliveryDelay(15000)
   .onPrepareFailure(new ExceptionProcessor()))
 .endChoice()
 .end();

</code>```

Body:
My camel route makes a API request which may throw HttpOperationFailedException with status code 400,404,500 etc.. On status code 400 i dont want to retry and also dont want that specific message to be added to dlq.But when exception status code is not 400 i want to retry and also add to dlq.I have a retry handler which is working for other exceptions like IOException,ConnectionException etc..Would like to use the same retry handler.

MyCamelRoute.java

public class MyCamelRoute extends RouteBuilder {

 @Override
 public void configure() {

  onException(ConnectException.class, UnknownHostException.class,
    ServiceUnavailableException.class, SocketException.class, NoHttpResponseException.class,
   IOException.class)
    .retryWhile(method(RetryHandler.class)).redeliveryDelay("15000").handled(true);//This works

  from("component:queue:MyQueue?concurrentConsumers=10&maxMessagesPerTask=100")
    .description("MyQueue").to("log:jms?showAll=true")
    .errorHandler(deadLetterChannel("component:queue:MyQueue.DLQ")
      .onPrepareFailure(new ExceptionProcessor())
      .maximumRedeliveries(0))
    .setHeader(Exchange.CONTENT_TYPE, constant("application/json"))
    .toD("http://localhost/restUriHere" + "?bridgeEndpoint=true");

 }
}

I tried the solution provided here How to handle 4xx(without retry) and 5xx (with retry) exceptions in camel

But issue is, message gets added to dlq directly without even retying for status code like 503 (Service Unavailable),when i add this to MyCamelRoute.java

onException(HttpOperationFailedException.class)
 .choice()
  .when(simple("${exception.getStatusCode()} == '400'"))
   .throwException(new BadRequestException())
  .endChoice()
 .otherwise()
  .to("component:queue:MyQueue.DLQ")
  .bean(defaultErrorHandler()
   .retryWhile(method(RetryHandler.class))
   .redeliveryDelay(15000)
   .onPrepareFailure(new ExceptionProcessor()))
 .endChoice()
 .end();


问:
what's different IEnumerator and IEnumerable?
I want to know difference IEnumerator and IEnumerable. This is a question I got when I was using coroutine. what they have difference? And do they have different uses? It's the biggest question using C# and Unity, but it's hard to understand. I want to learn about that easily.

I found they difference, but I don't understand that's Description.


问:
Why is the Typescript file in my Angular Component not being generated with a Constructor and an Oninit() life-cycle?
Normaly when we do ng generate component new-component , we get a component generated and in the Typescript file we automatically have an OnInit() lifecycle and a constrcutor. I dont know if it  something with the newer version of Angular as i just downloaded it, but it is really stressing me having to implment onInit and adding a constructor in every component.

eg

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
export class TestComponent {

}

</code>```
```<code>import { Component, onInit } from '@angular/core';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
export class TestComponent impelements onInit {
   constructor()  {}
}

</code>```

Body:
Normaly when we do ng generate component new-component , we get a component generated and in the Typescript file we automatically have an OnInit() lifecycle and a constrcutor. I dont know if it  something with the newer version of Angular as i just downloaded it, but it is really stressing me having to implment onInit and adding a constructor in every component.

eg

import { Component } from '@angular/core';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
export class TestComponent {

}

import { Component, onInit } from '@angular/core';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
export class TestComponent impelements onInit {
   constructor()  {}
}


问:
get new value in django admin widget
I am working on creating a widget so clients can easily modify model's Json field in django admin.

Env Info:
django-version: 3.1.14

Before drive into the widget, this is a simplify version of my model:

```<code>class Property(PolymorphicModel):
    """Basic information about property"""
    ...
    address = models.JSONField(blank=True, null=True, default=dict,)
    ...
</code>```

And this how I am declaring the form:

```<code>class PropertyForm(forms.ModelForm):
    class Meta:
        model = Property
        fields = [
            "address",
          ]
        widgets = {
            'address': JSONEditorWidget(),
        }
</code>```

I've already manage to convert json file into django admin inputs by using the following code:

```<code>class JSONEditorWidget(forms.widgets.Input):
    def as_field(self, name, key, value):
        """ Render key, value as field """
        new_name = name + '__' + key
        self.attrs = self.build_attrs({new_name:key})
        self.attrs['value'] = utils.encoding.force_text(value)
        return u'%s: <input%s />' % (new_name, forms.utils.flatatt(self.attrs))

    def to_fields(self, name, json_obj):
        """Get list of rendered fields for json object"""
        inputs = []
        for key, value in json_obj.items():
            inputs.append(self.as_field(name, key, value))
        return inputs

    def value_from_datadict(self, data, files, name):
        """I've been trying to get new values in this function but nothing successful"""

        return json.dumps(prev_dict)

    def render(self, name, value, attrs=None, renderer = None):
        # TODO: handle empty value (render text field?)

        if value is None or value == '':
            value = '{}'

        json_obj = json.loads(value)
        inputs = self.to_fields(name, json_obj)

        # render json as well
        inputs.append(value)

        return utils.safestring.mark_safe(u"<br />".join(inputs))
</code>```

with this I could go from this:

To this:

My problem now is to catch the new values when user clicks on save/save and continue, so I can convert them into json file to save new records on postgres.

Ive tried with the function value_fromdatadict()  but couldn't manage a way to get new values in the input box...

If anyone can helps me I will be so glad, I've been dealing with this a while and this is driving me crazy

Title: get new value in django admin widget

Body:
I am working on creating a widget so clients can easily modify model's Json field in django admin.

Env Info:
django-version: 3.1.14

Before drive into the widget, this is a simplify version of my model:

class Property(PolymorphicModel):
    """Basic information about property"""
    ...
    address = models.JSONField(blank=True, null=True, default=dict,)
    ...

And this how I am declaring the form:

class PropertyForm(forms.ModelForm):
    class Meta:
        model = Property
        fields = [
            "address",
          ]
        widgets = {
            'address': JSONEditorWidget(),
        }

I've already manage to convert json file into django admin inputs by using the following code:

class JSONEditorWidget(forms.widgets.Input):
    def as_field(self, name, key, value):
        """ Render key, value as field """
        new_name = name + '__' + key
        self.attrs = self.build_attrs({new_name:key})
        self.attrs['value'] = utils.encoding.force_text(value)
        return u'%s: <input%s />' % (new_name, forms.utils.flatatt(self.attrs))

    def to_fields(self, name, json_obj):
        """Get list of rendered fields for json object"""
        inputs = []
        for key, value in json_obj.items():
            inputs.append(self.as_field(name, key, value))
        return inputs

    def value_from_datadict(self, data, files, name):
        """I've been trying to get new values in this function but nothing successful"""

        return json.dumps(prev_dict)

    def render(self, name, value, attrs=None, renderer = None):
        # TODO: handle empty value (render text field?)

        if value is None or value == '':
            value = '{}'

        json_obj = json.loads(value)
        inputs = self.to_fields(name, json_obj)

        # render json as well
        inputs.append(value)

        return utils.safestring.mark_safe(u"
".join(inputs))

with this I could go from this:

To this:

My problem now is to catch the new values when user clicks on save/save and continue, so I can convert them into json file to save new records on postgres.

Ive tried with the function value_fromdatadict()  but couldn't manage a way to get new values in the input box...

If anyone can helps me I will be so glad, I've been dealing with this a while and this is driving me crazy


问:
For a trigger program in oracle responsys how can we stop sending to creatives in program when we reach/send max of 500 records
For a trigger program in oracle responsys how can we stop sending to creatives in program when we reach/send max of 500 records.

I'm not sure if count switch with batch of 365 days works.


问:
Combining Boolean operators (TRUE/FALSE) from an R data frame with continuous data to produce a box plot using categories of the true and false
I would like to create a histogram that uses true and false variables from a data frame to create categories, and then plot them against continuous variables.</p>
```<code>plot(data3$eigen_metric ~ groups)
Error in (function (formula, data = NULL, subset = NULL, na.action = na.fail,  :
  invalid type (list) for variable 'groups
</code>```

Body:
I would like to create a histogram that uses true and false variables from a data frame to create categories, and then plot them against continuous variables.

plot(data3$eigen_metric ~ groups)
Error in (function (formula, data = NULL, subset = NULL, na.action = na.fail,  :
  invalid type (list) for variable 'groups


问:
How to do maven build and run make command inside container
I need to run Maven build inside container and afterwards I need to run make command.

For executing Maven, I did the following inside dockerfile

```<code>FROM maven:3.8.1-adoptopenjdk-11 AS build
COPY src /usr/src/app/src
COPY pom.xml /usr/src/app

RUN mvn -f /usr/src/app/pom.xml clean package
</code>```

After maven execution, some jar files are generated, which is needed to run make command (used in make file)

Now my question is how to get docker image for make, and how do I use it in same dockerfile? I tried to find docker image for make but didn't get it directly in dockerhub.

I'm familiar with building java code but not with building C/C++ code with make. Any help would be appreciated.

Body:
I need to run Maven build inside container and afterwards I need to run make command.

For executing Maven, I did the following inside dockerfile

FROM maven:3.8.1-adoptopenjdk-11 AS build
COPY src /usr/src/app/src
COPY pom.xml /usr/src/app

RUN mvn -f /usr/src/app/pom.xml clean package

After maven execution, some jar files are generated, which is needed to run make command (used in make file)

Now my question is how to get docker image for make, and how do I use it in same dockerfile? I tried to find docker image for make but didn't get it directly in dockerhub.

I'm familiar with building java code but not with building C/C++ code with make. Any help would be appreciated.


问:
Supporting different variations for reading file header (see Update)
I am trying read the header for a PGM file, which I found could have the follow variations:

```<code>P2
255 255
255
</code>```

or

```<code>P2
255 255 255
</code>```

or

```<code>P2 255 255 255
</code>```

right now, I got this code:

```<code>  std::ifstream file(file_name);
  std::string line_one, line_two, line_three, line_pixels;

  char magicNumber;
  int width, height;

  while(getline(file, line_one)) {
    if(line_one.size() > 0 && line_one.at(0) != '#') {
      magicNumber = line_one.at(1);
      break;
    }
  }

  while(getline(file, line_two)) {
    if(line_two.size() > 0 && line_two.at(0) != '#') {
      std::stringstream ss(line_two);
      ss >> width >> height;
      break;
    }
  }

  while(getline(file, line_three)) {
    if(line_three.size() > 0 && line_three.at(0) != '#') {
      this->max_value = stoi(line_three);
      break;
    }
  }
</code>```

which works fine for the first variation, but not so much for the other two. I think this could be solve by checking if the end of line was reached after each 'while'/ 'getline' blocks above. Am i right? If so, how to do that?

UPDATE

I try this code, but it is not skipping the lines with comments (starting with #):

```<code>  std::ifstream file(file_name);
  std::string line_one, line_two, line_three, line_pixels;

  std::string magicNumber;
  int width, height;

  file >> magicNumber;

  if(file.peek() == '#') {
    std::string comment;
    getline(file, comment);
  }

  file >> width;

  if(file.peek() == '#') {
    std::string comment;
    getline(file, comment);
  }

  file >> height;

  if(file.peek() == '#') {
    std::string comment;
    getline(file, comment);
  }

  file >> this->max_value;

  if(file.peek() == '#') {
    std::string comment;
    getline(file, comment);
  }
</code>```

Body:
I am trying read the header for a PGM file, which I found could have the follow variations:

P2
255 255
255

or

P2
255 255 255

or

P2 255 255 255

right now, I got this code:

  std::ifstream file(file_name);
  std::string line_one, line_two, line_three, line_pixels;

  char magicNumber;
  int width, height;

  while(getline(file, line_one)) {
    if(line_one.size() > 0 && line_one.at(0) != '#') {
      magicNumber = line_one.at(1);
      break;
    }
  }

  while(getline(file, line_two)) {
    if(line_two.size() > 0 && line_two.at(0) != '#') {
      std::stringstream ss(line_two);
      ss >> width >> height;
      break;
    }
  }

  while(getline(file, line_three)) {
    if(line_three.size() > 0 && line_three.at(0) != '#') {
      this->max_value = stoi(line_three);
      break;
    }
  }

which works fine for the first variation, but not so much for the other two. I think this could be solve by checking if the end of line was reached after each 'while'/ 'getline' blocks above. Am i right? If so, how to do that?

UPDATE

I try this code, but it is not skipping the lines with comments (starting with #):

  std::ifstream file(file_name);
  std::string line_one, line_two, line_three, line_pixels;

  std::string magicNumber;
  int width, height;

  file >> magicNumber;

  if(file.peek() == '#') {
    std::string comment;
    getline(file, comment);
  }

  file >> width;

  if(file.peek() == '#') {
    std::string comment;
    getline(file, comment);
  }

  file >> height;

  if(file.peek() == '#') {
    std::string comment;
    getline(file, comment);
  }

  file >> this->max_value;

  if(file.peek() == '#') {
    std::string comment;
    getline(file, comment);
  }


问:
Keep only latest records by unique column in table
I have a question about delta tables  \ delta change data feed \ upsert

I have a table that stores all history of states (main), I use ZORDER by uniq column on it, and I retrieve results for 2s with WHERE clause BY (uniq, date) from the table.

During the day I receive many messages from the stream and add them (via append) into the delta table (main), each night I recalculate ZORDER for the main table
—

I would like to create another table that keeps only the latest records by a unique column in the table. I need this table for decreasing the latency of retrieving data.

Possible solutions:

Solution with DENSE_RANK by date (or QUALIFY), we grab from (main) only fresh uniq и date.

Each time we recreate the table, in that case, I lose a lot of CPU time and lose ZORDER on the table, in a result this new small table works worse than the bigger (main) with ZORDER.

Upsert (merge)

I tried but looks like it doesn't work as I want it to.
Hardly to say, it appends or deletes the data from the batch, not from the (main) table, and that records that haven't been matched are not deleted.

Delta Change Data Feed

For this approach, I need to store the full state in a batch, but currently batch is just a new portion of the data.

I start thinking about that for the latest data I need to store it somewhere else (in mem KV storage, Redis for example)

Partition by uniq
 works worse than ZORDER by uniq column. So maybe I need to drop uniq partition and add a new uniq from the batch?

Structure of the (main):

```<code>date | uniq | key | value
2022-12-13 | 1 | "key1" | 1
2022-12-13 | 1 | "key55" | 5
2022-12-13 | 2 | "key105" | 3
</code>```

Mini-batches like this one:

```<code>date | uniq | key | value
2022-12-14 | 1 | "key3" | 0
2022-12-14 | 1 | "key4" | 1
2022-12-14 | 1 | "key5" | 0
2022-12-14 | 1 | "key6" | 1
</code>```

Right now after insertion (batch) to (main), it will be:

```<code>date | uniq | key | value
2022-12-13 | 1 | "key1" | 1
2022-12-13 | 1 | "key55" | 5
2022-12-13 | 2 | "key105" | 3
2022-12-14 | 1 | "key3" | 0
2022-12-14 | 1 | "key4" | 1
2022-12-14 | 1 | "key5" | 0
2022-12-14 | 1 | "key6" | 1
</code>```

I want to have a such table (latest):

```<code>date | uniq | key | value
2022-12-13  | 2 | "key105" | 3
2022-12-14 | 1 | "key3" | 0
2022-12-14 | 1 | "key4" | 1
2022-12-14 | 1 | "key5" | 0
2022-12-14 | 1 | "key6" | 1
</code>```

ETL:

raw -> AutoLoader -> silver (with append every batch, night OPTIMIZE ZORDER)

Want to create another table (gold) that will keep only the latest records by uniq column.

If we add a new batch (new state), I expect to see only these new values per uniq in the gold table. So with every new batch, it should be triggered and recalculated somehow.
Or I should forget about the idea, and instead of that, save all the data in in-mem KV? (Redis)

Body:
I have a question about delta tables  \ delta change data feed \ upsert

I have a table that stores all history of states (main), I use ZORDER by uniq column on it, and I retrieve results for 2s with WHERE clause BY (uniq, date) from the table.

During the day I receive many messages from the stream and add them (via append) into the delta table (main), each night I recalculate ZORDER for the main table
—

I would like to create another table that keeps only the latest records by a unique column in the table. I need this table for decreasing the latency of retrieving data.

Possible solutions:

Solution with DENSE_RANK by date (or QUALIFY), we grab from (main) only fresh uniq и date.

Each time we recreate the table, in that case, I lose a lot of CPU time and lose ZORDER on the table, in a result this new small table works worse than the bigger (main) with ZORDER.

Upsert (merge)

I tried but looks like it doesn't work as I want it to.
Hardly to say, it appends or deletes the data from the batch, not from the (main) table, and that records that haven't been matched are not deleted.

Delta Change Data Feed

For this approach, I need to store the full state in a batch, but currently batch is just a new portion of the data.

I start thinking about that for the latest data I need to store it somewhere else (in mem KV storage, Redis for example)

Partition by uniq
 works worse than ZORDER by uniq column. So maybe I need to drop uniq partition and add a new uniq from the batch?

Structure of the (main):

date | uniq | key | value
2022-12-13 | 1 | "key1" | 1
2022-12-13 | 1 | "key55" | 5
2022-12-13 | 2 | "key105" | 3

Mini-batches like this one:

date | uniq | key | value
2022-12-14 | 1 | "key3" | 0
2022-12-14 | 1 | "key4" | 1
2022-12-14 | 1 | "key5" | 0
2022-12-14 | 1 | "key6" | 1

Right now after insertion (batch) to (main), it will be:

date | uniq | key | value
2022-12-13 | 1 | "key1" | 1
2022-12-13 | 1 | "key55" | 5
2022-12-13 | 2 | "key105" | 3
2022-12-14 | 1 | "key3" | 0
2022-12-14 | 1 | "key4" | 1
2022-12-14 | 1 | "key5" | 0
2022-12-14 | 1 | "key6" | 1

I want to have a such table (latest):

date | uniq | key | value
2022-12-13  | 2 | "key105" | 3
2022-12-14 | 1 | "key3" | 0
2022-12-14 | 1 | "key4" | 1
2022-12-14 | 1 | "key5" | 0
2022-12-14 | 1 | "key6" | 1

ETL:

raw -> AutoLoader -> silver (with append every batch, night OPTIMIZE ZORDER)

Want to create another table (gold) that will keep only the latest records by uniq column.

If we add a new batch (new state), I expect to see only these new values per uniq in the gold table. So with every new batch, it should be triggered and recalculated somehow.
Or I should forget about the idea, and instead of that, save all the data in in-mem KV? (Redis)


问:
Can I Wrap specific components with Redux store only
I am building a social media app with
React + Redux and I am currently building the profile page. I have noticed that I will need to share same data in multiple components but the thing is that I think it is not a good idea to make a global redux slice for the profile page specifically, so I am a bit confused of what should I do. Should I create a a global slice? or should I go for props sharing data? also if I used a global redux slice, I don't want the data to be stored if the user is not in the profile page, I want to re-fetch this data every time the user enters the profile page, so what is the best way to achieve that?

Thanks in advance


问:
Can I get the image as a variable for a condition in gitLab CI
I have a product and many projects in different versions and a global gitlab-ci.yml that is just linked. Some projects are build with an old Java version (image is overwritten) and some with the new one. Depending on which version is used I would like to add a build parameter using a rule.

Is there a way to query the used image or will I have to use a variable and set the image according to that variable (which would mean I have to update a lot of repositories)

I tried to treat image as a variable but didn't get anywhere.


问:
where can I put an array in gui joption
well I'm new to this whole programing thing my question is where can I put the array in GUI?

How do I do a user input array that accept how many people,names,get a deduction and gross pay?

Title: where can I put an array in gui joption


问:
Does Opencv support lossless compression for jpeg
Opencv imwrite lossy compress image into jpeg by set IMWRITE_JPEG_QUALITY to 0-100 to adjust the rate-distortion. It seems that image is still lossy compressed even if IMWRITE_JPEG_QUALITY is set to 100. Does Opencv support lossless compression for jpeg?


问:
Getting a type error when trying to run this python script
Getting this error below. How can I fix it?

```<code>1 frames
<ipython-input-7-3be77148eaa3> in create_training_data(data)
     39     # Loop through the data and retrieve relevant info
     40     for i in range(len(data['energy'])):
---> 41         X[i][0] = data['energy'][i]
     42         X[i][1] = data['chroma_stft'][i]
     43         X[i][2] = data['spectral_contrast'][i]

TypeError: 'numpy.float64' object does not support item assignment
</code>```

I am trying to build this music generator. But getting the error mentioned above. Can someone please have a look at the code and let me know what to update to make it all work?

The full code is provided below. Completing a project with deadline close so some help would really be appreciated.

```<code># importing necessary libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import sklearn
import librosa

# Gathering user's input
# Gather the tempo, rhythm and tone of the song
tempo = int(input("What tempo would you like the song to have? (BPM)"))
rhythm = input("What rhythm would you like the song to have? (e.g. 4/4) ")
tone = input("What is the 'feel' or tone of the song? (e.g. cheerful, melancholy)")

# Defining some Helper Functions

# File_Retreival
# This function will retrieve our dataset with audio information
def file_retreival(file):
    # Using Librosa to import the audio file
    audio, sample_rate = librosa.load(file)

    # Defining various results from the audio source
    results = {
        "tempo": librosa.beat.tempo(audio, sample_rate),
        "energy": librosa.feature.rms(audio),
        "chroma_stft": librosa.feature.chroma_stft(audio),
        "spectral_contrast": librosa.feature.spectral_contrast(audio),
        "tonnetz": librosa.feature.tonnetz(y=librosa.effects.harmonic(audio))
    }
    return results

# Create Training Data
# This function will prepare our data for training
def create_training_data(data):
    # Retrieve the silhouette information
    data_shape = np.ravel(data['chroma_stft']).shape
    # Create an empty list to store training data
    X = np.zeros(data_shape[0])
    # Loop through the data and retrieve relevant info
    for i in range(len(data['energy'])):
        X[i][0] = data['energy'][i]
        X[i][1] = data['chroma_stft'][i]
        X[i][2] = data['spectral_contrast'][i]
        X[i][3] = data['tonnetz'][i]
        X[i][4] = data['tempo']
    return X

# Build Model
# This function will build our ML model
def build_model(X_train, y_train):
    from sklearn.ensemble import RandomForestClassifier
    # Create the model
    model = RandomForestClassifier(n_estimators=100)
    # Train the model using X_train and y_train
    model.fit(X_train, y_train)
    # Return the model
    return model

# Generate Music
# This function will generate the music using ML
def generate_music(model, X):
    # Generate predictions using X
    pred = model.predict(X)
    # Return the predictions
    return pred

# Create Music
# This function will create the music according to the tempo and user-given parameters
def create_music(pred, sample_rate, tempo, rhythm, tone):
    # Import necessary libraries
    from mido import Message, MidiFile
    from mido.midifiles import MidiTrack
    from mido.messages import note_on, note_off
    # Create a new MIDI file
    mid = MidiFile()
    # Create a track
    track = MidiTrack()
    mid.tracks.append(track)
    # Set the tempo
    track.append(Message("set_tempo", tempo=tempo))
    # Set the time signature
    track.append(Message("time_signature", numerator=rhythm))
    # Iterate through the predictions and create the notes
    for i in range(len(pred)):
        duration = pred[i][0]
        # Note on message
        track.append(Message("note_on", note=pred[i][1], velocity=127, time=0))
        # Note off message
        track.append(Message("note_off", note=pred[i][1], velocity=127, time=duration))
    # Set the tone according to the user given parameters
    track.append(Message("control_change", data=[2,tone]))
    # Save the MIDI file
    mid.save("generated_music.mid")

# Main function
# This function will execute the program and generate the music
def main():
    # Gather the file and retrieve the data
    file = "audio.mp3"
    data = file_retreival(file)
    # Create the training data
    X_train = create_training_data(data)
    # Create the labels (in this case, empty labels as we just want to generate music)
    y_train = np.zeros(X_train.shape[0])
    # Build the model
    model = build_model(X_train, y_train)
    # Generate the music predictions
    music_pred = generate_music(model, X_train)
    # Create the music
    create_music(music_pred, data['sample_rate'], tempo, rhythm, tone)

# Execute the main function
main()
</code>```

Body:
Getting this error below. How can I fix it?

1 frames
<ipython-input-7-3be77148eaa3> in create_training_data(data)
     39     # Loop through the data and retrieve relevant info
     40     for i in range(len(data['energy'])):
---> 41         X[i][0] = data['energy'][i]
     42         X[i][1] = data['chroma_stft'][i]
     43         X[i][2] = data['spectral_contrast'][i]

TypeError: 'numpy.float64' object does not support item assignment

I am trying to build this music generator. But getting the error mentioned above. Can someone please have a look at the code and let me know what to update to make it all work?

The full code is provided below. Completing a project with deadline close so some help would really be appreciated.

# importing necessary libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import sklearn
import librosa

# Gathering user's input
# Gather the tempo, rhythm and tone of the song
tempo = int(input("What tempo would you like the song to have? (BPM)"))
rhythm = input("What rhythm would you like the song to have? (e.g. 4/4) ")
tone = input("What is the 'feel' or tone of the song? (e.g. cheerful, melancholy)")

# Defining some Helper Functions

# File_Retreival
# This function will retrieve our dataset with audio information
def file_retreival(file):
    # Using Librosa to import the audio file
    audio, sample_rate = librosa.load(file)

    # Defining various results from the audio source
    results = {
        "tempo": librosa.beat.tempo(audio, sample_rate),
        "energy": librosa.feature.rms(audio),
        "chroma_stft": librosa.feature.chroma_stft(audio),
        "spectral_contrast": librosa.feature.spectral_contrast(audio),
        "tonnetz": librosa.feature.tonnetz(y=librosa.effects.harmonic(audio))
    }
    return results

# Create Training Data
# This function will prepare our data for training
def create_training_data(data):
    # Retrieve the silhouette information
    data_shape = np.ravel(data['chroma_stft']).shape
    # Create an empty list to store training data
    X = np.zeros(data_shape[0])
    # Loop through the data and retrieve relevant info
    for i in range(len(data['energy'])):
        X[i][0] = data['energy'][i]
        X[i][1] = data['chroma_stft'][i]
        X[i][2] = data['spectral_contrast'][i]
        X[i][3] = data['tonnetz'][i]
        X[i][4] = data['tempo']
    return X

# Build Model
# This function will build our ML model
def build_model(X_train, y_train):
    from sklearn.ensemble import RandomForestClassifier
    # Create the model
    model = RandomForestClassifier(n_estimators=100)
    # Train the model using X_train and y_train
    model.fit(X_train, y_train)
    # Return the model
    return model

# Generate Music
# This function will generate the music using ML
def generate_music(model, X):
    # Generate predictions using X
    pred = model.predict(X)
    # Return the predictions
    return pred

# Create Music
# This function will create the music according to the tempo and user-given parameters
def create_music(pred, sample_rate, tempo, rhythm, tone):
    # Import necessary libraries
    from mido import Message, MidiFile
    from mido.midifiles import MidiTrack
    from mido.messages import note_on, note_off
    # Create a new MIDI file
    mid = MidiFile()
    # Create a track
    track = MidiTrack()
    mid.tracks.append(track)
    # Set the tempo
    track.append(Message("set_tempo", tempo=tempo))
    # Set the time signature
    track.append(Message("time_signature", numerator=rhythm))
    # Iterate through the predictions and create the notes
    for i in range(len(pred)):
        duration = pred[i][0]
        # Note on message
        track.append(Message("note_on", note=pred[i][1], velocity=127, time=0))
        # Note off message
        track.append(Message("note_off", note=pred[i][1], velocity=127, time=duration))
    # Set the tone according to the user given parameters
    track.append(Message("control_change", data=[2,tone]))
    # Save the MIDI file
    mid.save("generated_music.mid")

# Main function
# This function will execute the program and generate the music
def main():
    # Gather the file and retrieve the data
    file = "audio.mp3"
    data = file_retreival(file)
    # Create the training data
    X_train = create_training_data(data)
    # Create the labels (in this case, empty labels as we just want to generate music)
    y_train = np.zeros(X_train.shape[0])
    # Build the model
    model = build_model(X_train, y_train)
    # Generate the music predictions
    music_pred = generate_music(model, X_train)
    # Create the music
    create_music(music_pred, data['sample_rate'], tempo, rhythm, tone)

# Execute the main function
main()


问:
Dealing with n-dimensional lists and creating a dataframe mapping each values with its correspondence file
i need to extract my f0 values for each participant and each participant has multiple utterances (audio files) which is unequal for each participant..
i need to create a dataframe to export it later as csv file. in this dataframe i want to represent the filename (or fileID) of participant, utterancID, then the f0 values (each utterance has 20 values as list)
here you can see how i created the list and the output:

```<code>import glob, os
source_folder = '/content/drive/MyDrive/utterances/TD'
folders = os.listdir(source_folder)
TD = []
li_participant = []

for folder in folders:
  audios_path = os.path.join(source_folder,folder)
  audios = os.listdir(audios_path)
  # print(audios)
  li_participant.append(folder)

  li_utt = []
  patient = []
  for audio in audios:
    audio_path = os.path.join(source_folder,folder,audio)

    sound = parselmouth.Sound(audio_path)
    Audio(data=sound.values, rate=sound.sampling_frequency)
    pitch_val = sound.to_pitch()
    f0Values = f0_values(pitch_val)
    twenty_f0 = f0_normed(f0Values, 20)
    li_utt.append(audio)
    patient.append(twenty_f0)

  TD.append(patient)
#   # break

li_participant
li_utt
TD
</code>```

i was trying to map each participant with its file name and utterance ID and since they have unequal utterence number to fill the empty ones with 'nan'

```<code>df= pd.DataFrame({'li_participant': pd.Series(li_participant), 'li_utt': pd.Series(li_utt),'TD': pd.Series(TD)})
df
</code>```

i want my data to look like that, as to have the 1st column having the participantID, 2nd column the utterance id, then the f0 values (20 values) for each utterance :

Body:
i need to extract my f0 values for each participant and each participant has multiple utterances (audio files) which is unequal for each participant..
i need to create a dataframe to export it later as csv file. in this dataframe i want to represent the filename (or fileID) of participant, utterancID, then the f0 values (each utterance has 20 values as list)
here you can see how i created the list and the output:

import glob, os
source_folder = '/content/drive/MyDrive/utterances/TD'
folders = os.listdir(source_folder)
TD = []
li_participant = []

for folder in folders:
  audios_path = os.path.join(source_folder,folder)
  audios = os.listdir(audios_path)
  # print(audios)
  li_participant.append(folder)

  li_utt = []
  patient = []
  for audio in audios:
    audio_path = os.path.join(source_folder,folder,audio)

    sound = parselmouth.Sound(audio_path)
    Audio(data=sound.values, rate=sound.sampling_frequency)
    pitch_val = sound.to_pitch()
    f0Values = f0_values(pitch_val)
    twenty_f0 = f0_normed(f0Values, 20)
    li_utt.append(audio)
    patient.append(twenty_f0)

  TD.append(patient)
#   # break

li_participant
li_utt
TD

i was trying to map each participant with its file name and utterance ID and since they have unequal utterence number to fill the empty ones with 'nan'

df= pd.DataFrame({'li_participant': pd.Series(li_participant), 'li_utt': pd.Series(li_utt),'TD': pd.Series(TD)})
df

i want my data to look like that, as to have the 1st column having the participantID, 2nd column the utterance id, then the f0 values (20 values) for each utterance :


问:
Nagios Auto Rescheduling Feature Default Values Wrong?
I am trying to understand how the auto rescheduling logic is supposed to work.

The recommended values in nagios.cfg are:

```<code>auto_reschedule_checks=1
auto_rescheduling_interval=30
auto_rescheduling_window=45
</code>```

Supposedly this is after they realized the default values (same as above but with window=180) had the potential to have checks that never actually get executed (See https://support.nagios.com/kb/print-19.html).

But.. How are these new values any different?

How I understand it, every 30sec, it takes the next 45sec of checks, finds checks that overlap, and reschedules those evenly across the 45sec.

Isnt it possible for a check to indefinitely get rescheduled into that last 15 seconds of the 45sec window?

Am I missing something? Do rescheduled checks get an elevated priority so they arent rescheduled again? Reading through the code, it doesnt appear they are given any special treatment.

Seems to me that the only way to prevent that is for the interval and window to be the same.

Which means maybe a couple checks occurring right at each 30sec transition may go unnoticed,
but Id rather that than what I am presuming the behavior is with the "recommended" interval=30sec , window=45sec.

Any insights would be helpful!

Body:
I am trying to understand how the auto rescheduling logic is supposed to work.

The recommended values in nagios.cfg are:

auto_reschedule_checks=1
auto_rescheduling_interval=30
auto_rescheduling_window=45

Supposedly this is after they realized the default values (same as above but with window=180) had the potential to have checks that never actually get executed (See https://support.nagios.com/kb/print-19.html).

But.. How are these new values any different?

How I understand it, every 30sec, it takes the next 45sec of checks, finds checks that overlap, and reschedules those evenly across the 45sec.

Isnt it possible for a check to indefinitely get rescheduled into that last 15 seconds of the 45sec window?

Am I missing something? Do rescheduled checks get an elevated priority so they arent rescheduled again? Reading through the code, it doesnt appear they are given any special treatment.

Seems to me that the only way to prevent that is for the interval and window to be the same.

Which means maybe a couple checks occurring right at each 30sec transition may go unnoticed,
but Id rather that than what I am presuming the behavior is with the "recommended" interval=30sec , window=45sec.

Any insights would be helpful!


问:
AWS Elastic Beanstalk deployment fails (file not found) from new laptop
I have an Elastic Beanstalk environment set up, and used to deploy to it either manually from my Windows laptop (eb deploy [env]) or through my CD pipeline.

Now I have a new Windows laptop, and while I can still deploy from the old one or via the CD pipeline, any eb deploy [env] command from my new laptop always fails with an error saying that my celery.sh post-deploy hook does not exist (which is obviously false).

I went through other related answers, and am reasonably sure it's neither a permission issue (chmod already done on the file) nor a LF/CRLF issue (which in any case I think it's not possible, since the app. is deployed via Git, that always converts it to the Unix style). I am also sure the issue is related to only this specific file (not a matter of client authorisation or whatsoever), because I'm perfectly able to deploy from my new laptop if I just remove this file from my app.!

Here below my config. file tree:

```<code>Root_folder
|
|__ .ebxtensions
|  |__ django.config
|  |__ logging.config
|
|__ .elasticbeanstalk
|  |__ config.yml
|
|__ .platform
|  |__ hooks
|  |  |__ postdeploy
|  |     |__ celery.sh
|  |__ nginx
|  |  |__ conf.d
|  |    |__ config.conf
|
|__ app_folder1
|__ app_folder2...
</code>```

And here below the lines from the eb-engine log showing the error:

```<code>2022/12/13 16:46:03.789782 [INFO] Executing instruction: RunAppDeployPostDeployHooks
2022/12/13 16:46:03.789795 [INFO] Executing platform hooks in .platform/hooks/postdeploy/
2022/12/13 16:46:03.789857 [INFO] Following scripts will be executed in order: [celery.sh]
2022/12/13 16:46:03.789866 [INFO] Try add execution permission
2022/12/13 16:46:03.789873 [INFO] Running script: .platform/hooks/postdeploy/celery.sh
2022/12/13 16:46:03.791226 [ERROR] An error occurred during execution of command [app-deploy] - [RunAppDeployPostDeployHooks]. Stop running the command. Error: Command .platform/hooks/postdeploy/celery.sh failed with error fork/exec .platform/hooks/postdeploy/celery.sh: no such file or directory
</code>```

Body:
I have an Elastic Beanstalk environment set up, and used to deploy to it either manually from my Windows laptop (eb deploy [env]) or through my CD pipeline.

Now I have a new Windows laptop, and while I can still deploy from the old one or via the CD pipeline, any eb deploy [env] command from my new laptop always fails with an error saying that my celery.sh post-deploy hook does not exist (which is obviously false).

I went through other related answers, and am reasonably sure it's neither a permission issue (chmod already done on the file) nor a LF/CRLF issue (which in any case I think it's not possible, since the app. is deployed via Git, that always converts it to the Unix style). I am also sure the issue is related to only this specific file (not a matter of client authorisation or whatsoever), because I'm perfectly able to deploy from my new laptop if I just remove this file from my app.!

Here below my config. file tree:

Root_folder
|
|__ .ebxtensions
|  |__ django.config
|  |__ logging.config
|
|__ .elasticbeanstalk
|  |__ config.yml
|
|__ .platform
|  |__ hooks
|  |  |__ postdeploy
|  |     |__ celery.sh
|  |__ nginx
|  |  |__ conf.d
|  |    |__ config.conf
|
|__ app_folder1
|__ app_folder2...

And here below the lines from the eb-engine log showing the error:

2022/12/13 16:46:03.789782 [INFO] Executing instruction: RunAppDeployPostDeployHooks
2022/12/13 16:46:03.789795 [INFO] Executing platform hooks in .platform/hooks/postdeploy/
2022/12/13 16:46:03.789857 [INFO] Following scripts will be executed in order: [celery.sh]
2022/12/13 16:46:03.789866 [INFO] Try add execution permission
2022/12/13 16:46:03.789873 [INFO] Running script: .platform/hooks/postdeploy/celery.sh
2022/12/13 16:46:03.791226 [ERROR] An error occurred during execution of command [app-deploy] - [RunAppDeployPostDeployHooks]. Stop running the command. Error: Command .platform/hooks/postdeploy/celery.sh failed with error fork/exec .platform/hooks/postdeploy/celery.sh: no such file or directory


问:
i want to count firestore collections that have a same field value and count them in a table?
i have a list of users in the firestore
each user have his own Country
i want to count the number of users that have a same country and list them in a table like this

for example i have 3 users have Tunisia as a country, 1 user have Germany,

Country Name
Total users

Tunisia
3

Germany
1

my flutter code:

```<code>child: Container(
      width: double.infinity,
      height: 500,
      decoration: BoxDecoration(),
      child: DataTable(
        columns: [
          DataColumn(label: Text(
              'Country',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)
          )),
          DataColumn(label: Text(
              'Total',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)
          )),
        ],
        rows: [
          DataRow(cells: [
            DataCell(Text('Stephen')),
            DataCell(Text('Actor')),
          ]),
          DataRow(cells: [
            DataCell(Text('John')),
            DataCell(Text('Student')),
          ]),
        ],
      ),
    ),
</code>```

Body:
i have a list of users in the firestore
each user have his own Country
i want to count the number of users that have a same country and list them in a table like this

for example i have 3 users have Tunisia as a country, 1 user have Germany,

Country Name
Total users

Tunisia
3

Germany
1

my flutter code:

child: Container(
      width: double.infinity,
      height: 500,
      decoration: BoxDecoration(),
      child: DataTable(
        columns: [
          DataColumn(label: Text(
              'Country',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)
          )),
          DataColumn(label: Text(
              'Total',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)
          )),
        ],
        rows: [
          DataRow(cells: [
            DataCell(Text('Stephen')),
            DataCell(Text('Actor')),
          ]),
          DataRow(cells: [
            DataCell(Text('John')),
            DataCell(Text('Student')),
          ]),
        ],
      ),
    ),