问:
Asynchronous Batch Updates With Large Files Not Working Properly
I am trying to insert files which asynchronous batch updates but I am getting the following exception while inserting:

```<code>nested exception is org.postgresql.util.PSQLException: Large Objects may not be used in auto-commit mode.
</code>```

Code Sample

```<code>  @Autowired
  private JdbcTemplate jdbcTemplate;

  @Autowired
  private NamedParameterJdbcTemplate namedJdbcTemplate;

  @Value("${jdbc.batch_insert_size}")
  private int batchSize;

  private static final ExecutorService executor = Executors.newFixedThreadPool(10);

  @Transactional(propagation = Propagation.REQUIRES_NEW)
  public void batchInsertAsync(List<User> users) throws InterruptedException, ExecutionException {

    String sql = "INSERT INTO `USER` (USERNAME, PASSWORD, FILE, UPDATEDTIME, USERTYPE, DATEOFBIRTH)"
        + " VALUES(?,?,?,?,?,?)";
    final AtomicInteger sublists = new AtomicInteger();
    CompletableFuture[] futures = users.stream()
        .collect(Collectors.groupingBy(t -> sublists.getAndIncrement() / batchSize))
        .values()
        .stream()
        .map(ul -> runBatchInsert(ul, sql))
        .toArray(CompletableFuture[]::new);
    CompletableFuture<Void> run = CompletableFuture.allOf(futures);

    run.get();

    log.info("batchInsertAsync -> Total time in seconds: " + timer.getTotalTimeSeconds());
  }
  public CompletableFuture<Void> runBatchInsert(List<User> users, String sql) {
    return CompletableFuture.runAsync(() -> {
      jdbcTemplate.batchUpdate(sql, new UserBatchPreparedStatementSetter(users));
    }, executor);
  }
</code>```
```<code>public class UserBatchPreparedStatementSetter implements BatchPreparedStatementSetter{
  private List<User> users;

  public UserBatchPreparedStatementSetter(List<User> users) {
    super();
    this.users = users;
  }
  @Override
  public void setValues(PreparedStatement ps, int i) {

    try {
      User user = users.get(i);
      ps.setString(1, user.getUserName());
      ps.setString(2, user.getPassword());
      ps.setClob(3,org.hibernate.engine.jdbc.ClobProxy.generateProxy(user.getContent()));
      ps.setDate(4, user.getUpdatedTime() == null ? null : new java.sql.Date(user.getUpdatedTime().getTime()));
      ps.setString(5, user.getUserType().toString());
      ps.setDate(6, new java.sql.Date(user.getDateofBirth().getTime()));
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }
  @Override
  public int getBatchSize() {
    return users.size();
  }
}
</code>```

Can anyone help me how to use asynchronous batch updates with large files?

Thanks in advance

================================================================

Body:
I am trying to insert files which asynchronous batch updates but I am getting the following exception while inserting:

nested exception is org.postgresql.util.PSQLException: Large Objects may not be used in auto-commit mode.

Code Sample

  @Autowired
  private JdbcTemplate jdbcTemplate;

  @Autowired
  private NamedParameterJdbcTemplate namedJdbcTemplate;

  @Value("${jdbc.batch_insert_size}")
  private int batchSize;

  private static final ExecutorService executor = Executors.newFixedThreadPool(10);

  @Transactional(propagation = Propagation.REQUIRES_NEW)
  public void batchInsertAsync(List<User> users) throws InterruptedException, ExecutionException {

    String sql = "INSERT INTO `USER` (USERNAME, PASSWORD, FILE, UPDATEDTIME, USERTYPE, DATEOFBIRTH)"
        + " VALUES(?,?,?,?,?,?)";
    final AtomicInteger sublists = new AtomicInteger();
    CompletableFuture[] futures = users.stream()
        .collect(Collectors.groupingBy(t -> sublists.getAndIncrement() / batchSize))
        .values()
        .stream()
        .map(ul -> runBatchInsert(ul, sql))
        .toArray(CompletableFuture[]::new);
    CompletableFuture<Void> run = CompletableFuture.allOf(futures);

    run.get();

    log.info("batchInsertAsync -> Total time in seconds: " + timer.getTotalTimeSeconds());
  }
  public CompletableFuture<Void> runBatchInsert(List<User> users, String sql) {
    return CompletableFuture.runAsync(() -> {
      jdbcTemplate.batchUpdate(sql, new UserBatchPreparedStatementSetter(users));
    }, executor);
  }

public class UserBatchPreparedStatementSetter implements BatchPreparedStatementSetter{
  private List<User> users;

  public UserBatchPreparedStatementSetter(List<User> users) {
    super();
    this.users = users;
  }
  @Override
  public void setValues(PreparedStatement ps, int i) {

    try {
      User user = users.get(i);
      ps.setString(1, user.getUserName());
      ps.setString(2, user.getPassword());
      ps.setClob(3,org.hibernate.engine.jdbc.ClobProxy.generateProxy(user.getContent()));
      ps.setDate(4, user.getUpdatedTime() == null ? null : new java.sql.Date(user.getUpdatedTime().getTime()));
      ps.setString(5, user.getUserType().toString());
      ps.setDate(6, new java.sql.Date(user.getDateofBirth().getTime()));
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }
  @Override
  public int getBatchSize() {
    return users.size();
  }
}

Can anyone help me how to use asynchronous batch updates with large files?

Thanks in advance

================================================================


来源: stackexchange

问:
setup new database in ubuntu using a script
I am trying to automate an app deployment process which includes creating a new postgresql database and configure initial settings in a few lines.
I can already do this via the terminal manually, however I am struggling to get this working from an .sh script, what I have so far which is not working:

```<code>#!/bin/sh
sudo -u postgres psql
read -p "Enter a unique Postgresql db name: " DBN
CREATE DATABASE $DBN;
read -p "Enter a name for Database $DBN: " USN
read -p "Enter a password for user $USN: " USPSD
CREATE USER USN WITH PASSWORD 'USPSD';
ALTER ROLE USN SET client_encoding TO 'utf8';
ALTER ROLE USN SET default_transaction_isolation TO 'read committed';
ALTER ROLE USN SET timezone TO 'UTC';
GRANT ALL PRIVILEGES ON DATABASE DBN TO USN;
\q
</code>```

The above starts starts an interactive postgresql session but doesn't go any further. This is the output:

```<code>could not change directory to "/home/ubuntu": Permission denied
psql (14.5 (Ubuntu 14.5-0ubuntu0.22.04.1))
Type "help" for help.
postgres=#
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to automate an app deployment process which includes creating a new postgresql database and configure initial settings in a few lines.
I can already do this via the terminal manually, however I am struggling to get this working from an .sh script, what I have so far which is not working:

#!/bin/sh
sudo -u postgres psql
read -p "Enter a unique Postgresql db name: " DBN
CREATE DATABASE $DBN;
read -p "Enter a name for Database $DBN: " USN
read -p "Enter a password for user $USN: " USPSD
CREATE USER USN WITH PASSWORD 'USPSD';
ALTER ROLE USN SET client_encoding TO 'utf8';
ALTER ROLE USN SET default_transaction_isolation TO 'read committed';
ALTER ROLE USN SET timezone TO 'UTC';
GRANT ALL PRIVILEGES ON DATABASE DBN TO USN;
\q

The above starts starts an interactive postgresql session but doesn't go any further. This is the output:

could not change directory to "/home/ubuntu": Permission denied
psql (14.5 (Ubuntu 14.5-0ubuntu0.22.04.1))
Type "help" for help.
postgres=#


问:
How to set the size of an NSToolbarItem on macOS Ventura since setMaxSize is deprecated?
Everything works as expected when using [toolbarItem setMaxSize: NSMakeSize(24,24)]- but this function is deprecated now.

I tried to set the layout constraints on the items's view but that does not have any effect.

```<code>        NSView *itemView = toolbarItem.view;
        itemView.translatesAutoresizingMaskIntoConstraints = NO;

        NSLayoutConstraint *widthConstraint = [itemView.widthAnchor constraintEqualToConstant: 24];
        NSLayoutConstraint *heightConstraint = [itemView.heightAnchor constraintEqualToConstant: 24];

        widthConstraint.active = YES;
        heightConstraint.active = YES;
</code>```

Body:
Everything works as expected when using [toolbarItem setMaxSize: NSMakeSize(24,24)]- but this function is deprecated now.

I tried to set the layout constraints on the items's view but that does not have any effect.

        NSView *itemView = toolbarItem.view;
        itemView.translatesAutoresizingMaskIntoConstraints = NO;

        NSLayoutConstraint *widthConstraint = [itemView.widthAnchor constraintEqualToConstant: 24];
        NSLayoutConstraint *heightConstraint = [itemView.heightAnchor constraintEqualToConstant: 24];

        widthConstraint.active = YES;
        heightConstraint.active = YES;


问:
Pandas converts some numbers into zeros or other fixed values
I'm using Python with Pandas through Google Colab for some data analysis. I was analyzing some data through plots and noticed some missing data. However, when I looked at the original Excel data before any Python work, there was no missing data in these places. Somehow it's turning the first four days of a month of hourly data into zeros OR, but only for some of the files and some of the time periods. Following the zeros is also a period of other constant values.

I have four similar data files and two of them seem to be working just fine, but the other two get these zeros at the start of SOME (consecutive) months, while nothing is wrong with the original data. Is there some feature in Pandas that could cause some numbers to turn into zeros or other constant values? The same code is used for all the different files, which are all in the same format.

I thought it could be just a problem with using 'resample' during plotting, but even when I just print the values without 'resample', the values are still missing. I included a figure here to show what the data problem looks like.

Function to read the data:

```<code>def read_elec_data(data_file_name):
  df = pd.read_excel(data_file_name) # Read the original data

  # Convert the time value (30.11.2018 0:00-1:00) into a Pandas-compatible timestamp format (2018-11-30 0:00)
  new = df["Päivämäärä ja tunti"].str.split("-", n = 1, expand = True) # Split the time column by the delimiter and make it into two new columns [0, 1]. The ending hour [1] can be ignored.

  time_data = new[0]
  time_data_fixed = pd.to_datetime(time_data) # Convert the modified time data into datetime format

  df['Aika'] = time_data_fixed # Add the new time column to the dataframe

  # Remove all columns except the new timestamp and energy consumption columns. Rename the consumption according to the building name
  building_name = df['Kohde'][0]
  df.drop(columns =["Päivämäärä ja tunti", "Tunti", 'Kohde', 'Mittarin nimi'], inplace = True) # Remove everything except the new timestamp and energy consumption
  df = df.rename(columns={'Kulutus[kWh]' : building_name})
  df = df.set_index('Aika') # Set the timestamp as the index for the final DataFrame that will be utilized in the calculations

  return df
</code>```

Calling of the function:

```<code>all_electricity_data_list = []

for buildingname in list_of_electricity_data:
  df = read_elec_data(buildingname) # Use the file reading and modification function
  all_electricity_data_list.append(df)

all_electricity_data = pd.concat(all_electricity_data_list, axis=1)
</code>```

Some numbers are converted to zeros or other constant values even though the original data is fine:

Body:
I'm using Python with Pandas through Google Colab for some data analysis. I was analyzing some data through plots and noticed some missing data. However, when I looked at the original Excel data before any Python work, there was no missing data in these places. Somehow it's turning the first four days of a month of hourly data into zeros OR, but only for some of the files and some of the time periods. Following the zeros is also a period of other constant values.

I have four similar data files and two of them seem to be working just fine, but the other two get these zeros at the start of SOME (consecutive) months, while nothing is wrong with the original data. Is there some feature in Pandas that could cause some numbers to turn into zeros or other constant values? The same code is used for all the different files, which are all in the same format.

I thought it could be just a problem with using 'resample' during plotting, but even when I just print the values without 'resample', the values are still missing. I included a figure here to show what the data problem looks like.

Function to read the data:

def read_elec_data(data_file_name):
  df = pd.read_excel(data_file_name) # Read the original data

  # Convert the time value (30.11.2018 0:00-1:00) into a Pandas-compatible timestamp format (2018-11-30 0:00)
  new = df["Päivämäärä ja tunti"].str.split("-", n = 1, expand = True) # Split the time column by the delimiter and make it into two new columns [0, 1]. The ending hour [1] can be ignored.

  time_data = new[0]
  time_data_fixed = pd.to_datetime(time_data) # Convert the modified time data into datetime format

  df['Aika'] = time_data_fixed # Add the new time column to the dataframe

  # Remove all columns except the new timestamp and energy consumption columns. Rename the consumption according to the building name
  building_name = df['Kohde'][0]
  df.drop(columns =["Päivämäärä ja tunti", "Tunti", 'Kohde', 'Mittarin nimi'], inplace = True) # Remove everything except the new timestamp and energy consumption
  df = df.rename(columns={'Kulutus[kWh]' : building_name})
  df = df.set_index('Aika') # Set the timestamp as the index for the final DataFrame that will be utilized in the calculations

  return df

Calling of the function:

all_electricity_data_list = []

for buildingname in list_of_electricity_data:
  df = read_elec_data(buildingname) # Use the file reading and modification function
  all_electricity_data_list.append(df)

all_electricity_data = pd.concat(all_electricity_data_list, axis=1)

Some numbers are converted to zeros or other constant values even though the original data is fine:


问:
custom model for instance seg
this is my code fo rthe instance segmentation on some custom dataset using tensor flow
i am creating the model
import tensorflow as tf

```<code>
# Define the model architecture
model = tf.keras.models.Sequential()

# Add the convolutional layers
model.add(tf.keras.layers.Conv2D(32, (3, 3), padding='same', input_shape=(224, 224, 3)))
model.add(tf.keras.layers.Activation('relu'))
model.add(tf.keras.layers.Conv2D(32, (3, 3)))
model.add(tf.keras.layers.Activation('relu'))
model.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2)))
model.add(tf.keras.layers.Dropout(0.25))

model.add(tf.keras.layers.Conv2D(64, (3, 3), padding='same'))
model.add(tf.keras.layers.Activation('relu'))
model.add(tf.keras.layers.Conv2D(64, (3, 3)))
model.add(tf.keras.layers.Activation('relu'))
model.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2)))
model.add(tf.keras.layers.Dropout(0.25))

model.add(tf.keras.layers.Conv2D(128, (3, 3), padding='same'))
model.add(tf.keras.layers.Activation('relu'))
model.add(tf.keras.layers.Conv2D(128, (3, 3)))
model.add(tf.keras.layers.Activation('relu'))
model.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2)))
model.add(tf.keras.layers.Dropout(0.25))

# Flatten the output and add the fully connected layers
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(512))
model.add(tf.keras.layers.Activation('relu'))
model.add(tf.keras.layers.Dropout(0.5))

# Reshape the output of the fully connected layer to have a
model.add(tf.keras.layers.Reshape((1, 1, 512)))

# Add a convolutional layer with a kernel size of 1x1 and sigmoid activation
model.add(tf.keras.layers.Conv2D(1, (1, 1), activation='sigmoid'))

# Flatten the mask to a 2D array
model.add(tf.keras.layers.Reshape((224*224,1)))
</code>```

i try compiling it but it is givining an error what is that i  am doing wrong. i have little knowledge of computervision but i am trying to learn more an more please help me here the error is the flatenning layer

```<code>ValueError                                Traceback (most recent call last)
<ipython-input-8-ad4d85d788ab> in <module>
     40
     41 # Flatten the mask to a 2D array
---> 42 model.add(tf.keras.layers.Reshape((224*224,1)))
     43 # Compile the model with the Adam optimizer and
     44 model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\training\tracking\base.py in _method_wrapper(self, *args, **kwargs)
    528     self._self_setattr_tracking = False  # pylint: disable=protected-access
    529     try:
--> 530       result = method(self, *args, **kwargs)
    531     finally:
    532       self._self_setattr_tracking = previous_value  # pylint: disable=protected-access

D:\Anaconda\envs\tensorflow\lib\site-packages\keras\engine\sequential.py in add(self, layer)
    215       # If the model is being built continuously on top of an input layer:
    216       # refresh its output.
--> 217       output_tensor = layer(self.outputs[0])
    218       if len(tf.nest.flatten(output_tensor)) != 1:
    219         raise ValueError(SINGLE_LAYER_OUTPUT_ERROR_MSG)

D:\Anaconda\envs\tensorflow\lib\site-packages\keras\engine\base_layer.py in __call__(self, *args, **kwargs)
    975     if _in_functional_construction_mode(self, inputs, args, kwargs, input_list):
    976       return self._functional_construction_call(inputs, args, kwargs,
--> 977                                                 input_list)
    978
    979     # Maintains info about the `Layer.call` stack.

D:\Anaconda\envs\tensorflow\lib\site-packages\keras\engine\base_layer.py in _functional_construction_call(self, inputs, args, kwargs, input_list)
   1113       # Check input assumptions set after layer building, e.g. input shape.
   1114       outputs = self._keras_tensor_symbolic_call(
-> 1115           inputs, input_masks, args, kwargs)
   1116
   1117       if outputs is None:

D:\Anaconda\envs\tensorflow\lib\site-packages\keras\engine\base_layer.py in _keras_tensor_symbolic_call(self, inputs, input_masks, args, kwargs)
    846       return tf.nest.map_structure(keras_tensor.KerasTensor, output_signature)
    847     else:
--> 848       return self._infer_output_signature(inputs, args, kwargs, input_masks)
    849
    850   def _infer_output_signature(self, inputs, args, kwargs, input_masks):

D:\Anaconda\envs\tensorflow\lib\site-packages\keras\engine\base_layer.py in _infer_output_signature(self, inputs, args, kwargs, input_masks)
    886           self._maybe_build(inputs)
    887           inputs = self._maybe_cast_inputs(inputs)
--> 888           outputs = call_fn(inputs, *args, **kwargs)
    889
    890         self._handle_activity_regularization(inputs, outputs)

D:\Anaconda\envs\tensorflow\lib\site-packages\keras\layers\core.py in call(self, inputs)
    537       # Set the static shape for the result since it might lost during array_ops
    538       # reshape, eg, some `None` dim in the result could be inferred.
--> 539       result.set_shape(self.compute_output_shape(inputs.shape))
    540     return result
    541

D:\Anaconda\envs\tensorflow\lib\site-packages\keras\layers\core.py in compute_output_shape(self, input_shape)
    528       output_shape = [input_shape[0]]
    529       output_shape += self._fix_unknown_dimension(input_shape[1:],
--> 530                                                   self.target_shape)
    531     return tf.TensorShape(output_shape)
    532

D:\Anaconda\envs\tensorflow\lib\site-packages\keras\layers\core.py in _fix_unknown_dimension(self, input_shape, output_shape)
    516       output_shape[unknown] = original // known
    517     elif original != known:
--> 518       raise ValueError(msg)
    519     return output_shape
    520

ValueError: total size of new array must be unchanged, input_shape = [1, 1, 1], output_shape = [50176, 1]
</code>```

Title: custom model for instance seg

Body:
this is my code fo rthe instance segmentation on some custom dataset using tensor flow
i am creating the model
import tensorflow as tf

# Define the model architecture
model = tf.keras.models.Sequential()

# Add the convolutional layers
model.add(tf.keras.layers.Conv2D(32, (3, 3), padding='same', input_shape=(224, 224, 3)))
model.add(tf.keras.layers.Activation('relu'))
model.add(tf.keras.layers.Conv2D(32, (3, 3)))
model.add(tf.keras.layers.Activation('relu'))
model.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2)))
model.add(tf.keras.layers.Dropout(0.25))

model.add(tf.keras.layers.Conv2D(64, (3, 3), padding='same'))
model.add(tf.keras.layers.Activation('relu'))
model.add(tf.keras.layers.Conv2D(64, (3, 3)))
model.add(tf.keras.layers.Activation('relu'))
model.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2)))
model.add(tf.keras.layers.Dropout(0.25))

model.add(tf.keras.layers.Conv2D(128, (3, 3), padding='same'))
model.add(tf.keras.layers.Activation('relu'))
model.add(tf.keras.layers.Conv2D(128, (3, 3)))
model.add(tf.keras.layers.Activation('relu'))
model.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2)))
model.add(tf.keras.layers.Dropout(0.25))

# Flatten the output and add the fully connected layers
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(512))
model.add(tf.keras.layers.Activation('relu'))
model.add(tf.keras.layers.Dropout(0.5))

# Reshape the output of the fully connected layer to have a
model.add(tf.keras.layers.Reshape((1, 1, 512)))

# Add a convolutional layer with a kernel size of 1x1 and sigmoid activation
model.add(tf.keras.layers.Conv2D(1, (1, 1), activation='sigmoid'))

# Flatten the mask to a 2D array
model.add(tf.keras.layers.Reshape((224*224,1)))

i try compiling it but it is givining an error what is that i  am doing wrong. i have little knowledge of computervision but i am trying to learn more an more please help me here the error is the flatenning layer

ValueError                                Traceback (most recent call last)
<ipython-input-8-ad4d85d788ab> in <module>
     40
     41 # Flatten the mask to a 2D array
---> 42 model.add(tf.keras.layers.Reshape((224*224,1)))
     43 # Compile the model with the Adam optimizer and
     44 model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\training\tracking\base.py in _method_wrapper(self, *args, **kwargs)
    528     self._self_setattr_tracking = False  # pylint: disable=protected-access
    529     try:
--> 530       result = method(self, *args, **kwargs)
    531     finally:
    532       self._self_setattr_tracking = previous_value  # pylint: disable=protected-access

D:\Anaconda\envs\tensorflow\lib\site-packages\keras\engine\sequential.py in add(self, layer)
    215       # If the model is being built continuously on top of an input layer:
    216       # refresh its output.
--> 217       output_tensor = layer(self.outputs[0])
    218       if len(tf.nest.flatten(output_tensor)) != 1:
    219         raise ValueError(SINGLE_LAYER_OUTPUT_ERROR_MSG)

D:\Anaconda\envs\tensorflow\lib\site-packages\keras\engine\base_layer.py in __call__(self, *args, **kwargs)
    975     if _in_functional_construction_mode(self, inputs, args, kwargs, input_list):
    976       return self._functional_construction_call(inputs, args, kwargs,
--> 977                                                 input_list)
    978
    979     # Maintains info about the `Layer.call` stack.

D:\Anaconda\envs\tensorflow\lib\site-packages\keras\engine\base_layer.py in _functional_construction_call(self, inputs, args, kwargs, input_list)
   1113       # Check input assumptions set after layer building, e.g. input shape.
   1114       outputs = self._keras_tensor_symbolic_call(
-> 1115           inputs, input_masks, args, kwargs)
   1116
   1117       if outputs is None:

D:\Anaconda\envs\tensorflow\lib\site-packages\keras\engine\base_layer.py in _keras_tensor_symbolic_call(self, inputs, input_masks, args, kwargs)
    846       return tf.nest.map_structure(keras_tensor.KerasTensor, output_signature)
    847     else:
--> 848       return self._infer_output_signature(inputs, args, kwargs, input_masks)
    849
    850   def _infer_output_signature(self, inputs, args, kwargs, input_masks):

D:\Anaconda\envs\tensorflow\lib\site-packages\keras\engine\base_layer.py in _infer_output_signature(self, inputs, args, kwargs, input_masks)
    886           self._maybe_build(inputs)
    887           inputs = self._maybe_cast_inputs(inputs)
--> 888           outputs = call_fn(inputs, *args, **kwargs)
    889
    890         self._handle_activity_regularization(inputs, outputs)

D:\Anaconda\envs\tensorflow\lib\site-packages\keras\layers\core.py in call(self, inputs)
    537       # Set the static shape for the result since it might lost during array_ops
    538       # reshape, eg, some `None` dim in the result could be inferred.
--> 539       result.set_shape(self.compute_output_shape(inputs.shape))
    540     return result
    541

D:\Anaconda\envs\tensorflow\lib\site-packages\keras\layers\core.py in compute_output_shape(self, input_shape)
    528       output_shape = [input_shape[0]]
    529       output_shape += self._fix_unknown_dimension(input_shape[1:],
--> 530                                                   self.target_shape)
    531     return tf.TensorShape(output_shape)
    532

D:\Anaconda\envs\tensorflow\lib\site-packages\keras\layers\core.py in _fix_unknown_dimension(self, input_shape, output_shape)
    516       output_shape[unknown] = original // known
    517     elif original != known:
--> 518       raise ValueError(msg)
    519     return output_shape
    520

ValueError: total size of new array must be unchanged, input_shape = [1, 1, 1], output_shape = [50176, 1]


问:
Webhook call failed. Error: UNAVAILABLE, State: URL_UNREACHABLE, Reason: UNREACHABLE_5xx, HTTP status code: 500.|| Firebase || Dialogflow
I am trying to build a chat Bot with Dialogflow Essentials all the default code runs perfectly but when I write code to connect my Firebase Realtime database and make one intent after deploying when I call the intent it give me error below is my code

'use strict';

const functions = require('firebase-functions');
const firebaseAdmin = require("firebase-admin");
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');

process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements

 firebaseAdmin.initializeApp({
  credential:firebaseAdmin.credential.applicationDefault(),
   databaseURL: "https://*****************************************.firebasedatabase.app/.firebaseio.com",
  //databaseURL:"ws://****************************************.firebasedatabase.app/",
});

exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
  const agent = new WebhookClient({ request, response });
  console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
  console.log('Dialogflow Request body: ' + JSON.stringify(request.body));

  function welcome(agent) {
    agent.add(`Welcome to akvo agent!`);
  }

  function fallback(agent) {
    agent.add(`I didn't understand`);
    agent.add(`I'm sorry, can you try again?`);
  }

  function getFromFirebase(agent){
    return firebaseAdmin.database().ref('/All_Chassis').on("value", function(snapshot){
    var boardid=snapshot.val();
      agent.add(boardid);
    });
  }
  let intentMap = new Map();
  intentMap.set('Default Welcome Intent', welcome);
  intentMap.set('Default Fallback Intent', fallback);
  intentMap.set('board id', getFromFirebase);

  agent.handleRequest(intentMap);
});```

When i am calling the intent i am getting this response.

in Diagnostic info i am getting this error : Webhook call failed. Error: UNAVAILABLE, State: URL_UNREACHABLE, Reason: UNREACHABLE_5xx, HTTP status code: 500.

and in logs i am getting this error

 "Error: FIREBASE FATAL ERROR: Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com  at fatal (/workspace/node_modules/@firebase/database/dist/index.node.cjs.js:339:11) at parseRepoInfo (/workspace/node_modules/@firebase/database/dist/index.node.cjs.js:1265:9) at RepoManager.databaseFromApp (/workspace/node_modules/@firebase/database/dist/index.node.cjs.js:15055:25) at Object.initStandalone (/workspace/node_modules/@firebase/database/dist/index.node.cjs.js:15581:45) at DatabaseService.getDatabase (/workspace/node_modules/firebase-admin/lib/database/database.js:63:23) at FirebaseApp.database (/workspace/node_modules/firebase-admin/lib/firebase-app.js:231:24) at FirebaseNamespace.fn (/workspace/node_modules/firebase-admin/lib/firebase-namespace.js:280:45) at getFromFirebase (/workspace/index.js:35:26) at WebhookClient.handleRequest (/workspace/node_modules/dialogflow-fulfillment/src/dialogflow-fulfillment.js:303:44) at exports.dialogflowFirebaseFulfillment.functions.https.onRequest (/workspace/index.js:78:9)"

Body:
I am trying to build a chat Bot with Dialogflow Essentials all the default code runs perfectly but when I write code to connect my Firebase Realtime database and make one intent after deploying when I call the intent it give me error below is my code

'use strict';

const functions = require('firebase-functions');
const firebaseAdmin = require("firebase-admin");
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');

process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements

 firebaseAdmin.initializeApp({
  credential:firebaseAdmin.credential.applicationDefault(),
   databaseURL: "https://*****************************************.firebasedatabase.app/.firebaseio.com",
  //databaseURL:"ws://****************************************.firebasedatabase.app/",
});

exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
  const agent = new WebhookClient({ request, response });
  console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
  console.log('Dialogflow Request body: ' + JSON.stringify(request.body));

  function welcome(agent) {
    agent.add(`Welcome to akvo agent!`);
  }

  function fallback(agent) {
    agent.add(`I didn't understand`);
    agent.add(`I'm sorry, can you try again?`);
  }

  function getFromFirebase(agent){
    return firebaseAdmin.database().ref('/All_Chassis').on("value", function(snapshot){
    var boardid=snapshot.val();
      agent.add(boardid);
    });
  }
  let intentMap = new Map();
  intentMap.set('Default Welcome Intent', welcome);
  intentMap.set('Default Fallback Intent', fallback);
  intentMap.set('board id', getFromFirebase);

  agent.handleRequest(intentMap);
});

When i am calling the intent i am getting this response.

in Diagnostic info i am getting this error : Webhook call failed. Error: UNAVAILABLE, State: URL_UNREACHABLE, Reason: UNREACHABLE_5xx, HTTP status code: 500.

and in logs i am getting this error

 "Error: FIREBASE FATAL ERROR: Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com  at fatal (/workspace/node_modules/@firebase/database/dist/index.node.cjs.js:339:11) at parseRepoInfo (/workspace/node_modules/@firebase/database/dist/index.node.cjs.js:1265:9) at RepoManager.databaseFromApp (/workspace/node_modules/@firebase/database/dist/index.node.cjs.js:15055:25) at Object.initStandalone (/workspace/node_modules/@firebase/database/dist/index.node.cjs.js:15581:45) at DatabaseService.getDatabase (/workspace/node_modules/firebase-admin/lib/database/database.js:63:23) at FirebaseApp.database (/workspace/node_modules/firebase-admin/lib/firebase-app.js:231:24) at FirebaseNamespace.fn (/workspace/node_modules/firebase-admin/lib/firebase-namespace.js:280:45) at getFromFirebase (/workspace/index.js:35:26) at WebhookClient.handleRequest (/workspace/node_modules/dialogflow-fulfillment/src/dialogflow-fulfillment.js:303:44) at exports.dialogflowFirebaseFulfillment.functions.https.onRequest (/workspace/index.js:78:9)"


问:
gnu linker and underscore
Linking (using GNU linker) two modules:

module A calls external function sprintf <-- no ending underscore

module B provides sprintf_  <-- ending undesrcore

The reference sprintf is connected with reference sprintf_

I was expecting an undefined reference. Are there rules about underscores in relation with the GNU linker?

Title: gnu linker and underscore


问:
PyTorch Autoencoder - artifacts during image reconstruction
I have a problem with implementation of an autoencoder in Pytorch. I have input images in grayscale of size 100x100 pixels. During reconstruction I have some artifacts on the right side and on the bottom of the reconstructed image:
enter image description here

The architecture of the autoencoder is as follows:

```<code>
class Encoder(nn.Module):

    def __init__(self,
                 encoded_space_dim,
                 lin_dims):
        super().__init__()

        self.encoder_cnn = nn.Sequential(
            nn.Conv2d(1, 8, 3, stride=2, padding=1),    #1 image divided to 8 feature maps,                                                                 kernel 3x3
            nn.ReLU(True),
            nn.Conv2d(8, 16, 3, stride=2, padding=1),   #8 feature maps divided to 16, kernel 3x3
            nn.ReLU(True),
            nn.Conv2d(16, 32, 2, stride=2, padding=0),  #16 feature maps divided to 32, kernel 2x2 and padding 0 in order to achieve image size 12x12 pixels
            nn.ReLU(True),
            nn.Conv2d(32, 64, 3, stride=2, padding=1),  #32 feature maps to 64, kernel 3x3
            nn.ReLU(True),
            nn.Conv2d(64, 128, 3, stride=2, padding=1), #64 feature maps to 128, kernel 3x3
            nn.ReLU(True)
        )

        self.flatten = nn.Flatten(start_dim=1)

        self.encoder_lin = nn.Sequential(
            nn.Linear(128*3*3, lin_dims[0]),            #3x3(kernel size) x  number of feature maps in last layer so in this case 128
            nn.ReLU(True),
            nn.Linear(lin_dims[0], lin_dims[1]),
            nn.ReLU(True),
            nn.Linear(lin_dims[1], encoded_space_dim)
        )

    def forward(self, x):
        x = self.encoder_cnn(x)
        x = self.flatten(x)
        x = self.encoder_lin(x)
        return x

class Decoder(nn.Module):

    def __init__(self,
                 encoded_space_dim,
                 lin_dims):
        super().__init__()

        self.decoder_lin = nn.Sequential(
            nn.Linear(encoded_space_dim, lin_dims[0]),
            nn.ReLU(True),
            nn.Linear(lin_dims[0], lin_dims[1]),
            nn.ReLU(True),
            nn.Linear(lin_dims[1], 128*3*3),
            nn.ReLU(True)
        )

        self.decoder_cnn = nn.Sequential(
            nn.ConvTranspose2d(128, 64, 3, stride=2, padding=1, output_padding=1),   #128 maps to 64, kernel 3x3
            nn.ReLU(True),
            nn.ConvTranspose2d(64, 32, 3, stride=2, padding=1, output_padding=1),    #64 maps to 32, kernel 3x3
            nn.ReLU(True),
            nn.ConvTranspose2d(32, 16, 2, stride=2, padding=0, output_padding=1),    #32 maps to 16, kernel 2x2
            nn.ReLU(True),
            nn.ConvTranspose2d(16, 8, 3, stride=2, padding=1, output_padding=1),     #16 maps to 8, kernel 3x3
            nn.ReLU(True),
            nn.ConvTranspose2d(8, 1, 3, stride=2, padding=1, output_padding=1)       #8 maps to 1, kernel 3x3
        )

    def forward(self, x):
        x = self.decoder_lin(x)
        x = x.view(-1, 128, 3, 3)
        x = self.decoder_cnn(x)
        x = torch.sigmoid(x)
        return x
</code>```
```<code># print encoder summary
summary(encoder, (1, 100, 100))
</code>```
```<code>----------------------------------------------------------------
        Layer (type)               Output Shape         Param #
================================================================
            Conv2d-1            [-1, 8, 50, 50]              80
              ReLU-2            [-1, 8, 50, 50]               0
            Conv2d-3           [-1, 16, 25, 25]           1,168
              ReLU-4           [-1, 16, 25, 25]               0
            Conv2d-5           [-1, 32, 12, 12]           2,080
              ReLU-6           [-1, 32, 12, 12]               0
            Conv2d-7             [-1, 64, 6, 6]          18,496
              ReLU-8             [-1, 64, 6, 6]               0
            Conv2d-9            [-1, 128, 3, 3]          73,856
             ReLU-10            [-1, 128, 3, 3]               0
          Flatten-11                 [-1, 1152]               0
           Linear-12                 [-1, 1000]       1,153,000
             ReLU-13                 [-1, 1000]               0
           Linear-14                  [-1, 750]         750,750
             ReLU-15                  [-1, 750]               0
           Linear-16                  [-1, 500]         375,500
================================================================
Total params: 2,374,930
Trainable params: 2,374,930
Non-trainable params: 0
----------------------------------------------------------------
Input size (MB): 0.04
...
Forward/backward pass size (MB): 0.62
Params size (MB): 9.06
Estimated Total Size (MB): 9.72
----------------------------------------------------------------
</code>```
```<code># print decoder summary
summary(decoder, (1, encoded_space_dim))
</code>```
```<code>----------------------------------------------------------------
        Layer (type)               Output Shape         Param #
================================================================
            Linear-1               [-1, 1, 750]         375,750
              ReLU-2               [-1, 1, 750]               0
            Linear-3              [-1, 1, 1000]         751,000
              ReLU-4              [-1, 1, 1000]               0
            Linear-5              [-1, 1, 1152]       1,153,152
              ReLU-6              [-1, 1, 1152]               0
   ConvTranspose2d-7             [-1, 64, 6, 6]          73,792
              ReLU-8             [-1, 64, 6, 6]               0
   ConvTranspose2d-9           [-1, 32, 12, 12]          18,464
             ReLU-10           [-1, 32, 12, 12]               0
  ConvTranspose2d-11           [-1, 16, 25, 25]           2,064
             ReLU-12           [-1, 16, 25, 25]               0
  ConvTranspose2d-13            [-1, 8, 50, 50]           1,160
             ReLU-14            [-1, 8, 50, 50]               0
  ConvTranspose2d-15          [-1, 1, 100, 100]              73
================================================================
Total params: 2,375,455
Trainable params: 2,375,455
Non-trainable params: 0
----------------------------------------------------------------
Input size (MB): 0.00
Forward/backward pass size (MB): 0.68
Params size (MB): 9.06
Estimated Total Size (MB): 9.75
----------------------------------------------------------------
</code>```
```<code>loss_fn = nn.L1Loss()
batch_size = 128

#latent space
encoded_space_dim = 500
enc_dims = [1000, 750]
dec_dims = [750, 1000]

# Encoder & Decoder
encoder = Encoder(
    encoded_space_dim=encoded_space_dim,
    lin_dims=enc_dims
).to(device)

decoder = Decoder(
    encoded_space_dim=encoded_space_dim,
    lin_dims=dec_dims
).to(device)

# Optimizer
params_to_optimize = [
    {'params': encoder.parameters()},
    {'params': decoder.parameters()}
]
optim = torch.optim.Adam(params_to_optimize)
</code>```

In order to calculate the architecture I used the following formula:
((n+2p-f)/s)+1, where:
n - image size, in my case 100 in the first layer
p - padding,
s - stride,
f - kernel size,
1 is bias.

To sum up, I think the architecture is ok, if I try to play for example with padding I receive an error of wrong dimensions. I cant see any other way to implement it. If this would be casused by oversampling the whole picture would be bad and not only two edges so I think oversampling is also not the problem. Any advices? I am running out of ideas.
Best regards

Body:
I have a problem with implementation of an autoencoder in Pytorch. I have input images in grayscale of size 100x100 pixels. During reconstruction I have some artifacts on the right side and on the bottom of the reconstructed image:
enter image description here

The architecture of the autoencoder is as follows:

class Encoder(nn.Module):

    def __init__(self,
                 encoded_space_dim,
                 lin_dims):
        super().__init__()

        self.encoder_cnn = nn.Sequential(
            nn.Conv2d(1, 8, 3, stride=2, padding=1),    #1 image divided to 8 feature maps,                                                                 kernel 3x3
            nn.ReLU(True),
            nn.Conv2d(8, 16, 3, stride=2, padding=1),   #8 feature maps divided to 16, kernel 3x3
            nn.ReLU(True),
            nn.Conv2d(16, 32, 2, stride=2, padding=0),  #16 feature maps divided to 32, kernel 2x2 and padding 0 in order to achieve image size 12x12 pixels
            nn.ReLU(True),
            nn.Conv2d(32, 64, 3, stride=2, padding=1),  #32 feature maps to 64, kernel 3x3
            nn.ReLU(True),
            nn.Conv2d(64, 128, 3, stride=2, padding=1), #64 feature maps to 128, kernel 3x3
            nn.ReLU(True)
        )

        self.flatten = nn.Flatten(start_dim=1)

        self.encoder_lin = nn.Sequential(
            nn.Linear(128*3*3, lin_dims[0]),            #3x3(kernel size) x  number of feature maps in last layer so in this case 128
            nn.ReLU(True),
            nn.Linear(lin_dims[0], lin_dims[1]),
            nn.ReLU(True),
            nn.Linear(lin_dims[1], encoded_space_dim)
        )

    def forward(self, x):
        x = self.encoder_cnn(x)
        x = self.flatten(x)
        x = self.encoder_lin(x)
        return x

class Decoder(nn.Module):

    def __init__(self,
                 encoded_space_dim,
                 lin_dims):
        super().__init__()

        self.decoder_lin = nn.Sequential(
            nn.Linear(encoded_space_dim, lin_dims[0]),
            nn.ReLU(True),
            nn.Linear(lin_dims[0], lin_dims[1]),
            nn.ReLU(True),
            nn.Linear(lin_dims[1], 128*3*3),
            nn.ReLU(True)
        )

        self.decoder_cnn = nn.Sequential(
            nn.ConvTranspose2d(128, 64, 3, stride=2, padding=1, output_padding=1),   #128 maps to 64, kernel 3x3
            nn.ReLU(True),
            nn.ConvTranspose2d(64, 32, 3, stride=2, padding=1, output_padding=1),    #64 maps to 32, kernel 3x3
            nn.ReLU(True),
            nn.ConvTranspose2d(32, 16, 2, stride=2, padding=0, output_padding=1),    #32 maps to 16, kernel 2x2
            nn.ReLU(True),
            nn.ConvTranspose2d(16, 8, 3, stride=2, padding=1, output_padding=1),     #16 maps to 8, kernel 3x3
            nn.ReLU(True),
            nn.ConvTranspose2d(8, 1, 3, stride=2, padding=1, output_padding=1)       #8 maps to 1, kernel 3x3
        )

    def forward(self, x):
        x = self.decoder_lin(x)
        x = x.view(-1, 128, 3, 3)
        x = self.decoder_cnn(x)
        x = torch.sigmoid(x)
        return x

# print encoder summary
summary(encoder, (1, 100, 100))

----------------------------------------------------------------
        Layer (type)               Output Shape         Param #
================================================================
            Conv2d-1            [-1, 8, 50, 50]              80
              ReLU-2            [-1, 8, 50, 50]               0
            Conv2d-3           [-1, 16, 25, 25]           1,168
              ReLU-4           [-1, 16, 25, 25]               0
            Conv2d-5           [-1, 32, 12, 12]           2,080
              ReLU-6           [-1, 32, 12, 12]               0
            Conv2d-7             [-1, 64, 6, 6]          18,496
              ReLU-8             [-1, 64, 6, 6]               0
            Conv2d-9            [-1, 128, 3, 3]          73,856
             ReLU-10            [-1, 128, 3, 3]               0
          Flatten-11                 [-1, 1152]               0
           Linear-12                 [-1, 1000]       1,153,000
             ReLU-13                 [-1, 1000]               0
           Linear-14                  [-1, 750]         750,750
             ReLU-15                  [-1, 750]               0
           Linear-16                  [-1, 500]         375,500
================================================================
Total params: 2,374,930
Trainable params: 2,374,930
Non-trainable params: 0
----------------------------------------------------------------
Input size (MB): 0.04
...
Forward/backward pass size (MB): 0.62
Params size (MB): 9.06
Estimated Total Size (MB): 9.72
----------------------------------------------------------------

# print decoder summary
summary(decoder, (1, encoded_space_dim))

----------------------------------------------------------------
        Layer (type)               Output Shape         Param #
================================================================
            Linear-1               [-1, 1, 750]         375,750
              ReLU-2               [-1, 1, 750]               0
            Linear-3              [-1, 1, 1000]         751,000
              ReLU-4              [-1, 1, 1000]               0
            Linear-5              [-1, 1, 1152]       1,153,152
              ReLU-6              [-1, 1, 1152]               0
   ConvTranspose2d-7             [-1, 64, 6, 6]          73,792
              ReLU-8             [-1, 64, 6, 6]               0
   ConvTranspose2d-9           [-1, 32, 12, 12]          18,464
             ReLU-10           [-1, 32, 12, 12]               0
  ConvTranspose2d-11           [-1, 16, 25, 25]           2,064
             ReLU-12           [-1, 16, 25, 25]               0
  ConvTranspose2d-13            [-1, 8, 50, 50]           1,160
             ReLU-14            [-1, 8, 50, 50]               0
  ConvTranspose2d-15          [-1, 1, 100, 100]              73
================================================================
Total params: 2,375,455
Trainable params: 2,375,455
Non-trainable params: 0
----------------------------------------------------------------
Input size (MB): 0.00
Forward/backward pass size (MB): 0.68
Params size (MB): 9.06
Estimated Total Size (MB): 9.75
----------------------------------------------------------------

loss_fn = nn.L1Loss()
batch_size = 128

#latent space
encoded_space_dim = 500
enc_dims = [1000, 750]
dec_dims = [750, 1000]

# Encoder & Decoder
encoder = Encoder(
    encoded_space_dim=encoded_space_dim,
    lin_dims=enc_dims
).to(device)

decoder = Decoder(
    encoded_space_dim=encoded_space_dim,
    lin_dims=dec_dims
).to(device)

# Optimizer
params_to_optimize = [
    {'params': encoder.parameters()},
    {'params': decoder.parameters()}
]
optim = torch.optim.Adam(params_to_optimize)

In order to calculate the architecture I used the following formula:
((n+2p-f)/s)+1, where:
n - image size, in my case 100 in the first layer
p - padding,
s - stride,
f - kernel size,
1 is bias.

To sum up, I think the architecture is ok, if I try to play for example with padding I receive an error of wrong dimensions. I cant see any other way to implement it. If this would be casused by oversampling the whole picture would be bad and not only two edges so I think oversampling is also not the problem. Any advices? I am running out of ideas.
Best regards


问:
Formatting DynamoDB data to normal JSON in AWS Lambda in Rust
How can I convert a DynamoDB view JSON to a normal JSON in Rust?

For example, I want to convert:

{
 "id": {
  "N": "123"
 },
 "name": {
  "S": "some name"
 }
}
```
<p>to this:</p>
<pre class="lang-json prettyprint-override"><code>{
 "id": 123,
 "name": "some name"
}
</code>```

I've found this question Formatting DynamoDB data to normal JSON in AWS Lambda with several answers for Node.js or Python.

Is there a converter like unmarshall (JavaScript) or TypeDeserializer.deserialize (Python) for Rust in the aws-sdk-rust?

Body:
How can I convert a DynamoDB view JSON to a normal JSON in Rust?

For example, I want to convert:

{
 "id": {
  "N": "123"
 },
 "name": {
  "S": "some name"
 }
}

to this:

{
 "id": 123,
 "name": "some name"
}

I've found this question Formatting DynamoDB data to normal JSON in AWS Lambda with several answers for Node.js or Python.

Is there a converter like unmarshall (JavaScript) or TypeDeserializer.deserialize (Python) for Rust in the aws-sdk-rust?


问:
istio authorization policy and jwt check
xx

Hello everyone,

I am playing with istio and security based on a JWT token.

I am able to deny access to services based on simple token elements (ie. when the field is of type key and simple value). I would like to know if we can create rules when the field value is an array. I am not able to figure out if it's possible after many tries.

For example, let's consider the JWT with the following data

```<code>{
  "sub": "user",
  "aud": "mgu",
  "scope": [
    "openid",
    "address",
    "email",
    "phone",
    "profile"
  ],
  "iss": "http://host.docker.internal:8001",
  "exp": 1670583577,
  "iat": 1670579977,
  "authorities": [
    "AUTH1",
    "AUTH2"
  ],
  "jti": "mgu-proxy"
}
</code>```

I would like to allow access when one of the authorities is AUTH1.

I have tried with key of type

key: request.auth.claims[authorities][*]

key: request.auth.claims[authorities]

but none of them work.

Does someone know how to do it if it is possible?

Thanks for any help :)

PS: here is my AuthorizationPolicy.yaml file

```<code>apiVersion: security.istio.io/v1beta1
kind: AuthorizationPolicy
metadata:
  name: httpbin
spec:
  action: ALLOW
  selector:
    matchLabels:
      istio: ingressgateway
  rules:
  - when:
    - key: request.auth.audiences
      values: ["mgu"]
    - key: request.auth.claims[jti]
      values: ["mgu-proxy"]
</code>```

and I have tried with (and many others...)

```<code>- key: request.auth.claims[authorities][*]
  values: ["AUTH1"]
</code>```

and

```<code>- key: request.auth.claims[authorities]
  values: ["AUTH1"]
</code>```

Body:
xx

Hello everyone,

I am playing with istio and security based on a JWT token.

I am able to deny access to services based on simple token elements (ie. when the field is of type key and simple value). I would like to know if we can create rules when the field value is an array. I am not able to figure out if it's possible after many tries.

For example, let's consider the JWT with the following data

{
  "sub": "user",
  "aud": "mgu",
  "scope": [
    "openid",
    "address",
    "email",
    "phone",
    "profile"
  ],
  "iss": "http://host.docker.internal:8001",
  "exp": 1670583577,
  "iat": 1670579977,
  "authorities": [
    "AUTH1",
    "AUTH2"
  ],
  "jti": "mgu-proxy"
}

I would like to allow access when one of the authorities is AUTH1.

I have tried with key of type

key: request.auth.claims[authorities][*]

key: request.auth.claims[authorities]

but none of them work.

Does someone know how to do it if it is possible?

Thanks for any help :)

PS: here is my AuthorizationPolicy.yaml file

apiVersion: security.istio.io/v1beta1
kind: AuthorizationPolicy
metadata:
  name: httpbin
spec:
  action: ALLOW
  selector:
    matchLabels:
      istio: ingressgateway
  rules:
  - when:
    - key: request.auth.audiences
      values: ["mgu"]
    - key: request.auth.claims[jti]
      values: ["mgu-proxy"]

and I have tried with (and many others...)

- key: request.auth.claims[authorities][*]
  values: ["AUTH1"]

and

- key: request.auth.claims[authorities]
  values: ["AUTH1"]


问:
Moving information from an Excel file into a Word document
I am coding in VBA in Excel. I have an Excel sheet with information. I have two sheets titled: Finance and Invoice. I want to the Finance page to have cells which I would fill out - just by typing in the cells. And then I want the Invoice page to have specific cells which are auto-populated from the information in the Finance sheet.

Then, I want the cells on the Invoice page to be moved into a Word document. I am using a macro I've titled Macro2.

In the top part of the code, I am copying information from cells in the Finance sheet into the Invoice sheet. That works. But then I am trying to take the filled out information in the Finance sheet and move it into a Word doc. I looked for code online - but it isn't working for me. The cells that I want to move into a Word doc are B1 through D19 on the Invoice page. The name of my Excel file is FinanceMarketing.

```<code>Sub Macro2()
'
' Macro2 Macro
'
    'Ask user for input
    userinput = InputBox("Type Associated Letter corresponding to Desired Invoice Population:")
    'Copy Name
    Sheets("Finance").Range("B2").Copy Destination:=Sheets("Invoice").Range("D3")
    'Copy Email
    Sheets("Finance").Range("C2").Copy Destination:=Sheets("Invoice").Range("D4")
    'Copy Adress
    Sheets("Finance").Range("D2").Copy Destination:=Sheets("Invoice").Range("D5")
    'Copy Date
    Sheets("Finance").Range("E2").Copy Destination:=Sheets("Invoice").Range("B8")
    'Copy Amount Owed
    Sheets("Finance").Range("I2").Copy Destination:=Sheets("Invoice").Range("D8")

    'From here down in the part of the code that I found online to move the excel into word which isn't working
'Using Early Binding

    Dim wordApp As Word.Application
    Dim mydoc As Word.Document

    'Creating a new instance of word only if there no other instances
    Set wordApp = New Word.Application

    'Making word App Visible
    wordApp.Visible = True

    'Creating a new document
    Set mydoc = wordApp.Documents.Add()

    'copying the content from excel sheet
    FinanceMarketing.Worksheets("Invoice").Range("B1:D19").Copy

    'Pasting on the document
    mydoc.Paragraphs(1).Range.PasteExcelTable _
                               LinkedToExcel:=False, _
                               WordFormatting:=False, _
                               RTF:=False

    'saving the document
    mydoc.SaveAs2 "MyDoc"

    'closing the document
    'mydoc.Close

    'Emptying the Clipboard
    'CutCopyMode = False
End Sub
</code>```

Help to get moving the info into word would be very appreciated!

Body:
I am coding in VBA in Excel. I have an Excel sheet with information. I have two sheets titled: Finance and Invoice. I want to the Finance page to have cells which I would fill out - just by typing in the cells. And then I want the Invoice page to have specific cells which are auto-populated from the information in the Finance sheet.

Then, I want the cells on the Invoice page to be moved into a Word document. I am using a macro I've titled Macro2.

In the top part of the code, I am copying information from cells in the Finance sheet into the Invoice sheet. That works. But then I am trying to take the filled out information in the Finance sheet and move it into a Word doc. I looked for code online - but it isn't working for me. The cells that I want to move into a Word doc are B1 through D19 on the Invoice page. The name of my Excel file is FinanceMarketing.

Sub Macro2()
'
' Macro2 Macro
'
    'Ask user for input
    userinput = InputBox("Type Associated Letter corresponding to Desired Invoice Population:")
    'Copy Name
    Sheets("Finance").Range("B2").Copy Destination:=Sheets("Invoice").Range("D3")
    'Copy Email
    Sheets("Finance").Range("C2").Copy Destination:=Sheets("Invoice").Range("D4")
    'Copy Adress
    Sheets("Finance").Range("D2").Copy Destination:=Sheets("Invoice").Range("D5")
    'Copy Date
    Sheets("Finance").Range("E2").Copy Destination:=Sheets("Invoice").Range("B8")
    'Copy Amount Owed
    Sheets("Finance").Range("I2").Copy Destination:=Sheets("Invoice").Range("D8")

    'From here down in the part of the code that I found online to move the excel into word which isn't working
'Using Early Binding

    Dim wordApp As Word.Application
    Dim mydoc As Word.Document

    'Creating a new instance of word only if there no other instances
    Set wordApp = New Word.Application

    'Making word App Visible
    wordApp.Visible = True

    'Creating a new document
    Set mydoc = wordApp.Documents.Add()

    'copying the content from excel sheet
    FinanceMarketing.Worksheets("Invoice").Range("B1:D19").Copy

    'Pasting on the document
    mydoc.Paragraphs(1).Range.PasteExcelTable _
                               LinkedToExcel:=False, _
                               WordFormatting:=False, _
                               RTF:=False

    'saving the document
    mydoc.SaveAs2 "MyDoc"

    'closing the document
    'mydoc.Close

    'Emptying the Clipboard
    'CutCopyMode = False
End Sub

Help to get moving the info into word would be very appreciated!


问:
I'm getting error in room database , :app:kaptDebugKotlin
I got this error when I used the room database

Error:

Entity class must be annotated with @Entity - androidx.room.Entity

Error: Entities and POJOs must have a usable public constructor. You can have an empty constructor or a constructor whose parameters match the fields (by name and type). - androidx.room.Entity

Error:

An entity must have at least 1 field annotated with @PrimaryKey -
androidx.room.Entity

Error:

[SQLITE_ERROR] SQL error or missing database (near ")": syntax
error) - androidx.room.Entity

```<code>plugins {
    id 'com.android.application'
    id 'org.jetbrains.kotlin.android'
    id 'kotlin-android-extensions'
    id 'kotlin-kapt'
    id 'kotlin-android'
}

android {
    compileSdk 33

    defaultConfig {
        applicationId "com.example.todolist"
        minSdk 21
        targetSdk 33
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
}

dependencies {

    implementation 'androidx.core:core-ktx:1.9.0'

    implementation 'androidx.appcompat:appcompat:1.5.1'
    implementation 'com.google.android.material:material:1.7.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.4'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.0'

    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4")
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.4")

    //room
     def    room_version = '2.4.3'
    implementation("androidx.room:room-runtime:$room_version")
    annotationProcessor "androidx.room:room-compiler:$room_version"
    kapt("androidx.room:room-compiler:$room_version")
    implementation("androidx.room:room-ktx:$room_version")
</code>```

still facing issues

// this is my entity class

```<code>import androidx.room.Entity
import androidx.room.PrimaryKey

@Entity(tableName = "To_do")
data class Entity(
    @PrimaryKey(autoGenerate = true)
    var id: Int,
    var title: String,
    var priority: String

    )
</code>```

Body:
I got this error when I used the room database

Error:

Entity class must be annotated with @Entity - androidx.room.Entity

Error: Entities and POJOs must have a usable public constructor. You can have an empty constructor or a constructor whose parameters match the fields (by name and type). - androidx.room.Entity

Error:

An entity must have at least 1 field annotated with @PrimaryKey -
androidx.room.Entity

Error:

[SQLITE_ERROR] SQL error or missing database (near ")": syntax
error) - androidx.room.Entity

plugins {
    id 'com.android.application'
    id 'org.jetbrains.kotlin.android'
    id 'kotlin-android-extensions'
    id 'kotlin-kapt'
    id 'kotlin-android'
}

android {
    compileSdk 33

    defaultConfig {
        applicationId "com.example.todolist"
        minSdk 21
        targetSdk 33
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
}

dependencies {

    implementation 'androidx.core:core-ktx:1.9.0'

    implementation 'androidx.appcompat:appcompat:1.5.1'
    implementation 'com.google.android.material:material:1.7.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.4'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.0'

    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4")
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.4")

    //room
     def    room_version = '2.4.3'
    implementation("androidx.room:room-runtime:$room_version")
    annotationProcessor "androidx.room:room-compiler:$room_version"
    kapt("androidx.room:room-compiler:$room_version")
    implementation("androidx.room:room-ktx:$room_version")

still facing issues

// this is my entity class

import androidx.room.Entity
import androidx.room.PrimaryKey

@Entity(tableName = "To_do")
data class Entity(
    @PrimaryKey(autoGenerate = true)
    var id: Int,
    var title: String,
    var priority: String

    )


问:
Jenkins: How to use choice parameter from an other file?
I have many pipelines using the same choice parameters so I want to import them from an external file. I tried to do the following:

```<code>pipeline {
  agent any
  parameters {
    choice(
        name: 'myParameter',
        choices: readFile "${WORKSPACE}/properties",
        description: 'interesting stuff' )
  }
}
</code>```

But i have this error:

```<code>org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 17: expecting ')', found '' @ line 17, column 31.
               choices: readFile "${WORKSPACE}/properties",
</code>```

Any idea or advice on what I can do this?

Body:
I have many pipelines using the same choice parameters so I want to import them from an external file. I tried to do the following:

pipeline {
  agent any
  parameters {
    choice(
        name: 'myParameter',
        choices: readFile "${WORKSPACE}/properties",
        description: 'interesting stuff' )
  }
}

But i have this error:

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 17: expecting ')', found '' @ line 17, column 31.
               choices: readFile "${WORKSPACE}/properties",

Any idea or advice on what I can do this?


问:
Tileserver-gl with Varnish always giving Age: 0 for the pbf
I am using tileserver-gl and want to use Varnish to cache the tiles. Varnish is working with nginx, that is taking care of the SSL.
The pbf tiles return Age:0 in the header (and a MISS), while the Date and Expires headers keep their value between reloads. What am I doing wrong?
In nginx I am using the following parameters

```<code>expires 2d;
add_header Cache-Control "public, no-transform";
</code>```

Here's my .vcl

```<code>sub vcl_recv {
  unset req.http.cookie; #added as a test, nothing changed so don't know if I should keep it
}
sub vcl_backend_response {
}
sub vcl_deliver {
  if (obj.hits > 0) { # Add debug header to see if it's a HIT/MISS and the number of hits
    set resp.http.X-Cache = "HIT";
  } else {
    set resp.http.X-Cache = "MISS";
  }
}
</code>```

Here's response header for one of the pbf tiles. They all give similar results, with Age: 0

```<code>Accept-Ranges: bytes
Access-Control-Allow-Origin: *
Age: 0
Cache-Control: max-age=172800, public, no-transform
Content-Encoding: gzip
Content-Length: 44891
Content-Type: application/x-protobuf
Date: Fri, 09 Dec 2022 10:30:34 GMT
ETag: W/"af5b-yQTY5UUgiSJNWC0axguA5dmojbI"
Expires: Sun, 11 Dec 2022 10:30:34 GMT
Last-Modified: Wed, 23 Nov 2022 09:25:23 GMT
Server: nginx/1.18.0 (Ubuntu)
Vary: Accept-Encoding
Via: 1.1 varnish (Varnish/6.6)
X-Cache: MISS
X-Varnish: 557061
</code>```

EDIT

Tried Thijs suggestion, here's the output

```<code>*   << Request  >> 98318
-   Begin          req 98317 rxreq
-   Timestamp      Start: 1670854870.784403 0.000000 0.000000
-   Timestamp      Req: 1670854870.784403 0.000000 0.000000
-   VCL_use        boot
-   ReqStart       127.0.0.1 38402 a0
-   ReqMethod      GET
-   ReqURL         /data/2017-07-03_europe_italy/0/0/0.pbf
-   ReqProtocol    HTTP/1.0
-   ReqHeader      X-Forwarded-Host: tiles.urbismap.com
-   ReqHeader      X-Real_IP: 93.41.126.66
-   ReqHeader      X-Forwarded-For: 93.41.126.66
-   ReqHeader      X-Forwarded-Proto: https
-   ReqHeader      Host: tiles.urbismap.com
-   ReqHeader      Connection: close
-   ReqHeader      User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36
-   ReqHeader      Accept: */*
-   ReqHeader      Sec-Fetch-Site: same-origin
-   ReqHeader      Sec-Fetch-Mode: cors
-   ReqHeader      Sec-Fetch-Dest: empty
-   ReqHeader      Referer: https://tiles.urbismap.com/styles/basemap/
-   ReqHeader      Accept-Encoding: gzip, deflate, br
-   ReqHeader      Accept-Language: it-IT,it;q=0.9
-   ReqUnset       X-Forwarded-For: 93.41.126.66
-   ReqHeader      X-Forwarded-For: 93.41.126.66, 127.0.0.1
-   VCL_call       RECV
-   VCL_return     hash
-   ReqUnset       Accept-Encoding: gzip, deflate, br
-   ReqHeader      Accept-Encoding: gzip
-   VCL_call       HASH
-   VCL_return     lookup
-   VCL_call       MISS
-   VCL_return     fetch
-   Link           bereq 98319 fetch
-   Timestamp      Fetch: 1670854870.792969 0.008566 0.008566
-   RespProtocol   HTTP/1.1
-   RespStatus     200
-   RespReason     OK
-   RespHeader     Server: nginx/1.18.0 (Ubuntu)
-   RespHeader     Date: Mon, 12 Dec 2022 14:21:10 GMT
-   RespHeader     Content-Type: application/x-protobuf
-   RespHeader     Content-Length: 31578
-   RespHeader     Access-Control-Allow-Origin: *
-   RespHeader     Content-Encoding: gzip
-   RespHeader     Last-Modified: Wed, 23 Nov 2022 09:25:23 GMT
-   RespHeader     ETag: W/"7b5a-Lgi1EP0ZRDWVK1iX+VP47MXHk2M"
-   RespHeader     Expires: Wed, 14 Dec 2022 14:21:10 GMT
-   RespHeader     Cache-Control: max-age=172800, public, no-transform
-   RespHeader     Vary: Accept-Encoding
-   RespHeader     X-Varnish: 98318
-   RespHeader     Age: 0
-   RespHeader     Via: 1.1 varnish (Varnish/6.6)
-   VCL_call       DELIVER
-   RespHeader     X-Cache: MISS
-   VCL_return     deliver
-   Timestamp      Process: 1670854870.793004 0.008600 0.000034
-   Filters
-   RespHeader     Accept-Ranges: bytes
-   RespHeader     Connection: close
-   Timestamp      Resp: 1670854870.794239 0.009835 0.001235
-   ReqAcct        555 0 555 524 31578 32102
-   End
**  << BeReq    >> 98319
--  Begin          bereq 98318 fetch
--  VCL_use        boot
--  Timestamp      Start: 1670854870.784497 0.000000 0.000000
--  BereqMethod    GET
--  BereqURL       /data/2017-07-03_europe_italy/0/0/0.pbf
--  BereqProtocol  HTTP/1.0
--  BereqHeader    X-Forwarded-Host: tiles.urbismap.com
--  BereqHeader    X-Real_IP: 93.41.126.66
--  BereqHeader    X-Forwarded-Proto: https
--  BereqHeader    Host: tiles.urbismap.com
--  BereqHeader    User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36
--  BereqHeader    Accept: */*
--  BereqHeader    Sec-Fetch-Site: same-origin
--  BereqHeader    Sec-Fetch-Mode: cors
--  BereqHeader    Sec-Fetch-Dest: empty
--  BereqHeader    Referer: https://tiles.urbismap.com/styles/basemap/
--  BereqHeader    Accept-Language: it-IT,it;q=0.9
--  BereqHeader    X-Forwarded-For: 93.41.126.66, 127.0.0.1
--  BereqHeader    Accept-Encoding: gzip
--  BereqProtocol  HTTP/1.1
--  BereqHeader    X-Varnish: 98319
--  VCL_call       BACKEND_FETCH
--  VCL_return     fetch
--  Timestamp      Fetch: 1670854870.784543 0.000045 0.000045
--  Timestamp      Connected: 1670854870.784548 0.000050 0.000005
--  BackendOpen    31 default 127.0.0.1 8080 127.0.0.1 41766 reuse
--  Timestamp      Bereq: 1670854870.784608 0.000111 0.000060
--  Timestamp      Beresp: 1670854870.792781 0.008283 0.008172
--  BerespProtocol HTTP/1.1
--  BerespStatus   200
--  BerespReason   OK
--  BerespHeader   Server: nginx/1.18.0 (Ubuntu)
--  BerespHeader   Date: Mon, 12 Dec 2022 14:21:10 GMT
--  BerespHeader   Content-Type: application/x-protobuf
--  BerespHeader   Content-Length: 31578
--  BerespHeader   Connection: keep-alive
--  BerespHeader   Access-Control-Allow-Origin: *
--  BerespHeader   Content-Encoding: gzip
--  BerespHeader   Last-Modified: Wed, 23 Nov 2022 09:25:23 GMT
--  BerespHeader   ETag: W/"7b5a-Lgi1EP0ZRDWVK1iX+VP47MXHk2M"
--  BerespHeader   Expires: Wed, 14 Dec 2022 14:21:10 GMT
--  BerespHeader   Cache-Control: max-age=172800
--  BerespHeader   Cache-Control: public, no-transform
--  TTL            RFC 172800 10 0 1670854871 1670854871 1670854870 1671027670 172800 cacheable
--  VCL_call       BACKEND_RESPONSE
--  VCL_return     deliver
--  Timestamp      Process: 1670854870.792827 0.008329 0.000046
--  Filters         testgunzip
--  BerespHeader   Vary: Accept-Encoding
--  Storage        malloc s0
--  Fetch_Body     3 length stream
--  Gzip           u F - 31578 51339 80 141523 252560
--  BackendClose   31 default recycle
--  Timestamp      BerespBody: 1670854870.794161 0.009664 0.001334
--  Length         31578
--  BereqAcct      552 0 552 426 31578 32004
--  End

*   << Request  >> 98350
-   Begin          req 98349 rxreq
-   Timestamp      Start: 1670855034.759301 0.000000 0.000000
-   Timestamp      Req: 1670855034.759301 0.000000 0.000000
-   VCL_use        boot
-   ReqStart       127.0.0.1 47736 a0
-   ReqMethod      GET
-   ReqURL         /data/2017-07-03_europe_italy/0/0/0.pbf
-   ReqProtocol    HTTP/1.0
-   ReqHeader      X-Forwarded-Host: tiles.urbismap.com
-   ReqHeader      X-Real_IP: 93.41.126.66
-   ReqHeader      X-Forwarded-For: 93.41.126.66
-   ReqHeader      X-Forwarded-Proto: https
-   ReqHeader      Host: tiles.urbismap.com
-   ReqHeader      Connection: close
-   ReqHeader      User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36
-   ReqHeader      Accept: */*
-   ReqHeader      Sec-Fetch-Site: same-origin
-   ReqHeader      Sec-Fetch-Mode: cors
-   ReqHeader      Sec-Fetch-Dest: empty
-   ReqHeader      Referer: https://tiles.urbismap.com/styles/basemap/
-   ReqHeader      Accept-Encoding: gzip, deflate, br
-   ReqHeader      Accept-Language: it-IT,it;q=0.9
-   ReqUnset       X-Forwarded-For: 93.41.126.66
-   ReqHeader      X-Forwarded-For: 93.41.126.66, 127.0.0.1
-   VCL_call       RECV
-   VCL_return     hash
-   ReqUnset       Accept-Encoding: gzip, deflate, br
-   ReqHeader      Accept-Encoding: gzip
-   VCL_call       HASH
-   VCL_return     lookup
-   Hit            98319 172636.033479 10.000000 0.000000
-   VCL_call       HIT
-   VCL_return     deliver
-   RespProtocol   HTTP/1.1
-   RespStatus     200
-   RespReason     OK
-   RespHeader     Server: nginx/1.18.0 (Ubuntu)
-   RespHeader     Date: Mon, 12 Dec 2022 14:21:10 GMT
-   RespHeader     Content-Type: application/x-protobuf
-   RespHeader     Content-Length: 31578
-   RespHeader     Access-Control-Allow-Origin: *
-   RespHeader     Content-Encoding: gzip
-   RespHeader     Last-Modified: Wed, 23 Nov 2022 09:25:23 GMT
-   RespHeader     ETag: W/"7b5a-Lgi1EP0ZRDWVK1iX+VP47MXHk2M"
-   RespHeader     Expires: Wed, 14 Dec 2022 14:21:10 GMT
-   RespHeader     Cache-Control: max-age=172800, public, no-transform
-   RespHeader     Vary: Accept-Encoding
-   RespHeader     X-Varnish: 98350 98319
-   RespHeader     Age: 163
-   RespHeader     Via: 1.1 varnish (Varnish/6.6)
-   VCL_call       DELIVER
-   RespHeader     X-Cache: HIT
-   VCL_return     deliver
-   Timestamp      Process: 1670855034.759391 0.000089 0.000089
-   Filters
-   RespHeader     Accept-Ranges: bytes
-   RespHeader     Connection: close
-   Timestamp      Resp: 1670855034.759479 0.000177 0.000087
-   ReqAcct        555 0 555 531 31578 32109
-   End
</code>```

Body:
I am using tileserver-gl and want to use Varnish to cache the tiles. Varnish is working with nginx, that is taking care of the SSL.
The pbf tiles return Age:0 in the header (and a MISS), while the Date and Expires headers keep their value between reloads. What am I doing wrong?
In nginx I am using the following parameters

expires 2d;
add_header Cache-Control "public, no-transform";

Here's my .vcl

sub vcl_recv {
  unset req.http.cookie; #added as a test, nothing changed so don't know if I should keep it
}
sub vcl_backend_response {
}
sub vcl_deliver {
  if (obj.hits > 0) { # Add debug header to see if it's a HIT/MISS and the number of hits
    set resp.http.X-Cache = "HIT";
  } else {
    set resp.http.X-Cache = "MISS";
  }
}

Here's response header for one of the pbf tiles. They all give similar results, with Age: 0

Accept-Ranges: bytes
Access-Control-Allow-Origin: *
Age: 0
Cache-Control: max-age=172800, public, no-transform
Content-Encoding: gzip
Content-Length: 44891
Content-Type: application/x-protobuf
Date: Fri, 09 Dec 2022 10:30:34 GMT
ETag: W/"af5b-yQTY5UUgiSJNWC0axguA5dmojbI"
Expires: Sun, 11 Dec 2022 10:30:34 GMT
Last-Modified: Wed, 23 Nov 2022 09:25:23 GMT
Server: nginx/1.18.0 (Ubuntu)
Vary: Accept-Encoding
Via: 1.1 varnish (Varnish/6.6)
X-Cache: MISS
X-Varnish: 557061

EDIT

Tried Thijs suggestion, here's the output

*   << Request  >> 98318
-   Begin          req 98317 rxreq
-   Timestamp      Start: 1670854870.784403 0.000000 0.000000
-   Timestamp      Req: 1670854870.784403 0.000000 0.000000
-   VCL_use        boot
-   ReqStart       127.0.0.1 38402 a0
-   ReqMethod      GET
-   ReqURL         /data/2017-07-03_europe_italy/0/0/0.pbf
-   ReqProtocol    HTTP/1.0
-   ReqHeader      X-Forwarded-Host: tiles.urbismap.com
-   ReqHeader      X-Real_IP: 93.41.126.66
-   ReqHeader      X-Forwarded-For: 93.41.126.66
-   ReqHeader      X-Forwarded-Proto: https
-   ReqHeader      Host: tiles.urbismap.com
-   ReqHeader      Connection: close
-   ReqHeader      User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36
-   ReqHeader      Accept: */*
-   ReqHeader      Sec-Fetch-Site: same-origin
-   ReqHeader      Sec-Fetch-Mode: cors
-   ReqHeader      Sec-Fetch-Dest: empty
-   ReqHeader      Referer: https://tiles.urbismap.com/styles/basemap/
-   ReqHeader      Accept-Encoding: gzip, deflate, br
-   ReqHeader      Accept-Language: it-IT,it;q=0.9
-   ReqUnset       X-Forwarded-For: 93.41.126.66
-   ReqHeader      X-Forwarded-For: 93.41.126.66, 127.0.0.1
-   VCL_call       RECV
-   VCL_return     hash
-   ReqUnset       Accept-Encoding: gzip, deflate, br
-   ReqHeader      Accept-Encoding: gzip
-   VCL_call       HASH
-   VCL_return     lookup
-   VCL_call       MISS
-   VCL_return     fetch
-   Link           bereq 98319 fetch
-   Timestamp      Fetch: 1670854870.792969 0.008566 0.008566
-   RespProtocol   HTTP/1.1
-   RespStatus     200
-   RespReason     OK
-   RespHeader     Server: nginx/1.18.0 (Ubuntu)
-   RespHeader     Date: Mon, 12 Dec 2022 14:21:10 GMT
-   RespHeader     Content-Type: application/x-protobuf
-   RespHeader     Content-Length: 31578
-   RespHeader     Access-Control-Allow-Origin: *
-   RespHeader     Content-Encoding: gzip
-   RespHeader     Last-Modified: Wed, 23 Nov 2022 09:25:23 GMT
-   RespHeader     ETag: W/"7b5a-Lgi1EP0ZRDWVK1iX+VP47MXHk2M"
-   RespHeader     Expires: Wed, 14 Dec 2022 14:21:10 GMT
-   RespHeader     Cache-Control: max-age=172800, public, no-transform
-   RespHeader     Vary: Accept-Encoding
-   RespHeader     X-Varnish: 98318
-   RespHeader     Age: 0
-   RespHeader     Via: 1.1 varnish (Varnish/6.6)
-   VCL_call       DELIVER
-   RespHeader     X-Cache: MISS
-   VCL_return     deliver
-   Timestamp      Process: 1670854870.793004 0.008600 0.000034
-   Filters
-   RespHeader     Accept-Ranges: bytes
-   RespHeader     Connection: close
-   Timestamp      Resp: 1670854870.794239 0.009835 0.001235
-   ReqAcct        555 0 555 524 31578 32102
-   End
**  << BeReq    >> 98319
--  Begin          bereq 98318 fetch
--  VCL_use        boot
--  Timestamp      Start: 1670854870.784497 0.000000 0.000000
--  BereqMethod    GET
--  BereqURL       /data/2017-07-03_europe_italy/0/0/0.pbf
--  BereqProtocol  HTTP/1.0
--  BereqHeader    X-Forwarded-Host: tiles.urbismap.com
--  BereqHeader    X-Real_IP: 93.41.126.66
--  BereqHeader    X-Forwarded-Proto: https
--  BereqHeader    Host: tiles.urbismap.com
--  BereqHeader    User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36
--  BereqHeader    Accept: */*
--  BereqHeader    Sec-Fetch-Site: same-origin
--  BereqHeader    Sec-Fetch-Mode: cors
--  BereqHeader    Sec-Fetch-Dest: empty
--  BereqHeader    Referer: https://tiles.urbismap.com/styles/basemap/
--  BereqHeader    Accept-Language: it-IT,it;q=0.9
--  BereqHeader    X-Forwarded-For: 93.41.126.66, 127.0.0.1
--  BereqHeader    Accept-Encoding: gzip
--  BereqProtocol  HTTP/1.1
--  BereqHeader    X-Varnish: 98319
--  VCL_call       BACKEND_FETCH
--  VCL_return     fetch
--  Timestamp      Fetch: 1670854870.784543 0.000045 0.000045
--  Timestamp      Connected: 1670854870.784548 0.000050 0.000005
--  BackendOpen    31 default 127.0.0.1 8080 127.0.0.1 41766 reuse
--  Timestamp      Bereq: 1670854870.784608 0.000111 0.000060
--  Timestamp      Beresp: 1670854870.792781 0.008283 0.008172
--  BerespProtocol HTTP/1.1
--  BerespStatus   200
--  BerespReason   OK
--  BerespHeader   Server: nginx/1.18.0 (Ubuntu)
--  BerespHeader   Date: Mon, 12 Dec 2022 14:21:10 GMT
--  BerespHeader   Content-Type: application/x-protobuf
--  BerespHeader   Content-Length: 31578
--  BerespHeader   Connection: keep-alive
--  BerespHeader   Access-Control-Allow-Origin: *
--  BerespHeader   Content-Encoding: gzip
--  BerespHeader   Last-Modified: Wed, 23 Nov 2022 09:25:23 GMT
--  BerespHeader   ETag: W/"7b5a-Lgi1EP0ZRDWVK1iX+VP47MXHk2M"
--  BerespHeader   Expires: Wed, 14 Dec 2022 14:21:10 GMT
--  BerespHeader   Cache-Control: max-age=172800
--  BerespHeader   Cache-Control: public, no-transform
--  TTL            RFC 172800 10 0 1670854871 1670854871 1670854870 1671027670 172800 cacheable
--  VCL_call       BACKEND_RESPONSE
--  VCL_return     deliver
--  Timestamp      Process: 1670854870.792827 0.008329 0.000046
--  Filters         testgunzip
--  BerespHeader   Vary: Accept-Encoding
--  Storage        malloc s0
--  Fetch_Body     3 length stream
--  Gzip           u F - 31578 51339 80 141523 252560
--  BackendClose   31 default recycle
--  Timestamp      BerespBody: 1670854870.794161 0.009664 0.001334
--  Length         31578
--  BereqAcct      552 0 552 426 31578 32004
--  End

*   << Request  >> 98350
-   Begin          req 98349 rxreq
-   Timestamp      Start: 1670855034.759301 0.000000 0.000000
-   Timestamp      Req: 1670855034.759301 0.000000 0.000000
-   VCL_use        boot
-   ReqStart       127.0.0.1 47736 a0
-   ReqMethod      GET
-   ReqURL         /data/2017-07-03_europe_italy/0/0/0.pbf
-   ReqProtocol    HTTP/1.0
-   ReqHeader      X-Forwarded-Host: tiles.urbismap.com
-   ReqHeader      X-Real_IP: 93.41.126.66
-   ReqHeader      X-Forwarded-For: 93.41.126.66
-   ReqHeader      X-Forwarded-Proto: https
-   ReqHeader      Host: tiles.urbismap.com
-   ReqHeader      Connection: close
-   ReqHeader      User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36
-   ReqHeader      Accept: */*
-   ReqHeader      Sec-Fetch-Site: same-origin
-   ReqHeader      Sec-Fetch-Mode: cors
-   ReqHeader      Sec-Fetch-Dest: empty
-   ReqHeader      Referer: https://tiles.urbismap.com/styles/basemap/
-   ReqHeader      Accept-Encoding: gzip, deflate, br
-   ReqHeader      Accept-Language: it-IT,it;q=0.9
-   ReqUnset       X-Forwarded-For: 93.41.126.66
-   ReqHeader      X-Forwarded-For: 93.41.126.66, 127.0.0.1
-   VCL_call       RECV
-   VCL_return     hash
-   ReqUnset       Accept-Encoding: gzip, deflate, br
-   ReqHeader      Accept-Encoding: gzip
-   VCL_call       HASH
-   VCL_return     lookup
-   Hit            98319 172636.033479 10.000000 0.000000
-   VCL_call       HIT
-   VCL_return     deliver
-   RespProtocol   HTTP/1.1
-   RespStatus     200
-   RespReason     OK
-   RespHeader     Server: nginx/1.18.0 (Ubuntu)
-   RespHeader     Date: Mon, 12 Dec 2022 14:21:10 GMT
-   RespHeader     Content-Type: application/x-protobuf
-   RespHeader     Content-Length: 31578
-   RespHeader     Access-Control-Allow-Origin: *
-   RespHeader     Content-Encoding: gzip
-   RespHeader     Last-Modified: Wed, 23 Nov 2022 09:25:23 GMT
-   RespHeader     ETag: W/"7b5a-Lgi1EP0ZRDWVK1iX+VP47MXHk2M"
-   RespHeader     Expires: Wed, 14 Dec 2022 14:21:10 GMT
-   RespHeader     Cache-Control: max-age=172800, public, no-transform
-   RespHeader     Vary: Accept-Encoding
-   RespHeader     X-Varnish: 98350 98319
-   RespHeader     Age: 163
-   RespHeader     Via: 1.1 varnish (Varnish/6.6)
-   VCL_call       DELIVER
-   RespHeader     X-Cache: HIT
-   VCL_return     deliver
-   Timestamp      Process: 1670855034.759391 0.000089 0.000089
-   Filters
-   RespHeader     Accept-Ranges: bytes
-   RespHeader     Connection: close
-   Timestamp      Resp: 1670855034.759479 0.000177 0.000087
-   ReqAcct        555 0 555 531 31578 32109
-   End


问:
One Lambda is working, one isn't. (Tkinter)
I'm trying to make an advanced baseball metric calculator. Can anyone explain why the lambda in "wobaentry" is returning nonetypes when calling the "wOBA" function. I have a set of functions that I modelled this segment after and it's working perfectly. What am I overlooking? Any insight would be greatly appreciate

```<code>from tkinter import *
import tkinter.messagebox

def wobaentry():
    wobainput= Tk()
    L4 = Label(wobainput, text = "wOBA", fg = "red", font = "Times").grid(row=1, column=1)
    L5 = Label(wobainput, text ="Walks").grid(row=2, column=1)
    L6 = Label(wobainput, text ="Singles").grid(row=3, column=1)
    L7 = Label(wobainput, text ="Doubles").grid(row=4, column=1)
    L8 = Label(wobainput, text ="Triples").grid(row=5, column=1)
    L9 = Label(wobainput, text ="Home Runs").grid(row=6, column=1)
    L10 = Label(wobainput, text ="At bats").grid(row=7, column=1)
    L11 =Label(wobainput, text ="Sacrifice flies").grid(row=8, column=1)
    L12 = Label(wobainput, text ="Intentional Walks").grid(row=9, column=1)
    L14 = Label(wobainput, text ="Hit By Pitch").grid(row=10, column=1)
    E4= Entry(wobainput, width= 60).grid(row=2, column=2)
    E5= Entry(wobainput, width= 60).grid(row=3, column=2)
    E6= Entry(wobainput, width= 60).grid(row=4, column=2)
    E7= Entry(wobainput, width= 60).grid(row=5, column=2)
    E8= Entry(wobainput, width= 60).grid(row=6, column=2)
    E9= Entry(wobainput, width= 60).grid(row=7, column=2)
    E10= Entry(wobainput, width= 60).grid(row=8, column=2)
    E11= Entry(wobainput, width= 60).grid(row=9, column=2)
    E13= Entry(wobainput, width= 60).grid(row=10, column=2)
    B5= Button(wobainput, text= "Calculate wOBA", command = lambda: wOBA(E4, E5, E6, E7, E8, E9, E10, E11, E13) )
    B5.grid(row=15, column=2)

def wOBA(E4, E5, E6, E7, E8, E9, E10, E11, E13):
    wOBAoutput = Tk()
    L13 = Label (wOBAoutput, text = "wOBA", fg="black", font = "times")
    L13.grid (row=1, column = 1)
    E12 = Entry(wOBAoutput, bd=5).grid(row=2, column=1)
    bb = float(E4.get())
    hbp = float(E13.get())
    singles = float(E5.get())
    doubles = float(E6.get())
    triple = float(E7.get())
    hr = float(E8.get())
    ab = float(E9.get())
    sf = float(E10.get())
    ibb = float(E11.get())
    ubb = bb - ibb
    woba = float(((ubb * .69) + (.720 * hbp) + (.884 * singles) + (1.261 * doubles) + (1.601 * triple) + (2.072 * hr)) / (ab + bb - ibb + sf + hbp))
    E12.insert(0, str(woba))
    E12['bg']='grey'
</code>```

This is the set that is working:

```<code>def pythagentry():
    pythaginput = Tk()
    L0 = Label(pythaginput, text= "Expected Wins", fg="black", font = "Times")
    L0.grid(row=1, column=1)
    L1 = Label(pythaginput, text= "Runs Scored", fg="black", font= "Times")
    L1.grid(row=2, column=1)
    L2 = Label(pythaginput, text= "Runs Allowed", fg="black", font= "Times")
    L2.grid(row=3, column=1)
    L3 = Label(pythaginput, text= "Season Length", fg="black", font= "Times")
    L3.grid(row=4, column=1)
    E1 = Entry(pythaginput,bd=5)
    E1.grid (row=2, column=2)
    E2 = Entry(pythaginput,bd=5)
    E2.grid (row=3, column=2)
    E3 = Entry(pythaginput,bd=5)
    E3.grid (row=4, column=2)
    B4 = Button (pythaginput,text='Calculate Pythagorean Wins', command = lambda: pythag(E1, E2, E3) )
    B4.grid (row=5, column=2)

def pythag(E1, E2, E3):
    pythagoutput = Tk()
    L4=Label(pythagoutput,text="Expected Wins:",fg="red")
    L4.grid (row =1, column =1)
    E5=Entry(pythagoutput, bd=5)
    E5.grid(row=4,column=1)
    runsscored= float(E1.get())
    runsallowed= float(E2.get())
    lengthseason= float(E3.get())
    ratio = runsscored / runsallowed
    winpct = pow (ratio, 2) / (pow(ratio, 2) + 1)
    expectedwins = lengthseason * winpct
    E5.insert(0, str(expectedwins))
    E5['bg']='grey'

</code>```

Body:
I'm trying to make an advanced baseball metric calculator. Can anyone explain why the lambda in "wobaentry" is returning nonetypes when calling the "wOBA" function. I have a set of functions that I modelled this segment after and it's working perfectly. What am I overlooking? Any insight would be greatly appreciate

from tkinter import *
import tkinter.messagebox

def wobaentry():
    wobainput= Tk()
    L4 = Label(wobainput, text = "wOBA", fg = "red", font = "Times").grid(row=1, column=1)
    L5 = Label(wobainput, text ="Walks").grid(row=2, column=1)
    L6 = Label(wobainput, text ="Singles").grid(row=3, column=1)
    L7 = Label(wobainput, text ="Doubles").grid(row=4, column=1)
    L8 = Label(wobainput, text ="Triples").grid(row=5, column=1)
    L9 = Label(wobainput, text ="Home Runs").grid(row=6, column=1)
    L10 = Label(wobainput, text ="At bats").grid(row=7, column=1)
    L11 =Label(wobainput, text ="Sacrifice flies").grid(row=8, column=1)
    L12 = Label(wobainput, text ="Intentional Walks").grid(row=9, column=1)
    L14 = Label(wobainput, text ="Hit By Pitch").grid(row=10, column=1)
    E4= Entry(wobainput, width= 60).grid(row=2, column=2)
    E5= Entry(wobainput, width= 60).grid(row=3, column=2)
    E6= Entry(wobainput, width= 60).grid(row=4, column=2)
    E7= Entry(wobainput, width= 60).grid(row=5, column=2)
    E8= Entry(wobainput, width= 60).grid(row=6, column=2)
    E9= Entry(wobainput, width= 60).grid(row=7, column=2)
    E10= Entry(wobainput, width= 60).grid(row=8, column=2)
    E11= Entry(wobainput, width= 60).grid(row=9, column=2)
    E13= Entry(wobainput, width= 60).grid(row=10, column=2)
    B5= Button(wobainput, text= "Calculate wOBA", command = lambda: wOBA(E4, E5, E6, E7, E8, E9, E10, E11, E13) )
    B5.grid(row=15, column=2)

def wOBA(E4, E5, E6, E7, E8, E9, E10, E11, E13):
    wOBAoutput = Tk()
    L13 = Label (wOBAoutput, text = "wOBA", fg="black", font = "times")
    L13.grid (row=1, column = 1)
    E12 = Entry(wOBAoutput, bd=5).grid(row=2, column=1)
    bb = float(E4.get())
    hbp = float(E13.get())
    singles = float(E5.get())
    doubles = float(E6.get())
    triple = float(E7.get())
    hr = float(E8.get())
    ab = float(E9.get())
    sf = float(E10.get())
    ibb = float(E11.get())
    ubb = bb - ibb
    woba = float(((ubb * .69) + (.720 * hbp) + (.884 * singles) + (1.261 * doubles) + (1.601 * triple) + (2.072 * hr)) / (ab + bb - ibb + sf + hbp))
    E12.insert(0, str(woba))
    E12['bg']='grey'

This is the set that is working:

def pythagentry():
    pythaginput = Tk()
    L0 = Label(pythaginput, text= "Expected Wins", fg="black", font = "Times")
    L0.grid(row=1, column=1)
    L1 = Label(pythaginput, text= "Runs Scored", fg="black", font= "Times")
    L1.grid(row=2, column=1)
    L2 = Label(pythaginput, text= "Runs Allowed", fg="black", font= "Times")
    L2.grid(row=3, column=1)
    L3 = Label(pythaginput, text= "Season Length", fg="black", font= "Times")
    L3.grid(row=4, column=1)
    E1 = Entry(pythaginput,bd=5)
    E1.grid (row=2, column=2)
    E2 = Entry(pythaginput,bd=5)
    E2.grid (row=3, column=2)
    E3 = Entry(pythaginput,bd=5)
    E3.grid (row=4, column=2)
    B4 = Button (pythaginput,text='Calculate Pythagorean Wins', command = lambda: pythag(E1, E2, E3) )
    B4.grid (row=5, column=2)

def pythag(E1, E2, E3):
    pythagoutput = Tk()
    L4=Label(pythagoutput,text="Expected Wins:",fg="red")
    L4.grid (row =1, column =1)
    E5=Entry(pythagoutput, bd=5)
    E5.grid(row=4,column=1)
    runsscored= float(E1.get())
    runsallowed= float(E2.get())
    lengthseason= float(E3.get())
    ratio = runsscored / runsallowed
    winpct = pow (ratio, 2) / (pow(ratio, 2) + 1)
    expectedwins = lengthseason * winpct
    E5.insert(0, str(expectedwins))
    E5['bg']='grey'


问:
Using Strong Wolfe Condition to find learning rate
I'm trying to optimize a function with gradient decent code that I wrote but I want to use another function file related to Strong Wolfe Condition to find a good alpha.

Both of my codes are working with an equation and same time I get -inf for another equation.
-inf occures in con1 and con3 in Strong Wolfe Condition function.

I have no idea why with the second equation I can't find the Alpha. please help me with this.

My codes are wroten in Matlab.

This is my gradient descent code:

% Clear the space
clear all;
clc;

% Define the equation
syms x1 x2;
% f(x1, x2) = (-x1 ^ 3) * exp(x2 - (x1 ^ 2) - (10 * ((x1 - x2) ^ 2))); % First equation
f(x1, x2) = -cos(x1) * (cos(x2) * (exp((x1-pi)^2+(x2-pi)^2))); % Second equation

% plot the contour plot
fcontour(f, 'Fill', 'on');
% To show the color bar next to the plot
colorbar
% For 3d plot //// I just coment it because it doesn't look good
% fsurf(f);
% To hold the plot so we can show the update of point on it
hold on

% The diviation of equation
gx = gradient(f);

% Initial point given by homework
% x = [0.75, -1.25];
x = [2.1, 2.1];

% Learing Rate (alpha)
% learningRate = LR(x, f);
learningRate = LR(x, f);

% First compute of gradient with initial points
xResult = double(subs(gx(x(1, 1), x(1, 2)),{x1,x2},{x(1,1),x(1,2)}));

% Two empty list to save the points during the update
x1List = [x(1, 1)];
x2List = [x(1, 2)];

% for loop for update the points
for i = 1:1000

    % with GD formula update the points
    x(1, 1) = x(1,1) - (learningRate * xResult(1, 1));
    x(1, 2) = x(1,2) - (learningRate * xResult(2, 1));

    % Save the points inside the empty list for further use
    x1List = [x1List x(1, 1)]; %#ok
    x2List = [x2List x(1, 2)]; %#ok

    % With new points compute the gradient
    xResult = double(subs(gx(x(1, 1), x(1, 2)),{x1,x2},{x(1,1),x(1,2)}));

    % Plot the point on contour
%     plot(x(1, 1), x(1, 2), 'r-*');
%     title('Iteration = ', i )
%     pause(0.1)

    % Break the iteration
    % Check if the points don't change more than 10e-4 and if so break
    errorAmountx1 = x1List(1, i)  - x(1, 1);
    errorAmountx2 = x2List(1, i)  - x(1, 2);
    if (errorAmountx1 < 10e-4 && errorAmountx2 < 10e-4)
        break
    end

%     if (mod(i, 5) == 0)
%         learningRate = LR_2(x, f);
%     end
end

% After finding the min point print out the results
disp('Iteration = ');
disp(i);
disp('The Min Point = ');
disp(x);
disp('Final x in equation : ')
fResult = double(subs(f(x(1,1), x(1,2)),{x1,x2},{x(1,1),x(1,2)}));
disp(fResult);
plot(x1List, x2List, 'r-*');
```
<p>This is my Strong Wolfe Condition code:</p>
<pre class="lang-matlab prettyprint-override"><code>function [learningRate] = LR(x, f)
    syms x1 x2;
    f(x1, x2) = f;

    lr = 0.00001:0.001:1;

    c1 = rand();
    c2 = c1 + rand() * (1 - c1);

    gradi = double(subs(gradient(f, [x1, x2]),{x1,x2},{x(1,1),x(1,2)}));
    p = -gradi;

    for i = 1:length(lr)
        disp(i);

        xap = x + lr(i) * transpose(p);

        con1 = double(subs(f(xap(1,1), xap(1,2)),{x1,x2},{xap(1,1), xap(1,2)}));
        con2 = double(subs(f(x(1,1), x(1,2)),{x1,x2},{x(1,1),x(1,2)})) + (c1 * (lr(i) * transpose(gradi)) * p);
        con3 = abs(transpose(double(subs(gradient(f, [x1, x2]),{x1,x2},{xap(1,1),xap(1,2)}))) * p);
        con4 = c2 * abs(transpose(gradi) * p);

        if (con1 <= con2 && con3 <= con4)
            learningRate = lr(i);
            break
        end
    end
end
</code>```

Body:
I'm trying to optimize a function with gradient decent code that I wrote but I want to use another function file related to Strong Wolfe Condition to find a good alpha.

Both of my codes are working with an equation and same time I get -inf for another equation.
-inf occures in con1 and con3 in Strong Wolfe Condition function.

I have no idea why with the second equation I can't find the Alpha. please help me with this.

My codes are wroten in Matlab.

This is my gradient descent code:

% Clear the space
clear all;
clc;

% Define the equation
syms x1 x2;
% f(x1, x2) = (-x1 ^ 3) * exp(x2 - (x1 ^ 2) - (10 * ((x1 - x2) ^ 2))); % First equation
f(x1, x2) = -cos(x1) * (cos(x2) * (exp((x1-pi)^2+(x2-pi)^2))); % Second equation

% plot the contour plot
fcontour(f, 'Fill', 'on');
% To show the color bar next to the plot
colorbar
% For 3d plot //// I just coment it because it doesn't look good
% fsurf(f);
% To hold the plot so we can show the update of point on it
hold on

% The diviation of equation
gx = gradient(f);

% Initial point given by homework
% x = [0.75, -1.25];
x = [2.1, 2.1];

% Learing Rate (alpha)
% learningRate = LR(x, f);
learningRate = LR(x, f);

% First compute of gradient with initial points
xResult = double(subs(gx(x(1, 1), x(1, 2)),{x1,x2},{x(1,1),x(1,2)}));

% Two empty list to save the points during the update
x1List = [x(1, 1)];
x2List = [x(1, 2)];

% for loop for update the points
for i = 1:1000

    % with GD formula update the points
    x(1, 1) = x(1,1) - (learningRate * xResult(1, 1));
    x(1, 2) = x(1,2) - (learningRate * xResult(2, 1));

    % Save the points inside the empty list for further use
    x1List = [x1List x(1, 1)]; %#ok
    x2List = [x2List x(1, 2)]; %#ok

    % With new points compute the gradient
    xResult = double(subs(gx(x(1, 1), x(1, 2)),{x1,x2},{x(1,1),x(1,2)}));

    % Plot the point on contour
%     plot(x(1, 1), x(1, 2), 'r-*');
%     title('Iteration = ', i )
%     pause(0.1)

    % Break the iteration
    % Check if the points don't change more than 10e-4 and if so break
    errorAmountx1 = x1List(1, i)  - x(1, 1);
    errorAmountx2 = x2List(1, i)  - x(1, 2);
    if (errorAmountx1 < 10e-4 && errorAmountx2 < 10e-4)
        break
    end

%     if (mod(i, 5) == 0)
%         learningRate = LR_2(x, f);
%     end
end

% After finding the min point print out the results
disp('Iteration = ');
disp(i);
disp('The Min Point = ');
disp(x);
disp('Final x in equation : ')
fResult = double(subs(f(x(1,1), x(1,2)),{x1,x2},{x(1,1),x(1,2)}));
disp(fResult);
plot(x1List, x2List, 'r-*');

This is my Strong Wolfe Condition code:

function [learningRate] = LR(x, f)
    syms x1 x2;
    f(x1, x2) = f;

    lr = 0.00001:0.001:1;

    c1 = rand();
    c2 = c1 + rand() * (1 - c1);

    gradi = double(subs(gradient(f, [x1, x2]),{x1,x2},{x(1,1),x(1,2)}));
    p = -gradi;

    for i = 1:length(lr)
        disp(i);

        xap = x + lr(i) * transpose(p);

        con1 = double(subs(f(xap(1,1), xap(1,2)),{x1,x2},{xap(1,1), xap(1,2)}));
        con2 = double(subs(f(x(1,1), x(1,2)),{x1,x2},{x(1,1),x(1,2)})) + (c1 * (lr(i) * transpose(gradi)) * p);
        con3 = abs(transpose(double(subs(gradient(f, [x1, x2]),{x1,x2},{xap(1,1),xap(1,2)}))) * p);
        con4 = c2 * abs(transpose(gradi) * p);

        if (con1 <= con2 && con3 <= con4)
            learningRate = lr(i);
            break
        end
    end
end


问:
Service Account for Google Search Console on node returns 401
I am trying to use the @googleapis/searchconsole submodule package from node googleapis and the Service Account approach.

I created the keys and added the service account to the search console property.

I stored the email and private key on an dotenv file.

.env

```<code>GOOGLE_CLIENT_EMAIL='my-api@my-app.iam.gserviceaccount.com'
GOOGLE_PRIVATE_KEY='-----BEGIN PRIVATE KEY-----\netcn-----END PRIVATE KEY-----\n'
</code>```

Then I create an Auth and Client function to use the service account

```<code>const Auth = new searchConsole.auth.GoogleAuth({
  credentials: {
    private_key: process.env.GOOGLE_PRIVATE_KEY.replaceAll('\\n', '\n'),
    client_email: process.env.GOOGLE_CLIENT_EMAIL
  },
  scopes: ['https://www.googleapis.com/auth/webmasters.readonly']
})

const Client = searchConsole.searchconsole({
  version: 'v1',
  Auth
})
</code>```

But when I try to use it, I get a 401 response telling me Login Required

```<code>Client.searchanalytics
  .query({
    siteUrl: 'https://example.com',
    startDate: '2022-01-01',
    endDate: '2022-12-31'
  })
  .then((response) => console.log(response.data))
  .catch((reason) => console.log(reason))
</code>```

Body:
I am trying to use the @googleapis/searchconsole submodule package from node googleapis and the Service Account approach.

I created the keys and added the service account to the search console property.

I stored the email and private key on an dotenv file.

.env

GOOGLE_CLIENT_EMAIL='my-api@my-app.iam.gserviceaccount.com'
GOOGLE_PRIVATE_KEY='-----BEGIN PRIVATE KEY-----\netcn-----END PRIVATE KEY-----\n'

Then I create an Auth and Client function to use the service account

const Auth = new searchConsole.auth.GoogleAuth({
  credentials: {
    private_key: process.env.GOOGLE_PRIVATE_KEY.replaceAll('\\n', '\n'),
    client_email: process.env.GOOGLE_CLIENT_EMAIL
  },
  scopes: ['https://www.googleapis.com/auth/webmasters.readonly']
})

const Client = searchConsole.searchconsole({
  version: 'v1',
  Auth
})

But when I try to use it, I get a 401 response telling me Login Required

Client.searchanalytics
  .query({
    siteUrl: 'https://example.com',
    startDate: '2022-01-01',
    endDate: '2022-12-31'
  })
  .then((response) => console.log(response.data))
  .catch((reason) => console.log(reason))