问:
Converting BitArray to Binary
I'm trying to make a simple compressor (I think the algorithm is done) but when trying to get read the bytes from a file and converting them to binary i'm not able to do it.

I have a BitArray that should be referring to a file 'test.png'

```<code>b = BitArray(bytes=open('test.png', 'rb').read())
</code>```

And when I print b I get:

```<code>0x89504e470d0a1a0a0000000d494844520000031000000369080200000014b648a3000000017352474200aece1ce90000000467414d410000b18f0bfc6105000000097048597300000ec300000ec301c76fa86400008e9149444154785eeddd07781445e3c771ae25744215044445b0e3abd81b8205ebabd87dedbdf7de...
</code>```

I'm trying to get the binary value as following:

```<code>b = bin(int(str(b), 16))
print(b)
</code>```

But I get the following error:

ValueError: invalid literal for int() with base 16

I'm wondering if this is because the number is very large?

Thanks in advance!

Title: Converting BitArray to Binary

Body:
I'm trying to make a simple compressor (I think the algorithm is done) but when trying to get read the bytes from a file and converting them to binary i'm not able to do it.

I have a BitArray that should be referring to a file 'test.png'

b = BitArray(bytes=open('test.png', 'rb').read())

And when I print b I get:

0x89504e470d0a1a0a0000000d494844520000031000000369080200000014b648a3000000017352474200aece1ce90000000467414d410000b18f0bfc6105000000097048597300000ec300000ec301c76fa86400008e9149444154785eeddd07781445e3c771ae25744215044445b0e3abd81b8205ebabd87dedbdf7de...

I'm trying to get the binary value as following:

b = bin(int(str(b), 16))
print(b)

But I get the following error:

ValueError: invalid literal for int() with base 16

I'm wondering if this is because the number is very large?

Thanks in advance!


来源: stackexchange

问:
How to prevent CloudFormation stack resource being silently modified by another stack?
We have a CFN stack with a S3 BucketPolicy resource, however some other stacks within the same account also have S3 BucketPolicy defined for the same S3 bucket. How to prevent stack resource being modified silently by other CFN stacks?</p>

ContentLicense: CC BY-SA 4.0


问:
Determining Possible LCP candidate
In our website we have search page which shows records in rows with 4 products in one row(desktop). And we have top only top row in view port. All these images have same render size and their intrinsic sizes are bigger than render sizes. That means for LCP calculation they all have equal weight.

But when I run performance insights tab, the results are not consistent. The lcp image is switching between these 4 images in first row for different URLs.

Any idea how google calculates LCP in this case ?

We are thinking about adding high fetch priority to possible LCP image, we are worried not sure if we should make all four images ‘high’ fetch priority or only one if we can determine what would be lcp candidate. Also would it matter if adding four images as high fetch priority or one? considering HTTP2 can handle parallel calls without network bottleneck?

Thanks!

Title: Determining Possible LCP candidate


问:
Is it possible to appendChild from one function to a parent of another?
I'm trying to simulate a directory tree creation. The tree must include the files a user uploads in it. Something like this

Directory:            (Add Directory)(Add File)

```<code>Directory:            (Add Directory)(Add File)

  (browse) Uploaded_file.png

Directory:            (Add Directory)(Add File)

       Directory:            (Add Directory)(Add File)

        (browse) Uploaded_file.png

        (browse) Uploaded_file.png
</code>```

I've found a way to simulate the directory tree but I'm having problems with adding the uploaded files. I'm new to Javascript so not sure how to go about this.

I created a function for tree generating and a separate function for uploading the files. I'd like the file browsing to start when the (Add File) button is clicked. Here's my code:

function add_directory(current) {

  var chosen_branches_of_level = current.getAttribute('what_branches');
  var chosen_level = parseInt(current.getAttribute('what_level'));
  var same_level_branches = document.getElementsByClassName('class_level_' + (chosen_level + 1));
  same_level_branches = same_level_branches.length;
  var where_to = document.getElementById('level_' + chosen_branches_of_level);
  var subdirectory = document.createElement('div');
  var subdirectory_id = (chosen_level + 1) + '_' + (same_level_branches + 1);
  subdirectory.id = 'level_' + subdirectory_id;
  subdirectory.className = 'sub';
  subdirectory.setAttribute('class', 'class_level_' + (chosen_level + 1));

  where_to.appendChild(subdirectory);

  var label = document.createElement("label");
  label.name = 'where' + subdirectory_id;
  label.innerText = "Directory: ";
  subdirectory.appendChild(label);

  var input = document.createElement('input');
  input.name = 'where' + subdirectory_id;
  input.placeholder = 'Subdirectory';

  subdirectory.appendChild(input);

  var new_button_dir = document.createElement('button');
  new_button_dir.setAttribute('onclick', "add_directory(this)");
  new_button_dir.setAttribute('what_branches', subdirectory_id);
  new_button_dir.innerText = 'Add Directory';

  subdirectory.appendChild(new_button_dir);

  var new_button_files = document.createElement('button');
  new_button_files.setAttribute('onclick', "add_files()");
  new_button_files.setAttribute('what_branches', subdirectory_id);
  new_button_files.innerText = 'Add Files';

  subdirectory.appendChild(new_button_files);

  var file_upload = document.createElement("INPUT");
  file_upload.setAttribute("type", "file");
}

function add_files() {
  var file_upload = document.createElement("INPUT");
  file_upload.setAttribute("type", "file");
  subdirectory.appendChild(file_upload);

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
  padding: 10px;
  margin: 5px;
}</code>```

<!DOCTYPE html>

  <title>Adding HTML elements dynamically</title>

Directory tree simulator

    <button onclick="add_directory(this)" what_branches="0_0" what_level="0">Add Directory</button>

```

Making 'subdirectory' variable global doesn't really work. GetElementbyId doesn't work here either as the id changes with each branch. Is there a way to 'append' the 'add_files' function's variable 'file_upload' as a child to the 'subdirectory' parent?

Body:
I'm trying to simulate a directory tree creation. The tree must include the files a user uploads in it. Something like this

Directory:            (Add Directory)(Add File)

Directory:            (Add Directory)(Add File)

  (browse) Uploaded_file.png

Directory:            (Add Directory)(Add File)

       Directory:            (Add Directory)(Add File)

        (browse) Uploaded_file.png

        (browse) Uploaded_file.png

I've found a way to simulate the directory tree but I'm having problems with adding the uploaded files. I'm new to Javascript so not sure how to go about this.

I created a function for tree generating and a separate function for uploading the files. I'd like the file browsing to start when the (Add File) button is clicked. Here's my code:

function add_directory(current) {

  var chosen_branches_of_level = current.getAttribute('what_branches');
  var chosen_level = parseInt(current.getAttribute('what_level'));
  var same_level_branches = document.getElementsByClassName('class_level_' + (chosen_level + 1));
  same_level_branches = same_level_branches.length;
  var where_to = document.getElementById('level_' + chosen_branches_of_level);
  var subdirectory = document.createElement('div');
  var subdirectory_id = (chosen_level + 1) + '_' + (same_level_branches + 1);
  subdirectory.id = 'level_' + subdirectory_id;
  subdirectory.className = 'sub';
  subdirectory.setAttribute('class', 'class_level_' + (chosen_level + 1));

  where_to.appendChild(subdirectory);

  var label = document.createElement("label");
  label.name = 'where' + subdirectory_id;
  label.innerText = "Directory: ";
  subdirectory.appendChild(label);

  var input = document.createElement('input');
  input.name = 'where' + subdirectory_id;
  input.placeholder = 'Subdirectory';

  subdirectory.appendChild(input);

  var new_button_dir = document.createElement('button');
  new_button_dir.setAttribute('onclick', "add_directory(this)");
  new_button_dir.setAttribute('what_branches', subdirectory_id);
  new_button_dir.innerText = 'Add Directory';

  subdirectory.appendChild(new_button_dir);

  var new_button_files = document.createElement('button');
  new_button_files.setAttribute('onclick', "add_files()");
  new_button_files.setAttribute('what_branches', subdirectory_id);
  new_button_files.innerText = 'Add Files';

  subdirectory.appendChild(new_button_files);

  var file_upload = document.createElement("INPUT");
  file_upload.setAttribute("type", "file");
}

function add_files() {
  var file_upload = document.createElement("INPUT");
  file_upload.setAttribute("type", "file");
  subdirectory.appendChild(file_upload);

}

div {
  padding: 10px;
  margin: 5px;
}

<!DOCTYPE html>

  <title>Adding HTML elements dynamically</title>

Directory tree simulator

    <button onclick="add_directory(this)" what_branches="0_0" what_level="0">Add Directory</button>

Making 'subdirectory' variable global doesn't really work. GetElementbyId doesn't work here either as the id changes with each branch. Is there a way to 'append' the 'add_files' function's variable 'file_upload' as a child to the 'subdirectory' parent?


问:
Using Abante cart and trying to add an iframe but does not seem to work
I added this code to AbanteCart and I am only getting about a half of a page of the iframe. Here is the code I am pasting:

I tried to change the values for height and width to no avail.


问:
react native - Sentry.init slows the app drastically
i installed sentry in my react native app as per the docs, and even with the most basic setup the app seems to be lagging by a lot. even navigating to a screen crashes the app.
for example without sentry it takes about max 10 seconds to load, but with sentry it takes around a minute. anyone know why this is happening.

i have the basic sentry config initialized in my App.tsx file

```<code>import * as Sentry from '@sentry/react-native'
</code>```

and right below it before App component begins

```<code>Sentry.init({
 dsn: 'my sentry dsn.....................',
})
</code>```

and help would be much appreciated

Body:
i installed sentry in my react native app as per the docs, and even with the most basic setup the app seems to be lagging by a lot. even navigating to a screen crashes the app.
for example without sentry it takes about max 10 seconds to load, but with sentry it takes around a minute. anyone know why this is happening.

i have the basic sentry config initialized in my App.tsx file

import * as Sentry from '@sentry/react-native'

and right below it before App component begins

Sentry.init({
 dsn: 'my sentry dsn.....................',
})

and help would be much appreciated


问:
How to handle cors error using Magic Eden API?
I recently tried to fetch NFT attributes from Magic Eden using their api.

These are attributes I would like to fetch.

```<code>const nftData = await axios.get(
 `https://api-mainnet.magiceden.dev/rpc/getNFTByMintAddress/J7dEazGQhLzBogsXHFK29r5YRJ3bA42hY4PZAVWb6q4h`)
</code>```

I used this script to fetch data.
It's working on local server but once built, it throw cors error.

How can I handle this cors error?

Body:
I recently tried to fetch NFT attributes from Magic Eden using their api.

These are attributes I would like to fetch.

const nftData = await axios.get(
 `https://api-mainnet.magiceden.dev/rpc/getNFTByMintAddress/J7dEazGQhLzBogsXHFK29r5YRJ3bA42hY4PZAVWb6q4h`)

I used this script to fetch data.
It's working on local server but once built, it throw cors error.

How can I handle this cors error?


问:
phpldapadmin ERR_TOO_MANY_REDIRECTS
Using the downloaded release version 1.2.6.4 (.tar.gz) of phpLDAPadmin causes NGINX to do too many redirects.May I ask how to solve this problem, I can visit normally with httpd, but not with nginx.

Status Code: 302 Found

```<code>phpldapadmin.conf

`

</code>```

server {
listen 80;

```<code>server_name 192.168.198.134;

location /phpldapadmin {
    alias /var/www/html/phpldapadmin/htdocs;
    index index.php index.html index.htm;

    location ~ ^/phpldapadmin/(.+\.php)$ {
        try_files $uri =404;
        root /var/www/html/;
        if ($request_filename !~* htdocs) {
            rewrite ^/phpldapadmin(/.*)?$ /phpldapadmin/htdocs$1;
        }
        include fastcgi_params;

        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_pass unix:/run/php/php7.2-fpm.sock;
    }
}

        error_log /var/log/nginx/phpldapadmin.error.log;
        access_log /var/log/nginx/phpldapadmin.access.log;
</code>```

}

```<code>`
[enter image description here](https://i.stack.imgur.com/M7Fet.png)
</code>```

Title: phpldapadmin ERR_TOO_MANY_REDIRECTS

Body:
Using the downloaded release version 1.2.6.4 (.tar.gz) of phpLDAPadmin causes NGINX to do too many redirects.May I ask how to solve this problem, I can visit normally with httpd, but not with nginx.

Status Code: 302 Found

phpldapadmin.conf

`

server {
listen 80;

server_name 192.168.198.134;

location /phpldapadmin {
    alias /var/www/html/phpldapadmin/htdocs;
    index index.php index.html index.htm;

    location ~ ^/phpldapadmin/(.+\.php)$ {
        try_files $uri =404;
        root /var/www/html/;
        if ($request_filename !~* htdocs) {
            rewrite ^/phpldapadmin(/.*)?$ /phpldapadmin/htdocs$1;
        }
        include fastcgi_params;

        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_pass unix:/run/php/php7.2-fpm.sock;
    }
}

        error_log /var/log/nginx/phpldapadmin.error.log;
        access_log /var/log/nginx/phpldapadmin.access.log;

}

`
[enter image description here](https://i.stack.imgur.com/M7Fet.png)


问:
tensorflow.python.framework.errors_impl.NotFoundError: Key beta1_power_1 not found in checkpoint
I am trying to run the following script, to train a network and use it to predict. I use python 3.6.3 and tf 1.6.

```<code>'''Used for training and predicting a convolutional neural net with two 9 node
output layers. Does not use batch normalization'''
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import numpy as np
import random
import pickle
import tensorflow as tf
import codecs
import os
import datetime

truth_values=['mchi','chi','ek','ph','ts','tr','trph','tw','ltr','tsek','noise']
tf.logging.set_verbosity(tf.logging.INFO)

def input_function(xs1,xs2, labels,labels2, batch_size,i):
    """An input function for training,creates a minibatch of batch_size from input data"""
    length=np.shape(xs1)[0]
    #numb gives the number of next batch to be used given i
    numb=i%(length//batch_size)
    new_features={}
    #randomizes which input goes to which channel
    if random.random()>0.5:
        change={'x':'x','x2':'x2'}
        new_features['y']=labels[batch_size*numb:batch_size*(numb+1)]
        new_features['y2']=labels2[batch_size*numb:batch_size*(numb+1)]
    else:
        change={'x':'x2','x2':'x'}
        new_features['y']=labels2[batch_size*numb:batch_size*(numb+1)]
        new_features['y2']=labels[batch_size*numb:batch_size*(numb+1)]
    for key in ['x','x2']:
        new_features[key]=[]

    '''randomly rolls each pair of spectrograms in the batch for up to 5 pixels
    horizontally and vertically. Roll amount is same for both spectrograms'''

    for i in range(batch_size*numb,batch_size*(numb+1)):
        ver_shift=random.randint(-5,5)
        hor_shift=random.randint(-5,5)
        a=np.roll(xs1[i],(ver_shift,hor_shift),axis=(0,1))
        new_features[change['x']].append(a)

        a2=np.roll(xs2[i],(ver_shift,hor_shift),axis=(0,1))
        new_features[change['x2']].append(a2)

    for key in new_features.keys():
        new_features[key]=np.array(new_features[key],dtype=np.float32)
    return new_features

def eval_input_function(xs1,xs2, labels,labels2, batch_size,i):
    """An input function for evaluation, same as input_function() but doesn't use
    randomization"""
    length=np.shape(xs1)[0]
    numb=i%(length//batch_size)
    new_features={}
    new_features['y']=labels[batch_size*numb:batch_size*(numb+1)]
    new_features['y2']=labels2[batch_size*numb:batch_size*(numb+1)]
    for key in ['x','x2']:
        new_features[key]=[]
    for i in range(batch_size*numb,batch_size*(numb+1)):
        new_features['x'].append(xs1[i])
        new_features['x2'].append(xs2[i])

    for key in new_features.keys():
        new_features[key]=np.array(new_features[key],dtype=np.float32)
    return (new_features)

def pred_input_function(xs1,xs2, i):
    """An input function for predictions, makes a minibatch of 50
    spectrograms with step size of 50ms"""

    new_features={}
    for key in ['x','x2']:
        new_features[key]=[]
    '''splits 257x1299 array into 50 separate 257x256 pieces, 50ms stepsize translates to
    1299/50~26 pixels step size. First 41 pieces can be sliced from the first spectrogram array
    while the other 9 have to be concatenated with the first parts of the next array'''
    for j in range(41):
      start=26*j
      a=xs1[i,:,start:start+256]
      new_features['x'].append(a)

      a=xs2[i,:,start:start+256]
      new_features['x2'].append(a)

    for k in range(9):
      start=26*(k+41)
      init_a=xs1[i,:,start:]
      last=256-np.shape(init_a)[1]
      a=np.concatenate([init_a,xs1[i+1,:,:last]],axis=1)
      new_features['x'].append(a)

      init_a=xs2[i,:,start:]
      a=np.concatenate([init_a,xs2[i+1,:,:last]],axis=1)
      new_features['x2'].append(a)
    for key in new_features.keys():
      new_features[key]=np.array(new_features[key],dtype=np.float32)
    return new_features

def main(xs1=None,xs2=None, batch_size=10, mode='predict', model_dir='Models/model.ckpt'):
  '''the main function for using the network,
  -xs1 and xs2 are used to feed input files when in prediction mode,
  -batch_size refers to the minibatch size to be used when training,
  higher batch_size makes the network train faster but also use more memory, batch_size for predictions is
  hard coded to 50 due to more complicated data structure for performance gains.
  -mode tells whether the network is predicting or training, should be one of 'train' and 'predict'
  -model_dir is the path to where the model should be saved/loaded from'''
  #loads training data, done here to minimize memory usage
  if mode=='train':
      fil_tr_x1=open('Data/train_xs1','rb')
      xs1=np.load(fil_tr_x1)
      fil_tr_x1.close()
      fil_ev_x1=open('Data/eval_xs1','rb')
      eval_xs1=np.load(fil_ev_x1)
      fil_ev_x1.close()

      fil_tr_x2=open('Data/train_xs2','rb')
      xs2=np.load(fil_tr_x2)
      fil_tr_x2.close()
      fil_ev_x2=open('Data/eval_xs2','rb')
      eval_xs2=np.load(fil_ev_x2)
      fil_ev_x2.close()

      fil_tr_y=open('Data/train_ys_single','rb')
      labels=np.load(fil_tr_y)
      fil_tr_y.close()
      fil_ev_y=open('Data/eval_ys_single','rb')
      eval_labels=np.load(fil_ev_y)
      fil_ev_y.close()

      fil_tr_y2=open('Data/train_ys_single2','rb')
      labels2=np.load(fil_tr_y2)
      fil_tr_y2.close()
      fil_ev_y2=open('Data/eval_ys_single2','rb')
      eval_labels2=np.load(fil_ev_y2)
      fil_ev_y2.close()

  """Creates the two stream convolutional neural net with 4 blocks of conv-conv-maxpool"""
  # Input Layer
  x = tf.placeholder(tf.float32, [None, 257, 256])
  input_layer=tf.reshape(x,[-1,257,256,1])
  pool0 = tf.layers.max_pooling2d(inputs=input_layer, pool_size=[2, 2], strides=2)

  conv1 = tf.layers.conv2d(
      inputs=pool0,
      filters=16,
      kernel_size=[5, 5], strides=1,
      padding="same",
      activation=tf.nn.relu)
  conv2 = tf.layers.conv2d(
      inputs=conv1,
      filters=16,
      kernel_size=[5, 5], strides=1,
      padding="same",
      activation=tf.nn.relu)

  pool1 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2], strides=2)

  conv3 = tf.layers.conv2d(
      inputs=pool1,
      filters=32,
      kernel_size=[5, 5], strides=1,
      padding="same",
      activation=tf.nn.relu)
  conv4 = tf.layers.conv2d(
      inputs=conv3,
      filters=32,
      kernel_size=[5, 5], strides=1,
      padding="same",
      activation=tf.nn.relu)

  pool2 = tf.layers.max_pooling2d(inputs=conv4, pool_size=[2, 2], strides=2)#64,52

  conv5 = tf.layers.conv2d(
      inputs=pool2,
      filters=64,
      kernel_size=[3, 3], strides=1,
      padding="same",
      activation=tf.nn.relu)
  conv6 = tf.layers.conv2d(
      inputs=conv5,
      filters=64,
      kernel_size=[3, 3], strides=1,
      padding="same",
      activation=tf.nn.relu)

  pool3 = tf.layers.max_pooling2d(inputs=conv6, pool_size=[2, 2], strides=2)  #128,105

  conv7 = tf.layers.conv2d(
      inputs=pool3,
      filters=64,
      kernel_size=[5, 5], strides=1,
      padding="same",
      activation=tf.nn.relu)
  conv8 = tf.layers.conv2d(
      inputs=conv7,
      filters=64,
      kernel_size=[5, 5], strides=1,
      padding="same",
      activation=tf.nn.relu)

  pool4 = tf.layers.max_pooling2d(inputs=conv8, pool_size=[2, 2], strides=2)

  #Second convolutional stream for second input
  x2=tf.placeholder(tf.float32,[None,257,256])
  input_layer2 = tf.reshape(x2, [-1, 257, 256, 1])

  pool02 = tf.layers.max_pooling2d(inputs=input_layer2, pool_size=[2, 2], strides=2)

  conv12 = tf.layers.conv2d(
      inputs=pool02,
      filters=16,
      kernel_size=[5, 5], strides=1,
      padding="same",
      activation=tf.nn.relu)
  conv22 = tf.layers.conv2d(
      inputs=conv12,
      filters=16,
      kernel_size=[5, 5], strides=1,
      padding="same",
      activation=tf.nn.relu)

  pool12 = tf.layers.max_pooling2d(inputs=conv22, pool_size=[2, 2], strides=2)

  conv32 = tf.layers.conv2d(
      inputs=pool12,
      filters=32,
      kernel_size=[5, 5], strides=1,
      padding="same",
      activation=tf.nn.relu)
  conv42 = tf.layers.conv2d(
      inputs=conv32,
      filters=32,
      kernel_size=[5, 5], strides=1,
      padding="same",
      activation=tf.nn.relu)

  pool22 = tf.layers.max_pooling2d(inputs=conv42, pool_size=[2, 2], strides=2)

  conv52 = tf.layers.conv2d(
      inputs=pool22,
      filters=64,
      kernel_size=[3, 3], strides=1,
      padding="same",
      activation=tf.nn.relu)
  conv62 = tf.layers.conv2d(
      inputs=conv52,
      filters=64,
      kernel_size=[3, 3], strides=1,
      padding="same",
      activation=tf.nn.relu)

  pool32 = tf.layers.max_pooling2d(inputs=conv62, pool_size=[2, 2], strides=2)

  conv72 = tf.layers.conv2d(
      inputs=pool32,
      filters=64,
      kernel_size=[5, 5], strides=1,
      padding="same",
      activation=tf.nn.relu)
  conv82 = tf.layers.conv2d(
      inputs=conv72,
      filters=64,
      kernel_size=[5, 5], strides=1,
      padding="same",
      activation=tf.nn.relu)

  pool42 = tf.layers.max_pooling2d(inputs=conv82, pool_size=[2, 2], strides=2)

  # Combines the two convolutional nets and reshapes them into 1D(excluding batch dimension)
  final_pool_flat = tf.concat([tf.reshape(pool4, [-1, 8 * 8 * 64]),
                               tf.reshape(pool42, [-1, 8 * 8 * 64])],axis=1)
  #adds a 1024 fully connected layer with droupout
  dense = tf.layers.dense(inputs=final_pool_flat, units=1024, activation=tf.nn.relu)
  dropout = tf.layers.dropout(
      inputs=dense, rate=0.4, training=mode == 'train')
  #Creates the two output layers(logits, logits2)
  logits = tf.layers.dense(inputs=dropout, units=9)
  logits2= tf.layers.dense(inputs=dropout, units=9)
  #placeholders for labels
  y=tf.placeholder(tf.float32,[None,9])
  y2=tf.placeholder(tf.float32,[None,9])

  classes=tf.argmax(logits, axis=1)
  classes2=tf.argmax(logits2, axis=1)
  correct=tf.argmax(y, axis=1)
  correct2=tf.argmax(y2, axis=1)
  accuracy=tf.logical_and(tf.equal(classes,correct),tf.equal(classes2,correct2))

  probabilities=tf.nn.softmax(logits, name="softmax_tensor")
  probabilities2=tf.nn.softmax(logits2, name="softmax_tensor")

  loss1 = tf.losses.softmax_cross_entropy(onehot_labels=y, logits=logits)
  loss=loss1+tf.losses.softmax_cross_entropy(onehot_labels=y2, logits=logits2)
  lr=0.0003
  lrate=tf.placeholder(tf.float32,None)
  optimizer = tf.train.AdamOptimizer(learning_rate=lrate,epsilon=0.001)

  #needed if using batch normalization to make sure it works properly
  update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
  with tf.control_dependencies(update_ops):
    train_step = optimizer.minimize(loss)

  sess = tf.InteractiveSession()
  saver = tf.train.Saver()
  #if in prediction mode will use a saved model but if in train mode will train a new model instead
  if mode=='predict':
      saver.restore(sess, model_dir)
      print('Model restored')
  else:
      print('Training new model')
      tf.global_variables_initializer().run()

  if mode == 'predict':
    preds_list=[]
    preds_list2=[]
    predictions=[]
    predictions2=[]
    print('Predicting')
    length=min(np.shape(xs1)[0],np.shape(xs2)[0])
    num_batches=length
    for i in range(num_batches-1):
        inputs=pred_input_function(xs1,xs2, i)
        preds,preds2=sess.run([probabilities,probabilities2],feed_dict={x:inputs['x'],x2:inputs['x2']})
        for j in range(len(preds)):
            preds_list.append(preds[j])
            preds_list2.append(preds2[j])
        if i%25==0:
            print('{}/{}'.format(i,num_batches))
    '''After getting predictions for each timestep, makes final lists(predictions,predictions2)
    by averaging across 5 consecutive predictions,(step size of 1)'''

    for i in range(len(preds_list)-4):
        mean_preds=np.mean(preds_list[i:i+5],axis=0)
        mean_preds2=np.mean(preds_list2[i:i+5],axis=0)
        predictions.append(mean_preds)
        predictions2.append(mean_preds2)

    print(np.shape(predictions))
    tf.Graph()
    sess.close()
    return predictions,predictions2

  if mode=='train':

    length=np.shape(xs1)[0]
    s=[]
    accuracies=[]
    for j in range(length):
        s.append(j)
    for i in range(200):
        numb=i%(length//batch_size)
        #shuffles training data after a full epoch
        if numb==0:
            random.shuffle(s)
            labels=labels[s]
            labels2=labels2[s]
            xs1=xs1[s]
            xs2=xs2[s]

        inputs=input_function(xs1,xs2, labels,labels2, batch_size,i)
        #trains the model while keeping track of accuracy
        _,accurs=sess.run([train_step,accuracy],feed_dict={x:inputs['x'],x2:inputs['x2'],
                                                           y:inputs['y'],y2:inputs['y2'],lrate:lr})
        for value in accurs:
            if value==True:
                accuracies.append(1)
            else:
                accuracies.append(0)
        #prints training accuracy and evaluates evaluation accuracy every 1000 steps
        #also multiplies learning rate by 0.97
        if i%100==0:
            print("Step {} Train accuracy: {:.4f}".format(i,np.mean(accuracies)))
            mode='eval'
            lr=lr*0.97
            accuracies=[]
            for k in range(np.shape(eval_xs1)[0]//batch_size):
                inputs=eval_input_function(eval_xs1,eval_xs2, eval_labels,eval_labels2, batch_size,k)
                accurs=sess.run(accuracy,feed_dict=
                        {x:inputs['x'],x2:inputs['x2'],y:inputs['y'],y2:inputs['y2']})
                for value in accurs:
                    if value==True:
                        accuracies.append(1)
                    else:
                        accuracies.append(0)
            mode='train'
            print("Eval accuracy: {:.4f}".format(np.mean(accuracies)))
            accuracies=[]
            savepath=saver.save(sess, model_dir)
            print('Model saved', savepath)

def train(model_dire):
  main(batch_size=25,mode='train',model_dir=model_dire)

def predict(pred_data1,pred_data2,predictions_file1,predictions_file2,model_dir):
    '''function for predicting with the network
    -pred_data1 is the path to first file containing spectrogram arrays for file to be predicted from
    -pred_data2 is the path to second input file from the same session,
    if none an array of zeroes will be fed as the second input
    -predictions_file1 and predictions_file2 are the paths to where predictions will be saved,
    -model_dir is the path to the saved model to be used for predicting'''
    fil1=open(pred_data1,'rb')
    predict_x1=np.load(fil1)
    fil1.close()
    if pred_data2!=None:
        fil2=open(pred_data2,'rb')
        predict_x2=np.load(fil2)
        fil2.close()
    else:
        predict_x2=np.zeros(np.shape(predict_x1),dtype=np.float16)

    predictions1,predictions2=main(predict_x1,predict_x2,batch_size=25,mode='predict',
                     model_dir=model_dir)

    np.save(predictions_file1,predictions1)
    np.save(predictions_file2,predictions2)

if __name__=='__main__':
  start=datetime.datetime.now()
  train("Models/model_small.ckpt")
  print("Time taken: ", datetime.datetime.now()-start)
  predict('Data/Selma_111722_aligned_x1_test',
          'Data/Kafka_111722_aligned_x2_test',
          'Data/pred_111722_Selma_model_small',
          'Data/pred_111722_Kafka_model_small',
          model_dir="Models/mode_small.ckpt")
</code>```

But I get the following error:

```<code>INFO:tensorflow:Restoring parameters from Models/model_small.ckpt
2022-12-12 15:46:26.678180: W C:\tf_jenkins\workspace\rel-win\M\windows\PY\36\tensorflow\core\framework\op_kernel.cc:1202] OP_REQUIRES failed at save_restore_v2_ops.cc:184 : Not found: Key beta1_power_1 not found in checkpoint
Traceback (most recent call last):
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\client\session.py", line 1361, in _do_call
    return fn(*args)
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\client\session.py", line 1340, in _run_fn
    target_list, status, run_metadata)
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\framework\errors_impl.py", line 516, in __exit__
    c_api.TF_GetCode(self.status.status))
tensorflow.python.framework.errors_impl.NotFoundError: Key beta1_power_1 not found in checkpoint
         [[Node: save_1/RestoreV2 = RestoreV2[dtypes=[DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT, ..., DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT], _device="/job:localhost/replica:0/task:0/device:CPU:0"](_arg_save_1/Const_0_0, save_1/RestoreV2/tensor_names, save_1/RestoreV2/shape_and_slices)]]

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "new_train_72.py", line 437, in <module>
    model_dir="Models/model_small.ckpt")
  File "new_train_72.py", line 423, in predict
    model_dir=model_dir)
  File "new_train_72.py", line 315, in main
    saver.restore(sess, model_dir)
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\training\saver.py", line 1755, in restore
    {self.saver_def.filename_tensor_name: save_path})
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\client\session.py", line 905, in run
    run_metadata_ptr)
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\client\session.py", line 1137, in _run
    feed_dict_tensor, options, run_metadata)
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\client\session.py", line 1355, in _do_run
    options, run_metadata)
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\client\session.py", line 1374, in _do_call
    raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.NotFoundError: Key beta1_power_1 not found in checkpoint
         [[Node: save_1/RestoreV2 = RestoreV2[dtypes=[DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT, ..., DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT], _device="/job:localhost/replica:0/task:0/device:CPU:0"](_arg_save_1/Const_0_0, save_1/RestoreV2/tensor_names, save_1/RestoreV2/shape_and_slices)]]

Caused by op 'save_1/RestoreV2', defined at:
  File "new_train_72.py", line 437, in <module>
    model_dir="Models/model_small.ckpt")
  File "new_train_72.py", line 423, in predict
    model_dir=model_dir)
  File "new_train_72.py", line 312, in main
    saver = tf.train.Saver()
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\training\saver.py", line 1293, in __init__
    self.build()
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\training\saver.py", line 1302, in build
    self._build(self._filename, build_save=True, build_restore=True)
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\training\saver.py", line 1339, in _build
    build_save=build_save, build_restore=build_restore)
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\training\saver.py", line 796, in _build_internal
    restore_sequentially, reshape)
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\training\saver.py", line 449, in _AddRestoreOps
    restore_sequentially)
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\training\saver.py", line 847, in bulk_restore
    return io_ops.restore_v2(filename_tensor, names, slices, dtypes)
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\ops\gen_io_ops.py", line 1113, in restore_v2
    shape_and_slices=shape_and_slices, dtypes=dtypes, name=name)
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 787, in _apply_op_helper
    op_def=op_def)
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\framework\ops.py", line 3271, in create_op
    op_def=op_def)
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\framework\ops.py", line 1650, in __init__
    self._traceback = self._graph._extract_stack()  # pylint: disable=protected-access

NotFoundError (see above for traceback): Key beta1_power_1 not found in checkpoint
         [[Node: save_1/RestoreV2 = RestoreV2[dtypes=[DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT, ..., DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT], _device="/job:localhost/replica:0/task:0/device:CPU:0"](_arg_save_1/Const_0_0, save_1/RestoreV2/tensor_names, save_1/RestoreV2/shape_and_slices)]]
</code>```

I checked what is saved in my checkpoint (using inspect_checkpoint), and there are only beta1_power and beta2_power.
Also, when I run only the train part alone, or the predict part alone (by commenting lines 431 or 433) I do not get an error, but the prediction completely fails (does not detect anything).
Is there something wrong with the saving/restoring of the model? Why is it not working when I run the whole script (train and predict)? And why do I have no errors but no results when I run them separately?

Thanks for reading!

Body:
I am trying to run the following script, to train a network and use it to predict. I use python 3.6.3 and tf 1.6.

'''Used for training and predicting a convolutional neural net with two 9 node
output layers. Does not use batch normalization'''
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import numpy as np
import random
import pickle
import tensorflow as tf
import codecs
import os
import datetime

truth_values=['mchi','chi','ek','ph','ts','tr','trph','tw','ltr','tsek','noise']
tf.logging.set_verbosity(tf.logging.INFO)

def input_function(xs1,xs2, labels,labels2, batch_size,i):
    """An input function for training,creates a minibatch of batch_size from input data"""
    length=np.shape(xs1)[0]
    #numb gives the number of next batch to be used given i
    numb=i%(length//batch_size)
    new_features={}
    #randomizes which input goes to which channel
    if random.random()>0.5:
        change={'x':'x','x2':'x2'}
        new_features['y']=labels[batch_size*numb:batch_size*(numb+1)]
        new_features['y2']=labels2[batch_size*numb:batch_size*(numb+1)]
    else:
        change={'x':'x2','x2':'x'}
        new_features['y']=labels2[batch_size*numb:batch_size*(numb+1)]
        new_features['y2']=labels[batch_size*numb:batch_size*(numb+1)]
    for key in ['x','x2']:
        new_features[key]=[]

    '''randomly rolls each pair of spectrograms in the batch for up to 5 pixels
    horizontally and vertically. Roll amount is same for both spectrograms'''

    for i in range(batch_size*numb,batch_size*(numb+1)):
        ver_shift=random.randint(-5,5)
        hor_shift=random.randint(-5,5)
        a=np.roll(xs1[i],(ver_shift,hor_shift),axis=(0,1))
        new_features[change['x']].append(a)

        a2=np.roll(xs2[i],(ver_shift,hor_shift),axis=(0,1))
        new_features[change['x2']].append(a2)

    for key in new_features.keys():
        new_features[key]=np.array(new_features[key],dtype=np.float32)
    return new_features

def eval_input_function(xs1,xs2, labels,labels2, batch_size,i):
    """An input function for evaluation, same as input_function() but doesn't use
    randomization"""
    length=np.shape(xs1)[0]
    numb=i%(length//batch_size)
    new_features={}
    new_features['y']=labels[batch_size*numb:batch_size*(numb+1)]
    new_features['y2']=labels2[batch_size*numb:batch_size*(numb+1)]
    for key in ['x','x2']:
        new_features[key]=[]
    for i in range(batch_size*numb,batch_size*(numb+1)):
        new_features['x'].append(xs1[i])
        new_features['x2'].append(xs2[i])

    for key in new_features.keys():
        new_features[key]=np.array(new_features[key],dtype=np.float32)
    return (new_features)

def pred_input_function(xs1,xs2, i):
    """An input function for predictions, makes a minibatch of 50
    spectrograms with step size of 50ms"""

    new_features={}
    for key in ['x','x2']:
        new_features[key]=[]
    '''splits 257x1299 array into 50 separate 257x256 pieces, 50ms stepsize translates to
    1299/50~26 pixels step size. First 41 pieces can be sliced from the first spectrogram array
    while the other 9 have to be concatenated with the first parts of the next array'''
    for j in range(41):
      start=26*j
      a=xs1[i,:,start:start+256]
      new_features['x'].append(a)

      a=xs2[i,:,start:start+256]
      new_features['x2'].append(a)

    for k in range(9):
      start=26*(k+41)
      init_a=xs1[i,:,start:]
      last=256-np.shape(init_a)[1]
      a=np.concatenate([init_a,xs1[i+1,:,:last]],axis=1)
      new_features['x'].append(a)

      init_a=xs2[i,:,start:]
      a=np.concatenate([init_a,xs2[i+1,:,:last]],axis=1)
      new_features['x2'].append(a)
    for key in new_features.keys():
      new_features[key]=np.array(new_features[key],dtype=np.float32)
    return new_features

def main(xs1=None,xs2=None, batch_size=10, mode='predict', model_dir='Models/model.ckpt'):
  '''the main function for using the network,
  -xs1 and xs2 are used to feed input files when in prediction mode,
  -batch_size refers to the minibatch size to be used when training,
  higher batch_size makes the network train faster but also use more memory, batch_size for predictions is
  hard coded to 50 due to more complicated data structure for performance gains.
  -mode tells whether the network is predicting or training, should be one of 'train' and 'predict'
  -model_dir is the path to where the model should be saved/loaded from'''
  #loads training data, done here to minimize memory usage
  if mode=='train':
      fil_tr_x1=open('Data/train_xs1','rb')
      xs1=np.load(fil_tr_x1)
      fil_tr_x1.close()
      fil_ev_x1=open('Data/eval_xs1','rb')
      eval_xs1=np.load(fil_ev_x1)
      fil_ev_x1.close()

      fil_tr_x2=open('Data/train_xs2','rb')
      xs2=np.load(fil_tr_x2)
      fil_tr_x2.close()
      fil_ev_x2=open('Data/eval_xs2','rb')
      eval_xs2=np.load(fil_ev_x2)
      fil_ev_x2.close()

      fil_tr_y=open('Data/train_ys_single','rb')
      labels=np.load(fil_tr_y)
      fil_tr_y.close()
      fil_ev_y=open('Data/eval_ys_single','rb')
      eval_labels=np.load(fil_ev_y)
      fil_ev_y.close()

      fil_tr_y2=open('Data/train_ys_single2','rb')
      labels2=np.load(fil_tr_y2)
      fil_tr_y2.close()
      fil_ev_y2=open('Data/eval_ys_single2','rb')
      eval_labels2=np.load(fil_ev_y2)
      fil_ev_y2.close()

  """Creates the two stream convolutional neural net with 4 blocks of conv-conv-maxpool"""
  # Input Layer
  x = tf.placeholder(tf.float32, [None, 257, 256])
  input_layer=tf.reshape(x,[-1,257,256,1])
  pool0 = tf.layers.max_pooling2d(inputs=input_layer, pool_size=[2, 2], strides=2)

  conv1 = tf.layers.conv2d(
      inputs=pool0,
      filters=16,
      kernel_size=[5, 5], strides=1,
      padding="same",
      activation=tf.nn.relu)
  conv2 = tf.layers.conv2d(
      inputs=conv1,
      filters=16,
      kernel_size=[5, 5], strides=1,
      padding="same",
      activation=tf.nn.relu)

  pool1 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2], strides=2)

  conv3 = tf.layers.conv2d(
      inputs=pool1,
      filters=32,
      kernel_size=[5, 5], strides=1,
      padding="same",
      activation=tf.nn.relu)
  conv4 = tf.layers.conv2d(
      inputs=conv3,
      filters=32,
      kernel_size=[5, 5], strides=1,
      padding="same",
      activation=tf.nn.relu)

  pool2 = tf.layers.max_pooling2d(inputs=conv4, pool_size=[2, 2], strides=2)#64,52

  conv5 = tf.layers.conv2d(
      inputs=pool2,
      filters=64,
      kernel_size=[3, 3], strides=1,
      padding="same",
      activation=tf.nn.relu)
  conv6 = tf.layers.conv2d(
      inputs=conv5,
      filters=64,
      kernel_size=[3, 3], strides=1,
      padding="same",
      activation=tf.nn.relu)

  pool3 = tf.layers.max_pooling2d(inputs=conv6, pool_size=[2, 2], strides=2)  #128,105

  conv7 = tf.layers.conv2d(
      inputs=pool3,
      filters=64,
      kernel_size=[5, 5], strides=1,
      padding="same",
      activation=tf.nn.relu)
  conv8 = tf.layers.conv2d(
      inputs=conv7,
      filters=64,
      kernel_size=[5, 5], strides=1,
      padding="same",
      activation=tf.nn.relu)

  pool4 = tf.layers.max_pooling2d(inputs=conv8, pool_size=[2, 2], strides=2)

  #Second convolutional stream for second input
  x2=tf.placeholder(tf.float32,[None,257,256])
  input_layer2 = tf.reshape(x2, [-1, 257, 256, 1])

  pool02 = tf.layers.max_pooling2d(inputs=input_layer2, pool_size=[2, 2], strides=2)

  conv12 = tf.layers.conv2d(
      inputs=pool02,
      filters=16,
      kernel_size=[5, 5], strides=1,
      padding="same",
      activation=tf.nn.relu)
  conv22 = tf.layers.conv2d(
      inputs=conv12,
      filters=16,
      kernel_size=[5, 5], strides=1,
      padding="same",
      activation=tf.nn.relu)

  pool12 = tf.layers.max_pooling2d(inputs=conv22, pool_size=[2, 2], strides=2)

  conv32 = tf.layers.conv2d(
      inputs=pool12,
      filters=32,
      kernel_size=[5, 5], strides=1,
      padding="same",
      activation=tf.nn.relu)
  conv42 = tf.layers.conv2d(
      inputs=conv32,
      filters=32,
      kernel_size=[5, 5], strides=1,
      padding="same",
      activation=tf.nn.relu)

  pool22 = tf.layers.max_pooling2d(inputs=conv42, pool_size=[2, 2], strides=2)

  conv52 = tf.layers.conv2d(
      inputs=pool22,
      filters=64,
      kernel_size=[3, 3], strides=1,
      padding="same",
      activation=tf.nn.relu)
  conv62 = tf.layers.conv2d(
      inputs=conv52,
      filters=64,
      kernel_size=[3, 3], strides=1,
      padding="same",
      activation=tf.nn.relu)

  pool32 = tf.layers.max_pooling2d(inputs=conv62, pool_size=[2, 2], strides=2)

  conv72 = tf.layers.conv2d(
      inputs=pool32,
      filters=64,
      kernel_size=[5, 5], strides=1,
      padding="same",
      activation=tf.nn.relu)
  conv82 = tf.layers.conv2d(
      inputs=conv72,
      filters=64,
      kernel_size=[5, 5], strides=1,
      padding="same",
      activation=tf.nn.relu)

  pool42 = tf.layers.max_pooling2d(inputs=conv82, pool_size=[2, 2], strides=2)

  # Combines the two convolutional nets and reshapes them into 1D(excluding batch dimension)
  final_pool_flat = tf.concat([tf.reshape(pool4, [-1, 8 * 8 * 64]),
                               tf.reshape(pool42, [-1, 8 * 8 * 64])],axis=1)
  #adds a 1024 fully connected layer with droupout
  dense = tf.layers.dense(inputs=final_pool_flat, units=1024, activation=tf.nn.relu)
  dropout = tf.layers.dropout(
      inputs=dense, rate=0.4, training=mode == 'train')
  #Creates the two output layers(logits, logits2)
  logits = tf.layers.dense(inputs=dropout, units=9)
  logits2= tf.layers.dense(inputs=dropout, units=9)
  #placeholders for labels
  y=tf.placeholder(tf.float32,[None,9])
  y2=tf.placeholder(tf.float32,[None,9])

  classes=tf.argmax(logits, axis=1)
  classes2=tf.argmax(logits2, axis=1)
  correct=tf.argmax(y, axis=1)
  correct2=tf.argmax(y2, axis=1)
  accuracy=tf.logical_and(tf.equal(classes,correct),tf.equal(classes2,correct2))

  probabilities=tf.nn.softmax(logits, name="softmax_tensor")
  probabilities2=tf.nn.softmax(logits2, name="softmax_tensor")

  loss1 = tf.losses.softmax_cross_entropy(onehot_labels=y, logits=logits)
  loss=loss1+tf.losses.softmax_cross_entropy(onehot_labels=y2, logits=logits2)
  lr=0.0003
  lrate=tf.placeholder(tf.float32,None)
  optimizer = tf.train.AdamOptimizer(learning_rate=lrate,epsilon=0.001)

  #needed if using batch normalization to make sure it works properly
  update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
  with tf.control_dependencies(update_ops):
    train_step = optimizer.minimize(loss)

  sess = tf.InteractiveSession()
  saver = tf.train.Saver()
  #if in prediction mode will use a saved model but if in train mode will train a new model instead
  if mode=='predict':
      saver.restore(sess, model_dir)
      print('Model restored')
  else:
      print('Training new model')
      tf.global_variables_initializer().run()

  if mode == 'predict':
    preds_list=[]
    preds_list2=[]
    predictions=[]
    predictions2=[]
    print('Predicting')
    length=min(np.shape(xs1)[0],np.shape(xs2)[0])
    num_batches=length
    for i in range(num_batches-1):
        inputs=pred_input_function(xs1,xs2, i)
        preds,preds2=sess.run([probabilities,probabilities2],feed_dict={x:inputs['x'],x2:inputs['x2']})
        for j in range(len(preds)):
            preds_list.append(preds[j])
            preds_list2.append(preds2[j])
        if i%25==0:
            print('{}/{}'.format(i,num_batches))
    '''After getting predictions for each timestep, makes final lists(predictions,predictions2)
    by averaging across 5 consecutive predictions,(step size of 1)'''

    for i in range(len(preds_list)-4):
        mean_preds=np.mean(preds_list[i:i+5],axis=0)
        mean_preds2=np.mean(preds_list2[i:i+5],axis=0)
        predictions.append(mean_preds)
        predictions2.append(mean_preds2)

    print(np.shape(predictions))
    tf.Graph()
    sess.close()
    return predictions,predictions2

  if mode=='train':

    length=np.shape(xs1)[0]
    s=[]
    accuracies=[]
    for j in range(length):
        s.append(j)
    for i in range(200):
        numb=i%(length//batch_size)
        #shuffles training data after a full epoch
        if numb==0:
            random.shuffle(s)
            labels=labels[s]
            labels2=labels2[s]
            xs1=xs1[s]
            xs2=xs2[s]

        inputs=input_function(xs1,xs2, labels,labels2, batch_size,i)
        #trains the model while keeping track of accuracy
        _,accurs=sess.run([train_step,accuracy],feed_dict={x:inputs['x'],x2:inputs['x2'],
                                                           y:inputs['y'],y2:inputs['y2'],lrate:lr})
        for value in accurs:
            if value==True:
                accuracies.append(1)
            else:
                accuracies.append(0)
        #prints training accuracy and evaluates evaluation accuracy every 1000 steps
        #also multiplies learning rate by 0.97
        if i%100==0:
            print("Step {} Train accuracy: {:.4f}".format(i,np.mean(accuracies)))
            mode='eval'
            lr=lr*0.97
            accuracies=[]
            for k in range(np.shape(eval_xs1)[0]//batch_size):
                inputs=eval_input_function(eval_xs1,eval_xs2, eval_labels,eval_labels2, batch_size,k)
                accurs=sess.run(accuracy,feed_dict=
                        {x:inputs['x'],x2:inputs['x2'],y:inputs['y'],y2:inputs['y2']})
                for value in accurs:
                    if value==True:
                        accuracies.append(1)
                    else:
                        accuracies.append(0)
            mode='train'
            print("Eval accuracy: {:.4f}".format(np.mean(accuracies)))
            accuracies=[]
            savepath=saver.save(sess, model_dir)
            print('Model saved', savepath)

def train(model_dire):
  main(batch_size=25,mode='train',model_dir=model_dire)

def predict(pred_data1,pred_data2,predictions_file1,predictions_file2,model_dir):
    '''function for predicting with the network
    -pred_data1 is the path to first file containing spectrogram arrays for file to be predicted from
    -pred_data2 is the path to second input file from the same session,
    if none an array of zeroes will be fed as the second input
    -predictions_file1 and predictions_file2 are the paths to where predictions will be saved,
    -model_dir is the path to the saved model to be used for predicting'''
    fil1=open(pred_data1,'rb')
    predict_x1=np.load(fil1)
    fil1.close()
    if pred_data2!=None:
        fil2=open(pred_data2,'rb')
        predict_x2=np.load(fil2)
        fil2.close()
    else:
        predict_x2=np.zeros(np.shape(predict_x1),dtype=np.float16)

    predictions1,predictions2=main(predict_x1,predict_x2,batch_size=25,mode='predict',
                     model_dir=model_dir)

    np.save(predictions_file1,predictions1)
    np.save(predictions_file2,predictions2)

if __name__=='__main__':
  start=datetime.datetime.now()
  train("Models/model_small.ckpt")
  print("Time taken: ", datetime.datetime.now()-start)
  predict('Data/Selma_111722_aligned_x1_test',
          'Data/Kafka_111722_aligned_x2_test',
          'Data/pred_111722_Selma_model_small',
          'Data/pred_111722_Kafka_model_small',
          model_dir="Models/mode_small.ckpt")

But I get the following error:

INFO:tensorflow:Restoring parameters from Models/model_small.ckpt
2022-12-12 15:46:26.678180: W C:\tf_jenkins\workspace\rel-win\M\windows\PY\36\tensorflow\core\framework\op_kernel.cc:1202] OP_REQUIRES failed at save_restore_v2_ops.cc:184 : Not found: Key beta1_power_1 not found in checkpoint
Traceback (most recent call last):
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\client\session.py", line 1361, in _do_call
    return fn(*args)
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\client\session.py", line 1340, in _run_fn
    target_list, status, run_metadata)
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\framework\errors_impl.py", line 516, in __exit__
    c_api.TF_GetCode(self.status.status))
tensorflow.python.framework.errors_impl.NotFoundError: Key beta1_power_1 not found in checkpoint
         [[Node: save_1/RestoreV2 = RestoreV2[dtypes=[DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT, ..., DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT], _device="/job:localhost/replica:0/task:0/device:CPU:0"](_arg_save_1/Const_0_0, save_1/RestoreV2/tensor_names, save_1/RestoreV2/shape_and_slices)]]

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "new_train_72.py", line 437, in <module>
    model_dir="Models/model_small.ckpt")
  File "new_train_72.py", line 423, in predict
    model_dir=model_dir)
  File "new_train_72.py", line 315, in main
    saver.restore(sess, model_dir)
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\training\saver.py", line 1755, in restore
    {self.saver_def.filename_tensor_name: save_path})
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\client\session.py", line 905, in run
    run_metadata_ptr)
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\client\session.py", line 1137, in _run
    feed_dict_tensor, options, run_metadata)
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\client\session.py", line 1355, in _do_run
    options, run_metadata)
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\client\session.py", line 1374, in _do_call
    raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.NotFoundError: Key beta1_power_1 not found in checkpoint
         [[Node: save_1/RestoreV2 = RestoreV2[dtypes=[DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT, ..., DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT], _device="/job:localhost/replica:0/task:0/device:CPU:0"](_arg_save_1/Const_0_0, save_1/RestoreV2/tensor_names, save_1/RestoreV2/shape_and_slices)]]

Caused by op 'save_1/RestoreV2', defined at:
  File "new_train_72.py", line 437, in <module>
    model_dir="Models/model_small.ckpt")
  File "new_train_72.py", line 423, in predict
    model_dir=model_dir)
  File "new_train_72.py", line 312, in main
    saver = tf.train.Saver()
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\training\saver.py", line 1293, in __init__
    self.build()
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\training\saver.py", line 1302, in build
    self._build(self._filename, build_save=True, build_restore=True)
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\training\saver.py", line 1339, in _build
    build_save=build_save, build_restore=build_restore)
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\training\saver.py", line 796, in _build_internal
    restore_sequentially, reshape)
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\training\saver.py", line 449, in _AddRestoreOps
    restore_sequentially)
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\training\saver.py", line 847, in bulk_restore
    return io_ops.restore_v2(filename_tensor, names, slices, dtypes)
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\ops\gen_io_ops.py", line 1113, in restore_v2
    shape_and_slices=shape_and_slices, dtypes=dtypes, name=name)
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 787, in _apply_op_helper
    op_def=op_def)
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\framework\ops.py", line 3271, in create_op
    op_def=op_def)
  File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\framework\ops.py", line 1650, in __init__
    self._traceback = self._graph._extract_stack()  # pylint: disable=protected-access

NotFoundError (see above for traceback): Key beta1_power_1 not found in checkpoint
         [[Node: save_1/RestoreV2 = RestoreV2[dtypes=[DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT, ..., DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT], _device="/job:localhost/replica:0/task:0/device:CPU:0"](_arg_save_1/Const_0_0, save_1/RestoreV2/tensor_names, save_1/RestoreV2/shape_and_slices)]]

I checked what is saved in my checkpoint (using inspect_checkpoint), and there are only beta1_power and beta2_power.
Also, when I run only the train part alone, or the predict part alone (by commenting lines 431 or 433) I do not get an error, but the prediction completely fails (does not detect anything).
Is there something wrong with the saving/restoring of the model? Why is it not working when I run the whole script (train and predict)? And why do I have no errors but no results when I run them separately?

Thanks for reading!


问:
How to create a lambda connection when you dont know the sender class?
Is it possible somehow to create a lambda connection when you dont know the sender class?

I was trying to write a function that iterate trought all widgets in the gui and find these with the property "opacity", then listen to when it emit a signal and call a function.

However, these widgets are subclassed and have different class names, im not sure how to make the lambda connection in this case.

For example:

```<code>foreach (QWidget* widget, QApplication::allWidgets())
{
    if (widget != NULL)
    {
        QVariant prop = widget->property("opacity");
        if (prop.isValid())
        {
            connect(widget, &<???>::signalOpacity, [this]
            (QWidget* widget, int duration, bool fadein)
            {
                this->setOpacity(widget, duration, fadein)
            });
        }
    }
}
</code>```

I can get the widget class name with:

```<code>auto class_name = widget->metaObject()->className();
</code>```

But how do i get a pointer to the class itself?

Body:
Is it possible somehow to create a lambda connection when you dont know the sender class?

I was trying to write a function that iterate trought all widgets in the gui and find these with the property "opacity", then listen to when it emit a signal and call a function.

However, these widgets are subclassed and have different class names, im not sure how to make the lambda connection in this case.

For example:

foreach (QWidget* widget, QApplication::allWidgets())
{
    if (widget != NULL)
    {
        QVariant prop = widget->property("opacity");
        if (prop.isValid())
        {
            connect(widget, &<???>::signalOpacity, [this]
            (QWidget* widget, int duration, bool fadein)
            {
                this->setOpacity(widget, duration, fadein)
            });
        }
    }
}

I can get the widget class name with:

auto class_name = widget->metaObject()->className();

But how do i get a pointer to the class itself?


问:
Building Python against Openssl 3.0 in nonstandard location
I have successfully source compiled OpenSSL 3.0 and installed it in /some/dir via the following sequence:

```<code>$ wget https://github.com/openssl/openssl/archive/refs/tags/openssl-3.0.7.tar.gz
$ tar -xvf openssl-3.0.7.tar.gz
$ cd openssl-openssl-3.0.7/
$ ./Configure CC=clang --prefix=/some/dir --openssldir=/some/dir
'-Wl,-rpath,$(LIBRPATH)'
</code>```

I then try to build Python3.11 on top of it via:

```<code>$ wget https://www.python.org/ftp/python/3.11.1/Python-3.11.1.tgz
$ tar -xvf Python-3.11.1.tgz
$ cd Python-3.11.1/
$ ./configure CC=clang --with-openssl-rpath=auto --with-openssl=/some/dir
checking for openssl/ssl.h in /some/dir... yes
checking whether compiling and linking against OpenSSL works... yes
checking for --with-openssl-rpath... auto
checking whether OpenSSL provides required ssl module APIs... no
checking whether OpenSSL provides required hashlib module APIs... no
checking for --with-ssl-default-suites... python
checking for --with-builtin-hashlib-hashes... md5,sha1,sha256,sha512,sha3,blake2
...
checking for stdlib extension module _md5... yes
checking for stdlib extension module _sha1... yes
checking for stdlib extension module _sha256... yes
checking for stdlib extension module _sha512... yes
checking for stdlib extension module _sha3... yes
</code>```

However, when I build, I get the following error:

```<code>$ make
...
The necessary bits to build these optional modules were not found:
_hashlib              _ssl                  _tkinter
To find the necessary bits, look in setup.py in detect_modules() for the module's name.

Could not build the ssl module!
Python requires a OpenSSL 1.1.1 or newer
Custom linker flags may require --with-openssl-rpath=auto
</code>```

(FWIW, I have tried with and without --openssl-rpath=auto. I have also seen that python seems to support it.)

How can I build this successfully with OpenSSL 3.0? OpenSSL 1.1.1 does not emit this warning.

As an aside, hashlib seems to work anyway:

>>> import hashlib
>>> m = hashlib.sha256()
>>> m.update(b"Nobody inspects")
>>> m.digest()
b'\xe7\xa3\xf8\x08\xcb\x06\x87\xfd6`\xe9V\xa5\xdf\x0f\x00\xe2>\xda\xc5e\x07i\xec5N\xe6p\xb6X\x85\x8c'
```
<p>but <code>ssl</code> does not:</p>
<pre class="lang-py prettyprint-override"><code>>>> import ssl
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/some/dir/Python-3.11.1/Lib/ssl.py", line 100, in <module>
    import _ssl             # if we can't import it, let the error propagate
    ^^^^^^^^^^^
ModuleNotFoundError: No module named '_ssl'
</code>```

Body:
I have successfully source compiled OpenSSL 3.0 and installed it in /some/dir via the following sequence:

$ wget https://github.com/openssl/openssl/archive/refs/tags/openssl-3.0.7.tar.gz
$ tar -xvf openssl-3.0.7.tar.gz
$ cd openssl-openssl-3.0.7/
$ ./Configure CC=clang --prefix=/some/dir --openssldir=/some/dir
'-Wl,-rpath,$(LIBRPATH)'

I then try to build Python3.11 on top of it via:

$ wget https://www.python.org/ftp/python/3.11.1/Python-3.11.1.tgz
$ tar -xvf Python-3.11.1.tgz
$ cd Python-3.11.1/
$ ./configure CC=clang --with-openssl-rpath=auto --with-openssl=/some/dir
checking for openssl/ssl.h in /some/dir... yes
checking whether compiling and linking against OpenSSL works... yes
checking for --with-openssl-rpath... auto
checking whether OpenSSL provides required ssl module APIs... no
checking whether OpenSSL provides required hashlib module APIs... no
checking for --with-ssl-default-suites... python
checking for --with-builtin-hashlib-hashes... md5,sha1,sha256,sha512,sha3,blake2
...
checking for stdlib extension module _md5... yes
checking for stdlib extension module _sha1... yes
checking for stdlib extension module _sha256... yes
checking for stdlib extension module _sha512... yes
checking for stdlib extension module _sha3... yes

However, when I build, I get the following error:

$ make
...
The necessary bits to build these optional modules were not found:
_hashlib              _ssl                  _tkinter
To find the necessary bits, look in setup.py in detect_modules() for the module's name.

Could not build the ssl module!
Python requires a OpenSSL 1.1.1 or newer
Custom linker flags may require --with-openssl-rpath=auto

(FWIW, I have tried with and without --openssl-rpath=auto. I have also seen that python seems to support it.)

How can I build this successfully with OpenSSL 3.0? OpenSSL 1.1.1 does not emit this warning.

As an aside, hashlib seems to work anyway:

>>> import hashlib
>>> m = hashlib.sha256()
>>> m.update(b"Nobody inspects")
>>> m.digest()
b'\xe7\xa3\xf8\x08\xcb\x06\x87\xfd6`\xe9V\xa5\xdf\x0f\x00\xe2>\xda\xc5e\x07i\xec5N\xe6p\xb6X\x85\x8c'

but ssl does not:

>>> import ssl
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/some/dir/Python-3.11.1/Lib/ssl.py", line 100, in <module>
    import _ssl             # if we can't import it, let the error propagate
    ^^^^^^^^^^^
ModuleNotFoundError: No module named '_ssl'


问:
ANR in com.google.android.apps.messaging
Got the following error in Google Play prelaunch report:

```<code>ANR in com.google.android.apps.messaging;PID: 15781;Broadcast of Intent
{ act=android.accounts.LOGIN_ACCOUNTS_CHANGED flg=0x5000010 cmp=com.google.android.apps.messaging/com.google.apps.tiktok.account.data.device.DeviceAccountsChangedReceiver_Receiver };
</code>```

What is it? How to test this?

Body:
Got the following error in Google Play prelaunch report:

ANR in com.google.android.apps.messaging;PID: 15781;Broadcast of Intent
{ act=android.accounts.LOGIN_ACCOUNTS_CHANGED flg=0x5000010 cmp=com.google.android.apps.messaging/com.google.apps.tiktok.account.data.device.DeviceAccountsChangedReceiver_Receiver };

What is it? How to test this?


Title: MongoDB high latency when enable ReplicaSet, due to IOPS

Body:
I have the following setup:

2x c5n.4xlarge (16 vcpu, 32G mem):
 - each has 3 gp3 disk (500GB, 10000 Iops and 500Mb throughput), running raid 0

When mongo run standalone, it is fast. Inserts can easily reach 20K/s.

However, when replication is involved. Only 4K/s.

When running iostat -xtc 1,

Device            r/s     rkB/s   rrqm/s  %rrqm r_await rareq-sz     w/s     wkB/s   wrqm/s  %wrqm w_await wareq-sz     d/s     dkB/s   drqm/s  %drqm d_await dareq-sz     f/s f_await  aqu-sz  %util
loop0            0.00      0.00     0.00   0.00    0.00     0.00    0.00      0.00     0.00   0.00    0.00     0.00    0.00      0.00     0.00   0.00    0.00     0.00    0.00    0.00    0.00   0.00
loop1            0.00      0.00     0.00   0.00    0.00     0.00    0.00      0.00     0.00   0.00    0.00     0.00    0.00      0.00     0.00   0.00    0.00     0.00    0.00    0.00    0.00   0.00
loop2            0.00      0.00     0.00   0.00    0.00     0.00    0.00      0.00     0.00   0.00    0.00     0.00    0.00      0.00     0.00   0.00    0.00     0.00    0.00    0.00    0.00   0.00
loop3            0.00      0.00     0.00   0.00    0.00     0.00    0.00      0.00     0.00   0.00    0.00     0.00    0.00      0.00     0.00   0.00    0.00     0.00    0.00    0.00    0.00   0.00
loop4            0.00      0.00     0.00   0.00    0.00     0.00    0.00      0.00     0.00   0.00    0.00     0.00    0.00      0.00     0.00   0.00    0.00     0.00    0.00    0.00    0.00   0.00
loop5            0.00      0.00     0.00   0.00    0.00     0.00    0.00      0.00     0.00   0.00    0.00     0.00    0.00      0.00     0.00   0.00    0.00     0.00    0.00    0.00    0.00   0.00
loop6            0.00      0.00     0.00   0.00    0.00     0.00    0.00      0.00     0.00   0.00    0.00     0.00    0.00      0.00     0.00   0.00    0.00     0.00    0.00    0.00    0.00   0.00
loop7            0.00      0.00     0.00   0.00    0.00     0.00    0.00      0.00     0.00   0.00    0.00     0.00    0.00      0.00     0.00   0.00    0.00     0.00    0.00    0.00    0.00   0.00
md0              0.00      0.00     0.00   0.00    0.00     0.00  638.00  15488.00     0.00   0.00    0.81    24.28    0.00      0.00     0.00   0.00    0.00     0.00    0.00    0.00    0.52  82.80
nvme0n1          0.00      0.00     0.00   0.00    0.00     0.00    0.00      0.00     0.00   0.00    0.00     0.00    0.00      0.00     0.00   0.00    0.00     0.00    0.00    0.00    0.00   0.00
nvme1n1          0.00      0.00     0.00   0.00    0.00     0.00  196.00   4916.00     0.00   0.00    0.77    25.08    0.00      0.00     0.00   0.00    0.00     0.00    0.00    0.00    0.15  41.20
nvme2n1          0.00      0.00     0.00   0.00    0.00     0.00  237.00   5704.00     0.00   0.00    0.73    24.07    0.00      0.00     0.00   0.00    0.00     0.00    0.00    0.00    0.17  46.40
nvme3n1          0.00      0.00     0.00   0.00    0.00     0.00  220.00   5352.00     0.00   0.00    0.73    24.33    0.00      0.00     0.00   0.00    0.00     0.00    0.00    0.00    0.16  44.40

md0 device, utilisation is high. No matter how much IOPS i invested to disk, nothing significant changes.

Hope to get some advice on this matter.


问:
R Shiny unexpected error: Header part not working
I am trying to develop logo header for my app in R Shiny. When I try to execute the program it generates an error in the header program part. I am not able to understand why I am getting this error. I looked at the code many times but can't find the issue. Any help very much appreciated.

code:

```<code>shinyUI(fluidPage(navbarPage(HTML(""),theme = shinytheme("flatly"),
                             tags$style(HTML(".navbar .navbar-nav {float: right;
                                                          font-size: 38px; }
      .navbar .navbar-header {float: left; }
      .navbar-default .navbar-brand { font-size: 38px;
                                      }

  ")),

                             tags$script(HTML("var header = $('.navbar > .container-fluid');
header.append('<div style=\"float:left\"><ahref=\"URL\"><img src=\"https://www.rstudio.com/wp-content/uploads/2018/10/RStudio-Logo.png\" alt=\"alt\" style=\"float:left;width:70px;height:70px;padding-top:5px\"> </a></div>');
    console.log(header)")),
                             tags$script(HTML("var header = $('.navbar > .container-fluid');
 header.append('<div style=\"float:left;text-align:left;color:white\"><h2>  Sample - App </h2></div>')"
                             )),

</code>```

Error:

```<code>Error: unexpected symbol in:
" header.append('<div style=\"float:left;text-align:left;color:white\"><h2>  Sample - App</h2></div>');"
shinyUI"
</code>```

Body:
I am trying to develop logo header for my app in R Shiny. When I try to execute the program it generates an error in the header program part. I am not able to understand why I am getting this error. I looked at the code many times but can't find the issue. Any help very much appreciated.

code:

shinyUI(fluidPage(navbarPage(HTML(""),theme = shinytheme("flatly"),
                             tags$style(HTML(".navbar .navbar-nav {float: right;
                                                          font-size: 38px; }
      .navbar .navbar-header {float: left; }
      .navbar-default .navbar-brand { font-size: 38px;
                                      }

  ")),

                             tags$script(HTML("var header = $('.navbar > .container-fluid');
header.append('
<ahref=\"URL\">
');
    console.log(header)")),
                             tags$script(HTML("var header = $('.navbar > .container-fluid');
 header.append('

  Sample - App

')"
                             )),

Error:

Error: unexpected symbol in:
" header.append('

  Sample - App

');"
shinyUI"


问:
TypeError: unhashable type: 'numpy.ndarray'
This is my first time posting to an online forum. So if there is something in my post that is unclear then I apologize in advance

So I am learning the basics of Pandas and currently exploring the query() method. Performing this  method raises this TypeError. However, the textbook's doesn't mention if an error might be raised. I have checked and rechecked the instructions as stated in the book and have followed it carefully.

Any help or suggestion would be appreciated.

The data:

```<code>weather.head()
           date        datatype        station      attributes  value
0   2018-01-01T00:00:00 PRCP    GHCND:US1CTFR0039   ,,N,    0.0
1   2018-01-01T00:00:00 PRCP    GHCND:US1NJBG0015   ,,N,    0.0
2   2018-01-01T00:00:00 SNOW    GHCND:US1NJBG0015   ,,N,    0.0
3   2018-01-01T00:00:00 PRCP    GHCND:US1NJBG0017   ,,N,    0.0
4   2018-01-01T00:00:00 SNOW    GHCND:US1NJBG0017   ,,N,    0.0
</code>```

when I perform a Boolean indexing, I get the desired results.

```<code>weather[(weather['station'].str.contains('NY'))
         & (weather['datatype']=='SNOW')
         & (weather['value']>0)]

          date        datatype        station      attributes   value
114 2018-01-01T00:00:00 SNOW    GHCND:US1NYWC0019   ,,N,    25.0
789 2018-01-04T00:00:00 SNOW    GHCND:US1NYNS0007   ,,N,    41.0
794 2018-01-04T00:00:00 SNOW    GHCND:US1NYNS0018   ,,N,    10.0
798 2018-01-04T00:00:00 SNOW    GHCND:US1NYNS0024   ,,N,    89.0
800 2018-01-04T00:00:00 SNOW    GHCND:US1NYNS0030   ,,N,    102.0
</code>```

Performing a query() without "and station.str.contains('NY')" works

```<code>weather.query("datatype=='SNOW'
               "and value>0")`

             date         datatype     station     attributes   value
114 2018-01-01T00:00:00 SNOW    GHCND:US1NYWC0019   ,,N,    25.0
699 2018-01-04T00:00:00 SNOW    GHCND:US1NJBG0015   ,,N,    229.0
702 2018-01-04T00:00:00 SNOW    GHCND:US1NJBG0017   ,,N,    10.0
706 2018-01-04T00:00:00 SNOW    GHCND:US1NJBG0018   ,,N,    46.0
713 2018-01-04T00:00:00 SNOW    GHCND:US1NJES0018   ,,N,    10.0
</code>```

However attempting do accomplish the same after adding "and station.str.contains('NY')"

```<code>weather.query("datatype=='SNOW'"
              "and value>0"
              "and station.str.contains('NY')")

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-8-f6c5dd0c9862> in <module>
----> 1 weather.query("datatype=='SNOW'"
      2               "and value>0"
      3               "and station.str.contains('NY')"
      4               )

6 frames
/usr/local/lib/python3.8/dist-packages/pandas/core/computation/expr.py in names(self)
    832         if is_term(self.terms):
    833             return frozenset([self.terms.name])
--> 834         return frozenset(term.name for term in com.flatten(self.terms))
    835
    836

TypeError: unhashable type: 'numpy.ndarray'
</code>```

Body:
This is my first time posting to an online forum. So if there is something in my post that is unclear then I apologize in advance

So I am learning the basics of Pandas and currently exploring the query() method. Performing this  method raises this TypeError. However, the textbook's doesn't mention if an error might be raised. I have checked and rechecked the instructions as stated in the book and have followed it carefully.

Any help or suggestion would be appreciated.

The data:

weather.head()
           date        datatype        station      attributes  value
0   2018-01-01T00:00:00 PRCP    GHCND:US1CTFR0039   ,,N,    0.0
1   2018-01-01T00:00:00 PRCP    GHCND:US1NJBG0015   ,,N,    0.0
2   2018-01-01T00:00:00 SNOW    GHCND:US1NJBG0015   ,,N,    0.0
3   2018-01-01T00:00:00 PRCP    GHCND:US1NJBG0017   ,,N,    0.0
4   2018-01-01T00:00:00 SNOW    GHCND:US1NJBG0017   ,,N,    0.0

when I perform a Boolean indexing, I get the desired results.

weather[(weather['station'].str.contains('NY'))
         & (weather['datatype']=='SNOW')
         & (weather['value']>0)]

          date        datatype        station      attributes   value
114 2018-01-01T00:00:00 SNOW    GHCND:US1NYWC0019   ,,N,    25.0
789 2018-01-04T00:00:00 SNOW    GHCND:US1NYNS0007   ,,N,    41.0
794 2018-01-04T00:00:00 SNOW    GHCND:US1NYNS0018   ,,N,    10.0
798 2018-01-04T00:00:00 SNOW    GHCND:US1NYNS0024   ,,N,    89.0
800 2018-01-04T00:00:00 SNOW    GHCND:US1NYNS0030   ,,N,    102.0

Performing a query() without "and station.str.contains('NY')" works

weather.query("datatype=='SNOW'
               "and value>0")`

             date         datatype     station     attributes   value
114 2018-01-01T00:00:00 SNOW    GHCND:US1NYWC0019   ,,N,    25.0
699 2018-01-04T00:00:00 SNOW    GHCND:US1NJBG0015   ,,N,    229.0
702 2018-01-04T00:00:00 SNOW    GHCND:US1NJBG0017   ,,N,    10.0
706 2018-01-04T00:00:00 SNOW    GHCND:US1NJBG0018   ,,N,    46.0
713 2018-01-04T00:00:00 SNOW    GHCND:US1NJES0018   ,,N,    10.0

However attempting do accomplish the same after adding "and station.str.contains('NY')"

weather.query("datatype=='SNOW'"
              "and value>0"
              "and station.str.contains('NY')")

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-8-f6c5dd0c9862> in <module>
----> 1 weather.query("datatype=='SNOW'"
      2               "and value>0"
      3               "and station.str.contains('NY')"
      4               )

6 frames
/usr/local/lib/python3.8/dist-packages/pandas/core/computation/expr.py in names(self)
    832         if is_term(self.terms):
    833             return frozenset([self.terms.name])
--> 834         return frozenset(term.name for term in com.flatten(self.terms))
    835
    836

TypeError: unhashable type: 'numpy.ndarray'


问:
mpirun on SLURM with background and foreground subprocess in Python
I am using Python to synchronize the execution of two solvers, using a SLURM-based cluster and multiple nodes (4 nodes, 1 task per node, 20 CPUs per task).
One is using signals to communicate with the other, so it starts once and needs to keep going in background. I do it with the following command:

```<code>subprocess.Popen('mpirun -np 4 --bind-to none -oversubscribe execute_1'.split(), bufsize=-1, stdout=out, stderr=subprocess.STDOUT)
</code>```

When it starts I can see it uses 4 nodes and 20 CPUs for each of the 4 tasks, so it seems to work properly.

Once the first execution is complete, the first code goes automatically to sleep. The second code needs to be executed. This time, I have to wait for this second code to be done before to wake up the first code, therefore I wanted to use:

```<code>subprocess.check_call('mpirun -np 80 -oversubscribe --bind-to none execute_2'.split(), bufsize=-1, stdout=out, stderr=subprocess.STDOUT)
</code>```

Note that this code uses all the CPUs together (4 nodes, 20 tasks per node, 1 CPU per task). If I do it by itself, the behavior is as expected: it runs with maximum efficiency, using 80 CPU, although to do that I had to add this "--bind-to none -oversubscribe" which I do not fully understand. I also added it in the first one in case it was needed. However, when I do that with the first code in background, the calculation hangs, and from the tests I have performed, I can see that it never gets executed (no log of any form).

The sbatch submission file contains the following for every test I have done above:

```<code>#!/bin/bash
...
#SBATCH --nodes=4
#SBATCH --ntasks-per-node=1
#SBATCH --cpus-per-task=20
python3 Coupling.py
</code>```

I also cannot submit multiple sbatch commands, I really need just one.

So my questions are: what is wrong with my implementation? Is it due to "--bind-to none -oversubscribe"? Is there a way to make these two codes work with one in background and the other one in foreground?

I would really appreciate some guidance on that matter.

Thanks in advance!

Body:
I am using Python to synchronize the execution of two solvers, using a SLURM-based cluster and multiple nodes (4 nodes, 1 task per node, 20 CPUs per task).
One is using signals to communicate with the other, so it starts once and needs to keep going in background. I do it with the following command:

subprocess.Popen('mpirun -np 4 --bind-to none -oversubscribe execute_1'.split(), bufsize=-1, stdout=out, stderr=subprocess.STDOUT)

When it starts I can see it uses 4 nodes and 20 CPUs for each of the 4 tasks, so it seems to work properly.

Once the first execution is complete, the first code goes automatically to sleep. The second code needs to be executed. This time, I have to wait for this second code to be done before to wake up the first code, therefore I wanted to use:

subprocess.check_call('mpirun -np 80 -oversubscribe --bind-to none execute_2'.split(), bufsize=-1, stdout=out, stderr=subprocess.STDOUT)

Note that this code uses all the CPUs together (4 nodes, 20 tasks per node, 1 CPU per task). If I do it by itself, the behavior is as expected: it runs with maximum efficiency, using 80 CPU, although to do that I had to add this "--bind-to none -oversubscribe" which I do not fully understand. I also added it in the first one in case it was needed. However, when I do that with the first code in background, the calculation hangs, and from the tests I have performed, I can see that it never gets executed (no log of any form).

The sbatch submission file contains the following for every test I have done above:

#!/bin/bash
...
#SBATCH --nodes=4
#SBATCH --ntasks-per-node=1
#SBATCH --cpus-per-task=20
python3 Coupling.py

I also cannot submit multiple sbatch commands, I really need just one.

So my questions are: what is wrong with my implementation? Is it due to "--bind-to none -oversubscribe"? Is there a way to make these two codes work with one in background and the other one in foreground?

I would really appreciate some guidance on that matter.

Thanks in advance!


问:
In Parse Server, how do I know if if I loginAnonymous? (Flutter)
Will the snapshot have no data and I might be able to check with that? Or there is other ways to check?

I have an app that I have same data that I want all users including guest users to see, and some data are available to user/vip user only, and I have problem about how should I know whether the user is logged in as a guest(not logged in).


问:
How to create projectile that will move with constant speed along curved path?
I'm making a little game using SFML. I made a turret which shoots in 4 directions (diagonally) and now I'm trying to figure out how to shoot out the projectiles. I want them to travel from point A (turret) to point B (enemy) along curved path with constant speed and I don't really know what calculations and formulas should I used to control x and y position of the projectile. I'm terrible at explaining but maybe a photo will make it clearer:
Sketch of a turret with enemies and curved paths

I tried finding quadratic equations and equations of circles and move the projectiles along them. The problem was that:

firstly, my calculations weren't accurate

secondly, due to how cirlces and parabolas are calculated the speed of the projectile wasn't constant at all...


问:
xinput & libinput calibration & configuration of a Fujitsu resistive touchscreen (void linux)
So here's the situation: I have been running Void on a Toughbook CF-31 from about 2011 that has treated me quite well. It was running Win10 before I put Linux on it and the touchscreen worked with that OS. However, as soon as I installed Void the cursor started jumping continuously around the center of the screen and clicking unpredictably. It was essentially useless. I disabled the touchscreen in the BIOS and have used the laptop since.

From querying with lsusb I found that the touchscreen is described as a "Fujitsu Component USB Touch Panel", which is the same identifier associated with the touchscreen on the CF-19.

I initially tried to run xinput_calibrator, but it was not effective. I have also tried modifying the Coordinate Transformation Matrix property with "xinput set-prop", but this was not effective either, although I did manage to move the center of where the random movement is.

I know that the touchscreens on these machines work with calibration alone on Ubuntu and other distributions, and I've found sparse references to the touchscreen working on Linux Mint with minimal tweaks i.e. uninstalling libinput and reinstalling evdev or somesuch. I'm wary of simply uninstalling libinput as it seems to manage many of my input devices and I don't know what would happen to my system if I did.

I've also had trouble finding any comprehensive documentation that explains how xinput works from device to software, the distinctions between evdev, libinput and elographics, etc. I know that libinput has taken the touchscreen device automatically and is managing it.

There is only one other question relevant to my situation on SO and it just doesn't get me where I need to be to make this work.


问:
Salesforce to Azure
Needing some guidance. I am wanting to connect my Salesforce instance to Azure but not sure what I should go with as there are many things in this ecosystem i.e. Bricks, Synapse, Factories, Data Lakes, Storage Blobs, Azure SQL, Azure SQL DB. There are many things referenced online and I just want to do right by my company. Ultimately we are looking for a good place to put our data and then shape it without breaking the bank and to utilize tools like Tableau and Power BI.

I have researched some but I definitely won't know more than some grizzled experts out there.

Title: Salesforce to Azure


问:
How to access a Google Form from the Google API?
The following code accesses Google Sheets in my account:

```<code>import gspread, json
import pandas as pd
from google.auth import default
from google.colab import auth

auth.authenticate_user()

creds, _ = default()
gc = gspread.authorize(creds)

SCOPE = ["https://spreadsheets.google.com/feeds"]
SECRETS_FILE = "file.json"
SPREADSHEET = "File sheet"

# Based on docs here - http://gspread.readthedocs.org/en/latest/oauth2.html
# Load in the secret JSON key (must be a service account)
json_key = json.load(open(SECRETS_FILE))

# Authenticate using the signed key
#credentials = SignedJwtAssertionCredentials(json_key['client_email'], json_key['private_key'], SCOPE)

gc = gspread.authorize(creds)
print("The following sheets are available")
for sheet in gc.openall():
    print("{} - {}".format(sheet.title, sheet.id))

# Open up the workbook based on the spreadsheet name
workbook = gc.open(SPREADSHEET)

# Get the first sheet
sheet = workbook.sheet1

# Extract all data into a dataframe
data = pd.DataFrame(sheet.get_all_records())

column_names = {}

data.rename(columns=column_names, inplace=True)
# data.timestamp = pd.to_datetime(data.timestamp)
print(data.head())
</code>```

I have a Google Form in this account as well. How can I access the Google Forms and return as a Pandas dataframe as I am doing it here?

Body:
The following code accesses Google Sheets in my account:

import gspread, json
import pandas as pd
from google.auth import default
from google.colab import auth

auth.authenticate_user()

creds, _ = default()
gc = gspread.authorize(creds)

SCOPE = ["https://spreadsheets.google.com/feeds"]
SECRETS_FILE = "file.json"
SPREADSHEET = "File sheet"

# Based on docs here - http://gspread.readthedocs.org/en/latest/oauth2.html
# Load in the secret JSON key (must be a service account)
json_key = json.load(open(SECRETS_FILE))

# Authenticate using the signed key
#credentials = SignedJwtAssertionCredentials(json_key['client_email'], json_key['private_key'], SCOPE)

gc = gspread.authorize(creds)
print("The following sheets are available")
for sheet in gc.openall():
    print("{} - {}".format(sheet.title, sheet.id))

# Open up the workbook based on the spreadsheet name
workbook = gc.open(SPREADSHEET)

# Get the first sheet
sheet = workbook.sheet1

# Extract all data into a dataframe
data = pd.DataFrame(sheet.get_all_records())

column_names = {}

data.rename(columns=column_names, inplace=True)
# data.timestamp = pd.to_datetime(data.timestamp)
print(data.head())

I have a Google Form in this account as well. How can I access the Google Forms and return as a Pandas dataframe as I am doing it here?


问:
Adding even tiny send delay to a UDP speed test makes it 100x slower
I'm currently trying to compare the speeds of TCP and UDP for the purposes of a science project. I am sending 10000 packets of 100 bytes each over a local network (currently only on one computer) and measuring the time (clientside) it takes for 10000 packets to be received. I got my program to work, however, TCP appeared much faster than UDP, which should not be the case for this experiment (although, it IS an experiment, so technically those results could be valid...).

I investigated the problem by counting the amount of UDP packets that were sent, and then comparing them to the amount of packets that were received. This turned out to be shocking, as I found 3000+ packets were sent, but not received on the client side. To fix this, I tried adding a short delay (1ms) to each UDP packet send (serverside only) but then found that that delay (quite frustratingly) slowed the total transmission time down by nearly 100x. I then reduced the delay to around 12 nanoseconds and found the same effect (again to my chagrin). I expected for this delay to give the client some time to catch up... not to mysteriously slow my code down by 100x!!!

Can anyone help me? My code is at https://github.com/Archonic944/ProtocolSpeedTest.


问:
I created this SYN Flood attack code but when I do netstat -at in the destination host looks like the attack didn't performed
I'm creating a SYN Flood Attack but the attack looks never happened when I try to do netstat -at in destination host.

```<code>#!/usr/bin/python
from scapy.all import *

p=IP(dst="192.192.192.192",id=1111,ttl=99)/TCP(sport=RandShort(),dport=22,seq=12345,ack=1000,window=1000,flags="S")
ans,unans=srloop(p,inter=0.3,retry=2,timeout=4, count=10)
ans.summary()
unans.summary()
</code>```

I'm trying to do SYN Flood attack and when I do netstat -at in destination host find the attack result there. I didn't find the attack at all.

Body:
I'm creating a SYN Flood Attack but the attack looks never happened when I try to do netstat -at in destination host.

#!/usr/bin/python
from scapy.all import *

p=IP(dst="192.192.192.192",id=1111,ttl=99)/TCP(sport=RandShort(),dport=22,seq=12345,ack=1000,window=1000,flags="S")
ans,unans=srloop(p,inter=0.3,retry=2,timeout=4, count=10)
ans.summary()
unans.summary()

I'm trying to do SYN Flood attack and when I do netstat -at in destination host find the attack result there. I didn't find the attack at all.


问:
Using latest postgres driver with gorm
I am using the gorm release v1.24.2, and I am using gorm.io/driver/postgres which is v1.4.5, and that version uses pgx v4.  Now I noticed github.com/go-gorm/postgres has been updated to use pgx v5.  I want to use pgx v5 because that handles marshaling of the INET type.  But when I try to import github.com/go-gorm/postgres it says the module is declaring itself as gorm.io/driver/postgres.  Is there a udpated version of gorm.io/driver/postgres that I could use to get the updated drive that is shown on github?</p>

Title: Using latest postgres driver with gorm


问:
how can edit content in [events calendar] plugin wordpress
In Wordpress, i've got an issue that  i don't know i can be able to edit content as this image below

from [Latest Past 活动] -> i wanna edit to another content.

i've tried to find in Events-> Settings but it's seem like anable

I would appreciate it if someone could help me this issue


问:
Flutter Geolocator AccuracyLevel.Low takes longer to complete versus AccuracyLevel.High
In Geolocator.getCurrentPosition()

AccuracyLevel.Low would take around 10secs to complete while
AccuracyLevel.High would take around 1-2secs only.

Shouldn't be Low accuracy level much faster to complete?


问:
jsconfig.js file not working with symlink package
I have a React node repo that imports from a custom node repo. Both repos are located in my local machine. I have jsconfig.js files in both repo, using VS code. However, only the React repo is recognizing the jsconfig.js file. The jsconfig.js file in the imported module appears to be completely ignored.

The the imported module is symlinked into my React repo via npm like so:

npm link

This is what is in both jsconfig.js files:

```<code>{
  "compilerOptions": {
    "baseUrl": "./src"
  }
}
</code>```

Why is the jsconfig.js file being completely ignored in the imported module. Does being symlinked causes this?

Body:
I have a React node repo that imports from a custom node repo. Both repos are located in my local machine. I have jsconfig.js files in both repo, using VS code. However, only the React repo is recognizing the jsconfig.js file. The jsconfig.js file in the imported module appears to be completely ignored.

The the imported module is symlinked into my React repo via npm like so:

npm link

This is what is in both jsconfig.js files:

{
  "compilerOptions": {
    "baseUrl": "./src"
  }
}

Why is the jsconfig.js file being completely ignored in the imported module. Does being symlinked causes this?


问:
Convert excel data into a dataframe and then into a dict object
I have a excel file in the below format. I would like to get the values into dictionary groups by each product after loading into dataframe.  Each dictionary group should have one product details. Is that possible?

```<code>              | Nov 2021 | Nov 2021 | Nov 2021 | Oct 2021 | Oct 2021 | Oct 2021 | Sep 2021 | Sep 2021 | Sep 2021
              | Metric A | Metric B | Metric C | Metric A | Metric B | Metric C | Metric A | Metric B | Metric C
     Product 1| 0.9      | 1.95     | 0.9      | 5.95     | 0.4      | 1.95     | 3.9      | 5.95     |  3.4
     Product 2| 0.86     | 1.94     | 0.45     | 15.94    | 0.6      | 4.5      | 4.45     | 5.4      |  4.5
     Product 3| 0.56     | 2.3      | 0.56     | 10.94    | 0.6      | 2.3      | 3.56     | 1.94     |  5.6
     Product 4| 0.65     | 4.5      | 1.45     | 21.94    | 0.42     | 4.5      | 1.45     | 1.4      |  6.7
</code>```

I have tried to load the entire excel sheet into dataframe but I am not able to separate the data into groups.

Body:
I have a excel file in the below format. I would like to get the values into dictionary groups by each product after loading into dataframe.  Each dictionary group should have one product details. Is that possible?

              | Nov 2021 | Nov 2021 | Nov 2021 | Oct 2021 | Oct 2021 | Oct 2021 | Sep 2021 | Sep 2021 | Sep 2021
              | Metric A | Metric B | Metric C | Metric A | Metric B | Metric C | Metric A | Metric B | Metric C
     Product 1| 0.9      | 1.95     | 0.9      | 5.95     | 0.4      | 1.95     | 3.9      | 5.95     |  3.4
     Product 2| 0.86     | 1.94     | 0.45     | 15.94    | 0.6      | 4.5      | 4.45     | 5.4      |  4.5
     Product 3| 0.56     | 2.3      | 0.56     | 10.94    | 0.6      | 2.3      | 3.56     | 1.94     |  5.6
     Product 4| 0.65     | 4.5      | 1.45     | 21.94    | 0.42     | 4.5      | 1.45     | 1.4      |  6.7

I have tried to load the entire excel sheet into dataframe but I am not able to separate the data into groups.


问:
How to use csrf token? csrf must be sent on every server request?
hello im junior developer

I've read many articles about csrf tokens,

but I can't figure out how to use them. If the csrf token is what sends malicious code to the server, should all server requests include the csrf token, including accessing logged-in users?

Isn't it necessary for non-login users' services? Request like example main page post get

I am putting csrf token in every request, but I don't know if this is the right way


问:
Enable toggle switch only to one item in react
We are using react in our questionnaire in forms. I would like to add the toggle switch to each question to identify the deciding question for a condition. The working should be such that when the toggle is enabled for 1 question, the other questions toggle should be turned off, meaning user should be able to select  only 1 deciding question. Please guide me on how to achieve this? i am stuck

```<code>

                   <Form.Check
                        type="switch"
                        id="decidingQuestion"
                        name="decidingQuestion"
                        value={input.decidingQuestion}
                        checked={input.decidingQuestion}
                        onChange={event => props.handleInputChange(index, event)}
                    >
                    </Form.Check>

</code>```

NOTE: The number of questions will be dynamic based on whether user clicks on "Add" button when they want to add another question.

tried multiple things but did not get the expected results. Not familiar with react and JS.

Addiitonal:

```<code>const templateRow = { question: '', questionType: '', questionState: '' , decidingQuestion:false};
    const [inputFields, setInputFields] = useState([templateRow]);
</code>```
```<code>    const handleInputChange = (index, event) => {
        const values = [...inputFields];
        console.log(event)
        console.log(values)
        if(event.target.name!="decidingQuestion")
            values[index][event.target.name] = event.target.value;
        else{
         if(event.target.checked)
            {
            console.log("INSIDE THIS FIELD")
                values.forEach((x,ind)=>{
                    console.log(x)
                    if(ind!=index){

                        x[event.target.name]=!x[event.target.value]

                    }
                    console.log(x)
            })}
        values[index][event.target.name]= event.target.checked;

    }

        setInputFields(values);
    };
</code>```

Body:
We are using react in our questionnaire in forms. I would like to add the toggle switch to each question to identify the deciding question for a condition. The working should be such that when the toggle is enabled for 1 question, the other questions toggle should be turned off, meaning user should be able to select  only 1 deciding question. Please guide me on how to achieve this? i am stuck

                   <Form.Check
                        type="switch"
                        id="decidingQuestion"
                        name="decidingQuestion"
                        value={input.decidingQuestion}
                        checked={input.decidingQuestion}
                        onChange={event => props.handleInputChange(index, event)}
                    >
                    </Form.Check>

NOTE: The number of questions will be dynamic based on whether user clicks on "Add" button when they want to add another question.

tried multiple things but did not get the expected results. Not familiar with react and JS.

Addiitonal:

const templateRow = { question: '', questionType: '', questionState: '' , decidingQuestion:false};
    const [inputFields, setInputFields] = useState([templateRow]);

    const handleInputChange = (index, event) => {
        const values = [...inputFields];
        console.log(event)
        console.log(values)
        if(event.target.name!="decidingQuestion")
            values[index][event.target.name] = event.target.value;
        else{
         if(event.target.checked)
            {
            console.log("INSIDE THIS FIELD")
                values.forEach((x,ind)=>{
                    console.log(x)
                    if(ind!=index){

                        x[event.target.name]=!x[event.target.value]

                    }
                    console.log(x)
            })}
        values[index][event.target.name]= event.target.checked;

    }

        setInputFields(values);
    };