问:
Is Apache POI support modify password protect xlsx file content?
After I generate a password protected xlsx file with apache poi, I  modify file content with XSSFWorkbook.like:

File file = new File("Test2.xlsx");
XSSFWorkbook wb = (XSSFWorkbook) WorkbookFactory.create(file, "password");
wb.createSheet("Test0001");
try (FileOutputStream fileOutputStream = new FileOutputStream(file)) {
    wb.write(fileOutputStream);
} finally {
    wb.close();
}
```

when I reopen the file, the file was no longer password protected,Apache POI and poi-ooxml version:5.2.1.Maybe poi not support modify password protected xlsx file?

is there anyway modify password protected xlsx file with apache poi?

Body:
After I generate a password protected xlsx file with apache poi, I  modify file content with XSSFWorkbook.like:

File file = new File("Test2.xlsx");
XSSFWorkbook wb = (XSSFWorkbook) WorkbookFactory.create(file, "password");
wb.createSheet("Test0001");
try (FileOutputStream fileOutputStream = new FileOutputStream(file)) {
    wb.write(fileOutputStream);
} finally {
    wb.close();
}

when I reopen the file, the file was no longer password protected,Apache POI and poi-ooxml version:5.2.1.Maybe poi not support modify password protected xlsx file?

is there anyway modify password protected xlsx file with apache poi?


来源: stackexchange

问:
I am getting sonarqube codecoverage repot 0% I installed all recent version applications
Jococo.exec file is creating after maven build in target folder, but getting code coverage 0% and added plugins of both sonarqube and jococo.

I tried added report dependies and I refered all sites and yt videos I am not able to get this code coverage.
I am expection to solve issue and get code coverage percentage.

ContentLicense: CC BY-SA 4.0


问:
How to compute the R1 and R2
i try as an exercise to visualize camera1, camera2 and their geometric relationship.

Something like this:

I do this step for more understanding.

For this purpose i need to compute the R1 and R2.
From this two guys i can compute the P1, P2 and the baseline between the camera1 and camera2.

I have this two camera single and stereo calibrated. From the stereo calibration i have R and T.

R is the rotation matrix between camera1 and camera2.

I'm little bit confused, and I'm not sure how to interpret this sentence.

My question is, can i say that R2 = R and R1 = R^T, is this correct?

Thanks!

Title: How to compute the R1 and R2


问:
Piping the openDownloadStream() of MongoDB gridFS bucket with a createWriteStream () writes an empty file
I referenced GridFS-download files to download the files stored in mongoDB but it writes an empty file. I have made sure that the files in my database aren't empty.

server.js:

```<code>import fs from "fs";
import path from "path";
import express from "express";
import "dotenv/config";
import { db, bucket, connectToDb } from "./db.js";
import { fileURLToPath } from "url";
import cors from "cors";
import { ObjectId } from "mongodb";

const app = express();
app.use(express.json());
app.use(cors());

const PORT = process.env.PORT || 8000;

app.get("/", async (req, res) => {
  const cursor = bucket.find({});
  const songInfo = await cursor.toArray();
  console.log("id", songInfo[0]._id);
  bucket.openDownloadStream(songInfo[0]._id).pipe(fs.createWriteStream('./outputFile.mp3'));
  res.json(songInfo);
});

connectToDb(() => {
  console.log("Successfully connected to database!!");
  app.listen(PORT, () => {
    console.log("Server is listening on port " + PORT);
  });
});

</code>```

db.js:

```<code>import { GridFSBucket, MongoClient } from "mongodb";

let db, bucket;

async function connectToDb(cb) {
  const client = new MongoClient(`mongodb+srv://${process.env.MONGO_USERNAME}:${process.env.MONGO_PASSWORD}@cluster0.0xbmpug.mongodb.net/?retryWrites=true&w=majority`);
  await client.connect();
  db = client.db("musix");
  bucket = new GridFSBucket(db);
  cb();
}

export { db, bucket, connectToDb };
</code>```

The files are audio files(.mp3). Is there a way I can download them. I would prefer not using mongoose.

I tried:

```<code>  var fs_write_stream = fs.createWriteStream('./newAudio.mp3');
  var readstream = bucket.createReadStream({_id: songInfo[0]._id});
  readstream.pipe(fs_write_stream);
  fs_write_stream.on("close", function () {
    console.log('File has been written fully!')
  });
</code>```

but these returned error as createReadStream not a function.

Body:
I referenced GridFS-download files to download the files stored in mongoDB but it writes an empty file. I have made sure that the files in my database aren't empty.

server.js:

import fs from "fs";
import path from "path";
import express from "express";
import "dotenv/config";
import { db, bucket, connectToDb } from "./db.js";
import { fileURLToPath } from "url";
import cors from "cors";
import { ObjectId } from "mongodb";

const app = express();
app.use(express.json());
app.use(cors());

const PORT = process.env.PORT || 8000;

app.get("/", async (req, res) => {
  const cursor = bucket.find({});
  const songInfo = await cursor.toArray();
  console.log("id", songInfo[0]._id);
  bucket.openDownloadStream(songInfo[0]._id).pipe(fs.createWriteStream('./outputFile.mp3'));
  res.json(songInfo);
});

connectToDb(() => {
  console.log("Successfully connected to database!!");
  app.listen(PORT, () => {
    console.log("Server is listening on port " + PORT);
  });
});

db.js:

import { GridFSBucket, MongoClient } from "mongodb";

let db, bucket;

async function connectToDb(cb) {
  const client = new MongoClient(`mongodb+srv://${process.env.MONGO_USERNAME}:${process.env.MONGO_PASSWORD}@cluster0.0xbmpug.mongodb.net/?retryWrites=true&w=majority`);
  await client.connect();
  db = client.db("musix");
  bucket = new GridFSBucket(db);
  cb();
}

export { db, bucket, connectToDb };

The files are audio files(.mp3). Is there a way I can download them. I would prefer not using mongoose.

I tried:

  var fs_write_stream = fs.createWriteStream('./newAudio.mp3');
  var readstream = bucket.createReadStream({_id: songInfo[0]._id});
  readstream.pipe(fs_write_stream);
  fs_write_stream.on("close", function () {
    console.log('File has been written fully!')
  });

but these returned error as createReadStream not a function.


问:
How can I create a recursive TypeScript utility for deeply nested nullable fields using lookup types?
I'm using graphql-codegen which has generated the following type:

```<code>type GetMenuQuery = {
  __typename?: "RootQuery"
  menu?: {
    __typename?: "Menu"
    id: string
    menuItems?: {
      __typename?: "MenuToMenuItemConnection"
      nodes: Array<{
        __typename?: "MenuItem"
        id: string
        url?: string | null
        label?: string | null
        childItems?: {
          __typename?: "MenuItemToMenuItemConnection"
          nodes: Array<{
            __typename?: "MenuItem"
            id: string
            url?: string | null
            label?: string | null
            childItems?: {
              __typename?: "MenuItemToMenuItemConnection"
              nodes: Array<{
                __typename?: "MenuItem"
                id: string
                url?: string | null
                label?: string | null
                childItems?: {
                  __typename?: "MenuItemToMenuItemConnection"
                  nodes: Array<{
                    __typename?: "MenuItem"
                    id: string
                    url?: string | null
                    label?: string | null
                  }>
                } | null
              }>
            } | null
          }>
        } | null
      }>
    } | null
  } | null
}
</code>```

I'm fetching the data in my Layout component and I want to pass only the menu.menuItems.nodes object to a Header component. In the Header component, I want to type the props. I will be ensuring it's not null before passing it to Header (i.e. {menu?.menuItems?.nodes && <Header menuItems={menu.menuItems.nodes}).

I can't just set the type of the props as { menuItems: GetMenuQuery["menu"]["menuItems"]["nodes"] } because each level is nullable.

I could do { menuItems: NonNullable<NonNullable<GetMenuQuery["menu"]>["menuItems"]>["nodes"] } but this will be happening with many components and sometimes even deeper than this example.

Is there a better way of doing this? I'm hoping for some sort of utility that can accept any number of arguments and recursively make them NonNullable, but I'm admittedly beyond my knowledge here.

The end result I'm imagining would be to use it as such: { menuItems: NullBeGone<GetMenuQuery, ["menu", "menuItems", "nodes"]> } where it iterates through the second argument (array) and performs NonNullable<T, array[i]> and the T on each subsequent iteration is the result of the previous iteration.

{ menuItems: NonNullable<NonNullable<GetMenuQuery["menu"]>["menuItems"]>["nodes"] }

This will get really ugly really fast.

Body:
I'm using graphql-codegen which has generated the following type:

type GetMenuQuery = {
  __typename?: "RootQuery"
  menu?: {
    __typename?: "Menu"
    id: string
    menuItems?: {
      __typename?: "MenuToMenuItemConnection"
      nodes: Array<{
        __typename?: "MenuItem"
        id: string
        url?: string | null
        label?: string | null
        childItems?: {
          __typename?: "MenuItemToMenuItemConnection"
          nodes: Array<{
            __typename?: "MenuItem"
            id: string
            url?: string | null
            label?: string | null
            childItems?: {
              __typename?: "MenuItemToMenuItemConnection"
              nodes: Array<{
                __typename?: "MenuItem"
                id: string
                url?: string | null
                label?: string | null
                childItems?: {
                  __typename?: "MenuItemToMenuItemConnection"
                  nodes: Array<{
                    __typename?: "MenuItem"
                    id: string
                    url?: string | null
                    label?: string | null
                  }>
                } | null
              }>
            } | null
          }>
        } | null
      }>
    } | null
  } | null
}

I'm fetching the data in my Layout component and I want to pass only the menu.menuItems.nodes object to a Header component. In the Header component, I want to type the props. I will be ensuring it's not null before passing it to Header (i.e. {menu?.menuItems?.nodes && <Header menuItems={menu.menuItems.nodes}).

I can't just set the type of the props as { menuItems: GetMenuQuery["menu"]["menuItems"]["nodes"] } because each level is nullable.

I could do { menuItems: NonNullable<NonNullable<GetMenuQuery["menu"]>["menuItems"]>["nodes"] } but this will be happening with many components and sometimes even deeper than this example.

Is there a better way of doing this? I'm hoping for some sort of utility that can accept any number of arguments and recursively make them NonNullable, but I'm admittedly beyond my knowledge here.

The end result I'm imagining would be to use it as such: { menuItems: NullBeGone<GetMenuQuery, ["menu", "menuItems", "nodes"]> } where it iterates through the second argument (array) and performs NonNullable<T, array[i]> and the T on each subsequent iteration is the result of the previous iteration.

{ menuItems: NonNullable<NonNullable<GetMenuQuery["menu"]>["menuItems"]>["nodes"] }

This will get really ugly really fast.


问:
Android Studio asking for bluetooth permission check even though it's already present
See lines 94-95 in mainactivity file.

```<code>**bluetoothSocket = bluetoothDevice.createRfcommSocketToServiceRecord(MY_UUID);
           bluetoothSocket.connect();**
           inputStream = bluetoothSocket.getInputStream();
</code>```

Am receiving this error:

"Call requires permission which may be rejected by user: code should explicitly check to see if permission is available (with checkPermission) or explicitly handle a potential SecurityException."

I tried adding the onRequestPermissionsResult method and preceding if-statement, but I am still receiving the error. What more is needed?

Am using HC-05 module to transmit serial data from arduino to android device. Thanks.

Manifest attached as well

AndroidManifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>

\<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"\>

    <!--Before Android 12 (but still needed location, even if not requested)-->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" android:maxSdkVersion="30" />
    <!--From Android 12-->
    <uses-permission android:name="android.permission.BLUETOOTH_SCAN" android:usesPermissionFlags="neverForLocation" />
    <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.StrikeTec"
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

            <meta-data
                android:name="android.app.lib_name"
                android:value="" />
        </activity>
    </application>

</code>```

MainActivity.java

`

```<code>package com.example.striketec;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.UUID;

public class MainActivity extends AppCompatActivity {
private static final int REQUEST_BLUETOOTH_PERMISSIONS = 1;
private static final String\[\] BLUETOOTH_PERMISSIONS = {
Manifest.permission.BLUETOOTH,
Manifest.permission.BLUETOOTH_ADMIN
};
private static final String MAC_ADDRESS = "00:11:22:33:44:55"; // Replace with your device's MAC address
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); // Standard SPP UUID

private BluetoothAdapter bluetoothAdapter;
private BluetoothDevice bluetoothDevice;
private BluetoothSocket bluetoothSocket;
private InputStream inputStream;
private BufferedReader reader;

private TextView fastestTextView;
private TextView slowestTextView;
private TextView averageTextView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

       fastestTextView = findViewById(R.id.fastest_text_view);
       slowestTextView = findViewById(R.id.slowest_text_view);
       averageTextView = findViewById(R.id.average_text_view);

       // Check if the app has the required permissions
       if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH) != PackageManager.PERMISSION_GRANTED
               || ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_ADMIN) != PackageManager.PERMISSION_GRANTED) {
           // Request the permissions if they are not granted
           ActivityCompat.requestPermissions(this, BLUETOOTH_PERMISSIONS, REQUEST_BLUETOOTH_PERMISSIONS);
       } else {
           // Initialize Bluetooth if the permissions are already granted
           initBluetooth();
       }

}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String\[\] permissions, @NonNull int\[\] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_BLUETOOTH_PERMISSIONS) {
if (grantResults.length \> 0 && grantResults\[0\] == PackageManager.PERMISSION_GRANTED
&& grantResults\[1\] == PackageManager.PERMISSION_GRANTED) {
// Initialize Bluetooth if the permissions are granted
initBluetooth();
} else {
Toast.makeText(this, "Bluetooth permissions are required", Toast.LENGTH_SHORT).show();
finish();
}
}
}

private void initBluetooth() {
// Initialize Bluetooth here
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not supported on this device", Toast.LENGTH_SHORT).show();
finish();
return;
}

       if (!bluetoothAdapter.isEnabled()) {
           Toast.makeText(this, "Please enable Bluetooth", Toast.LENGTH_SHORT).show();
           finish();
           return;
       }

       bluetoothDevice = bluetoothAdapter.getRemoteDevice(MAC_ADDRESS);
       try {
           **bluetoothSocket = bluetoothDevice.createRfcommSocketToServiceRecord(MY_UUID);
           bluetoothSocket.connect();**
           inputStream = bluetoothSocket.getInputStream();
           reader = new BufferedReader(new InputStreamReader(inputStream));
           new Thread(new Runnable() {
               @Override
               public void run() {
                   while (true) {
                       try {
                           final String data = reader.readLine();
                           runOnUiThread(new Runnable() {
                               @Override
                               public void run() {
                                   // Update the UI with the data received
                                   fastestTextView.setText(data);
                                   slowestTextView.setText(data);
                                   averageTextView.setText(data);
                                   }
                               });
                           } catch (IOException e) {
                               e.printStackTrace();
                           }
                       }
                   }
               }).start();
           } catch (IOException e) {
           e.printStackTrace();
           }
       }

}\`

</code>```

I tried adding the onRequestPermissionsResult method and preceding if-statement, but I am still receiving the error. What more is needed? Expected this to suffice and the error to disappear.

Body:
See lines 94-95 in mainactivity file.

**bluetoothSocket = bluetoothDevice.createRfcommSocketToServiceRecord(MY_UUID);
           bluetoothSocket.connect();**
           inputStream = bluetoothSocket.getInputStream();

Am receiving this error:

"Call requires permission which may be rejected by user: code should explicitly check to see if permission is available (with checkPermission) or explicitly handle a potential SecurityException."

I tried adding the onRequestPermissionsResult method and preceding if-statement, but I am still receiving the error. What more is needed?

Am using HC-05 module to transmit serial data from arduino to android device. Thanks.

Manifest attached as well

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>

\<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"\>

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" android:maxSdkVersion="30" />

    <uses-permission android:name="android.permission.BLUETOOTH_SCAN" android:usesPermissionFlags="neverForLocation" />
    <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.StrikeTec"
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

            <meta-data
                android:name="android.app.lib_name"
                android:value="" />
        </activity>
    </application>

MainActivity.java

`

package com.example.striketec;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.UUID;

public class MainActivity extends AppCompatActivity {
private static final int REQUEST_BLUETOOTH_PERMISSIONS = 1;
private static final String\[\] BLUETOOTH_PERMISSIONS = {
Manifest.permission.BLUETOOTH,
Manifest.permission.BLUETOOTH_ADMIN
};
private static final String MAC_ADDRESS = "00:11:22:33:44:55"; // Replace with your device's MAC address
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); // Standard SPP UUID

private BluetoothAdapter bluetoothAdapter;
private BluetoothDevice bluetoothDevice;
private BluetoothSocket bluetoothSocket;
private InputStream inputStream;
private BufferedReader reader;

private TextView fastestTextView;
private TextView slowestTextView;
private TextView averageTextView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

       fastestTextView = findViewById(R.id.fastest_text_view);
       slowestTextView = findViewById(R.id.slowest_text_view);
       averageTextView = findViewById(R.id.average_text_view);

       // Check if the app has the required permissions
       if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH) != PackageManager.PERMISSION_GRANTED
               || ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_ADMIN) != PackageManager.PERMISSION_GRANTED) {
           // Request the permissions if they are not granted
           ActivityCompat.requestPermissions(this, BLUETOOTH_PERMISSIONS, REQUEST_BLUETOOTH_PERMISSIONS);
       } else {
           // Initialize Bluetooth if the permissions are already granted
           initBluetooth();
       }

}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String\[\] permissions, @NonNull int\[\] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_BLUETOOTH_PERMISSIONS) {
if (grantResults.length \> 0 && grantResults\[0\] == PackageManager.PERMISSION_GRANTED
&& grantResults\[1\] == PackageManager.PERMISSION_GRANTED) {
// Initialize Bluetooth if the permissions are granted
initBluetooth();
} else {
Toast.makeText(this, "Bluetooth permissions are required", Toast.LENGTH_SHORT).show();
finish();
}
}
}

private void initBluetooth() {
// Initialize Bluetooth here
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not supported on this device", Toast.LENGTH_SHORT).show();
finish();
return;
}

       if (!bluetoothAdapter.isEnabled()) {
           Toast.makeText(this, "Please enable Bluetooth", Toast.LENGTH_SHORT).show();
           finish();
           return;
       }

       bluetoothDevice = bluetoothAdapter.getRemoteDevice(MAC_ADDRESS);
       try {
           **bluetoothSocket = bluetoothDevice.createRfcommSocketToServiceRecord(MY_UUID);
           bluetoothSocket.connect();**
           inputStream = bluetoothSocket.getInputStream();
           reader = new BufferedReader(new InputStreamReader(inputStream));
           new Thread(new Runnable() {
               @Override
               public void run() {
                   while (true) {
                       try {
                           final String data = reader.readLine();
                           runOnUiThread(new Runnable() {
                               @Override
                               public void run() {
                                   // Update the UI with the data received
                                   fastestTextView.setText(data);
                                   slowestTextView.setText(data);
                                   averageTextView.setText(data);
                                   }
                               });
                           } catch (IOException e) {
                               e.printStackTrace();
                           }
                       }
                   }
               }).start();
           } catch (IOException e) {
           e.printStackTrace();
           }
       }

}\`

I tried adding the onRequestPermissionsResult method and preceding if-statement, but I am still receiving the error. What more is needed? Expected this to suffice and the error to disappear.


问:
Draw choropleth map for US states using plotly
I have json file for us states boundaries from here: https://eric.clst.org/assets/wiki/uploads/Stuff/gz_2010_us_040_00_5m.json'

Also I have information about population of US states in df_state (https://docs.google.com/spreadsheets/d/12_4mOvF3skwWcIG_LojC07UOpjXPjhN9dRcqb6kxYck/edit?usp=sharing), that looks like this:

NAME
april
2020
Total Population

Alabama
5,024,279
5,024,803
5,039,877

Alaska
733,391
732,441
732,673

Arizona
7,151,502
7,177,986
7,276,316

Based on these two sources, I decided to draw a choropleth map on plotly that would draw US states and color them based on total population:

```<code>geo_states='https://eric.clst.org/assets/wiki/uploads/Stuff/gz_2010_us_040_00_5m.json'
with urlopen(geo_states) as response:
    geo_states= json.load(response)

df_state=pd.read_csv('state.csv')
df_state['Total Population']=df_state['Total Population'].str.replace(',','').astype(int)

fig_states = px.choropleth_mapbox(df_state,
                                   geojson=geo_states,
                                   locations='NAME',
                                   featureidkey='properties.NAME',
                                   color='Total Population',
                                   color_continuous_scale="Viridis",
                                   mapbox_style="carto-positron",
                                   opacity=0.3
                                   )
fig_states.update_layout(autosize=False, height=600, width=1000, margin={"r":0,"t":0,"l":0,"b":0})
fig_states.show()
</code>```

But i got blank return:

How to fix this?

Body:
I have json file for us states boundaries from here: https://eric.clst.org/assets/wiki/uploads/Stuff/gz_2010_us_040_00_5m.json'

Also I have information about population of US states in df_state (https://docs.google.com/spreadsheets/d/12_4mOvF3skwWcIG_LojC07UOpjXPjhN9dRcqb6kxYck/edit?usp=sharing), that looks like this:

NAME
april
2020
Total Population

Alabama
5,024,279
5,024,803
5,039,877

Alaska
733,391
732,441
732,673

Arizona
7,151,502
7,177,986
7,276,316

Based on these two sources, I decided to draw a choropleth map on plotly that would draw US states and color them based on total population:

geo_states='https://eric.clst.org/assets/wiki/uploads/Stuff/gz_2010_us_040_00_5m.json'
with urlopen(geo_states) as response:
    geo_states= json.load(response)

df_state=pd.read_csv('state.csv')
df_state['Total Population']=df_state['Total Population'].str.replace(',','').astype(int)

fig_states = px.choropleth_mapbox(df_state,
                                   geojson=geo_states,
                                   locations='NAME',
                                   featureidkey='properties.NAME',
                                   color='Total Population',
                                   color_continuous_scale="Viridis",
                                   mapbox_style="carto-positron",
                                   opacity=0.3
                                   )
fig_states.update_layout(autosize=False, height=600, width=1000, margin={"r":0,"t":0,"l":0,"b":0})
fig_states.show()

But i got blank return:

How to fix this?


问:
why from a grayscale image I get values of 255 in pixels that are not white?
For example in the coordinates of the example vector in the following code block I get for each pixel a value of 255 when in the reference image to various shades of gray

```<code>import cv2

#Function to obtain coordinates within the vector
def bresenham(x1, y1, x2, y2):
    # Inicializar variables
    dx = abs(x2 - x1)
    dy = abs(y2 - y1)
    x, y = x1, y1
    sx = -1 if x1 > x2 else 1
    sy = -1 if y1 > y2 else 1
    error = dx - dy

    # Iterate over the points of the vector
    coords = []
    while True:
        coords.append((x, y))
        if x == x2 and y == y2:
            break
        e2 = 2 * error
        if e2 > -dy:
            error -= dy
            x += sx
        if e2 < dx:
            error += dx
            y += sy
    return coords

#Create images
originalImage = cv2.imread("image.jpg",3)
gray = cv2.cvtColor(originalImage, cv2.COLOR_BGR2GRAY)

# Vector coordinates
x1, y1 = 300, 120
x2, y2 = 400, 200

#Obtain the coordinates inside the vector
coords = bresenham(x1, y1, x2, y2)

# obtain the value of each pixel
for i in range(len(coords)-1):
    imagex,imagey=coords[i]
    pixel = gray[imagex,imagey]
    print(imagex,imagey)
    print(pixel)

# print(coords)
# cv2.line(gray, (x1, y1), (x2, y2), (0, 0, 0), 1)
cv2.namedWindow("black", cv2.WINDOW_NORMAL)
cv2.imshow("black", gray)

cv2.waitKey()
cv2.destroyAllWindows()
</code>```

Even drawing a line to corroborate before the pixel check or after to see that you are trying to acquire the correct values.

I attach the reference image.enter image description here

Body:
For example in the coordinates of the example vector in the following code block I get for each pixel a value of 255 when in the reference image to various shades of gray

import cv2

#Function to obtain coordinates within the vector
def bresenham(x1, y1, x2, y2):
    # Inicializar variables
    dx = abs(x2 - x1)
    dy = abs(y2 - y1)
    x, y = x1, y1
    sx = -1 if x1 > x2 else 1
    sy = -1 if y1 > y2 else 1
    error = dx - dy

    # Iterate over the points of the vector
    coords = []
    while True:
        coords.append((x, y))
        if x == x2 and y == y2:
            break
        e2 = 2 * error
        if e2 > -dy:
            error -= dy
            x += sx
        if e2 < dx:
            error += dx
            y += sy
    return coords

#Create images
originalImage = cv2.imread("image.jpg",3)
gray = cv2.cvtColor(originalImage, cv2.COLOR_BGR2GRAY)

# Vector coordinates
x1, y1 = 300, 120
x2, y2 = 400, 200

#Obtain the coordinates inside the vector
coords = bresenham(x1, y1, x2, y2)

# obtain the value of each pixel
for i in range(len(coords)-1):
    imagex,imagey=coords[i]
    pixel = gray[imagex,imagey]
    print(imagex,imagey)
    print(pixel)

# print(coords)
# cv2.line(gray, (x1, y1), (x2, y2), (0, 0, 0), 1)
cv2.namedWindow("black", cv2.WINDOW_NORMAL)
cv2.imshow("black", gray)

cv2.waitKey()
cv2.destroyAllWindows()

Even drawing a line to corroborate before the pixel check or after to see that you are trying to acquire the correct values.

I attach the reference image.enter image description here


问:
mono: command not found in VSCode
```<code>/Users/jaehunshim/.vscode/extensions/ms-dotnettools.csharp-1.24.4-darwin-arm64/.omnisharp/1.39.3-beta.27/run: line 19: mono: command not found
</code>```

The following error is showing when I'm trying to open omnisharp project.
I already download latest version of .NET and Mono Framework but the error is showing command not found.

Title: mono: command not found in VSCode

Body:
/Users/jaehunshim/.vscode/extensions/ms-dotnettools.csharp-1.24.4-darwin-arm64/.omnisharp/1.39.3-beta.27/run: line 19: mono: command not found

The following error is showing when I'm trying to open omnisharp project.
I already download latest version of .NET and Mono Framework but the error is showing command not found.


问:
How to pass first part of route and then the rest of path nginx
I have an auth_request in my /protected/ path. Everything works fine so far. But I want that every request that includes /protected/ for example /protected/application1 and /protected/application2 will be go first through the /protected/ location with the authentication and if this is passed go to the further location.
I have this so far but it doesn't seem that the authentication has any impact of the route.
So when I call /protected/ everything works as expected, when I call /protected/application1 it doesn't matter if the authentication succeeds or not.

This is part of my config:

```<code>   location /protected/application1 {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_pass http://localhost:4501;
    }
    location /protected/application2 {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_pass http://localhost:4502;
    }
    location /protected/ {
        auth_request /auth;
        auth_request_set $auth_status $upstream_status;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_pass http://localhost:4500;
    }
    location = /auth {
        internal;
        proxy_pass http://localhost:8081/welcome;
        proxy_set_header Content-Length "";
        proxy_set_header X-Original-URI $request_uri;
    }
</code>```

Do you have any suggestions?

Thank you very much!

Body:
I have an auth_request in my /protected/ path. Everything works fine so far. But I want that every request that includes /protected/ for example /protected/application1 and /protected/application2 will be go first through the /protected/ location with the authentication and if this is passed go to the further location.
I have this so far but it doesn't seem that the authentication has any impact of the route.
So when I call /protected/ everything works as expected, when I call /protected/application1 it doesn't matter if the authentication succeeds or not.

This is part of my config:

   location /protected/application1 {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_pass http://localhost:4501;
    }
    location /protected/application2 {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_pass http://localhost:4502;
    }
    location /protected/ {
        auth_request /auth;
        auth_request_set $auth_status $upstream_status;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_pass http://localhost:4500;
    }
    location = /auth {
        internal;
        proxy_pass http://localhost:8081/welcome;
        proxy_set_header Content-Length "";
        proxy_set_header X-Original-URI $request_uri;
    }

Do you have any suggestions?

Thank you very much!


问:
GraphQL and N+1 problem solutions with prisma
I have a GraphQL api implemented with Nexus-graphql and Prisma + Postgres.

Prisma has a nice solution for N+1 issue with query batching when it comes to GraphQL but seems to be working on 2 levels of nesting, e.g. User -> Posts, but when we need multiple levels of GraphQL nesting (User -> Posts -> Comments -> Likes -> Users) it seems to execute hundreds of queries.

What are the general best practices for doing query optimization in such cases?
I have 2 ideas but maybe there are more:

Using prisma's "include" option. Construct a map of prisma relations based on the received graphql query (from "info" field) and query all the relations at once in a single query.

Using a dataloader, query all necessary data and save to dataloader and within the resolvers load models from dataloder.


问:
Azure Function's log streams from Azure Event Hub can't be consumed by Filebeat
Our team wants to import the log of Azure Function by Azure Event Hub and Filebeat into Elastic Search. We followed this references to set up an Event Hub for Azure function. But we faced an issue with the wrong format of the log stream.

Firstly, Let me show what's the correct format we expect. Take Azure PostgresSQL's log from Event Hub for example:

```<code>[
  {
    "records": [
      {
        "time": "2023-01-04T03:45:31.1040000Z",
        "properties": {
          "timestamp": "2023-01-04 03:45:31.104 UTC",
          "processId": 8909,
          "errorLevel": "LOG",
          "sqlerrcode": "00000",
          "message": "2023-01-04 03:45:31 UTC-63b4f65b.22cd-LOG:  connection received: host=<host> port=<port>"
        },
        "resourceId": "/SUBSCRIPTIONS/<my subscription id>/RESOURCEGROUPS/<my resource group>/PROVIDERS/MICROSOFT.DBFORPOSTGRESQL/FLEXIBLESERVERS/<postgres server>",
        "category": "PostgreSQLLogs",
        "operationName": "LogEvent"
      }
    ]
  }
]
</code>```

Notice that the properties is a flattened json so that it can be consumed by Filebeat. We want this kind of properties. But the Azure Function's log looks like the following, which is a string rather than flattened json:

```<code>[
  {
    "records": [
      {
        "level": "Informational",
        "resourceId": "/SUBSCRIPTIONS/<my subscription id>/RESOURCEGROUPS/<my resource group>/PROVIDERS/MICROSOFT.WEB/SITES/<my azure function>"
        "operationName": "Microsoft.Web/sites/functions/log",
        "category": "FunctionAppLogs",
        "time": "01/04/2023 01:55:00",
        "properties": "{'appName':'<my azure function>','roleInstance':'<id>','message':'Host Status: {\\n  \\'id\\': \\'<function app id>\\',\\n  \\'state\\': \\'Running\\',\\n  \\'version\\': \\'4.13.0.0\\',\\n  \\'versionDetails\\': \\'4.13.0+da9a765ed67be48c79440526f78fa1b5c6efdeea\\',\\n  \\'platformVersion\\': \\'99.0.10.764\\',\\n  \\'instanceId\\': \\'<instance id>\\',\\n  \\'computerName\\': \\'<computer name>\\',\\n  \\'processUptime\\': 69254486,\\n  \\'functionAppContentEditingState\\': \\'Unknown\\'\\n}','category':'Host.Controllers.Host','hostVersion':'4.13.0.0','hostInstanceId':'<host id>','level':'Information','levelId':2,'processId':1}",
        "EventStampType": "Stamp",
        "EventPrimaryStampName": "waws-prod-ty1-081",
        "EventStampName": "waws-prod-ty1-081",
        "Host": "<host name>",
        "EventIpAddress": "<ip address>"
      },
</code>```

The string value of properties can't be processed by decode_json_fields of Filebeat either because the format is not json (the format is 'key': value rather than "key": value). Is there any way to correct the format of properties before it is consumed by Filebeat? By the way, our Azure Function is deployed using a container.

Body:
Our team wants to import the log of Azure Function by Azure Event Hub and Filebeat into Elastic Search. We followed this references to set up an Event Hub for Azure function. But we faced an issue with the wrong format of the log stream.

Firstly, Let me show what's the correct format we expect. Take Azure PostgresSQL's log from Event Hub for example:

[
  {
    "records": [
      {
        "time": "2023-01-04T03:45:31.1040000Z",
        "properties": {
          "timestamp": "2023-01-04 03:45:31.104 UTC",
          "processId": 8909,
          "errorLevel": "LOG",
          "sqlerrcode": "00000",
          "message": "2023-01-04 03:45:31 UTC-63b4f65b.22cd-LOG:  connection received: host=<host> port=<port>"
        },
        "resourceId": "/SUBSCRIPTIONS/<my subscription id>/RESOURCEGROUPS/<my resource group>/PROVIDERS/MICROSOFT.DBFORPOSTGRESQL/FLEXIBLESERVERS/<postgres server>",
        "category": "PostgreSQLLogs",
        "operationName": "LogEvent"
      }
    ]
  }
]

Notice that the properties is a flattened json so that it can be consumed by Filebeat. We want this kind of properties. But the Azure Function's log looks like the following, which is a string rather than flattened json:

[
  {
    "records": [
      {
        "level": "Informational",
        "resourceId": "/SUBSCRIPTIONS/<my subscription id>/RESOURCEGROUPS/<my resource group>/PROVIDERS/MICROSOFT.WEB/SITES/<my azure function>"
        "operationName": "Microsoft.Web/sites/functions/log",
        "category": "FunctionAppLogs",
        "time": "01/04/2023 01:55:00",
        "properties": "{'appName':'<my azure function>','roleInstance':'<id>','message':'Host Status: {\\n  \\'id\\': \\'<function app id>\\',\\n  \\'state\\': \\'Running\\',\\n  \\'version\\': \\'4.13.0.0\\',\\n  \\'versionDetails\\': \\'4.13.0+da9a765ed67be48c79440526f78fa1b5c6efdeea\\',\\n  \\'platformVersion\\': \\'99.0.10.764\\',\\n  \\'instanceId\\': \\'<instance id>\\',\\n  \\'computerName\\': \\'<computer name>\\',\\n  \\'processUptime\\': 69254486,\\n  \\'functionAppContentEditingState\\': \\'Unknown\\'\\n}','category':'Host.Controllers.Host','hostVersion':'4.13.0.0','hostInstanceId':'<host id>','level':'Information','levelId':2,'processId':1}",
        "EventStampType": "Stamp",
        "EventPrimaryStampName": "waws-prod-ty1-081",
        "EventStampName": "waws-prod-ty1-081",
        "Host": "<host name>",
        "EventIpAddress": "<ip address>"
      },

The string value of properties can't be processed by decode_json_fields of Filebeat either because the format is not json (the format is 'key': value rather than "key": value). Is there any way to correct the format of properties before it is consumed by Filebeat? By the way, our Azure Function is deployed using a container.


问:
Why isn’t order after payeer payment getting marked as complete?
Already did test payments using payeer payment it goes through fine and I have set return url to payment success page via payeer settings, but no email is generated to website admin via woocommerce saying order paid or completed how to fix this? Also note that there is also another payment method which is manually done so a global code would not be ideal. So payment method specific code would be awesome if have any which can be injected to functions.php</p>


问:
java.lang.NullPointerException after upgrading WSO2 API manager upgrade from 3.1.0 to 4.0.0
we have upgraded wso2 API manager  from 3.1.0 to 4.0.0 using below link. During upgrade we did not see any error in logs.

https://apim.docs.wso2.com/en/4.0.0/install-and-setup/upgrading-wso2-api-manager/upgrading-from-310-to-400/

But we are getting error while access application end point after publishing to wso2 .

```<code>TID: [-1234] [] [2023-01-06 01:22:40,915] ERROR {org.apache.synapse.transport.passthru.ServerWorker} - Error processing GET request for : /pizzashack/2.0/menu. java.lang.NullPointerException
        at org.wso2.carbon.apimgt.gateway.handlers.security.jwt.JWTValidator.<init>(JWTValidator.java:108)
        at org.wso2.carbon.apimgt.gateway.handlers.security.oauth.OAuthAuthenticator.authenticate_aroundBody4(OAuthAuthenticator.java:130)
        at org.wso2.carbon.apimgt.gateway.handlers.security.oauth.OAuthAuthenticator.authenticate(OAuthAuthenticator.java:115)
        at org.wso2.carbon.apimgt.gateway.handlers.security.APIAuthenticationHandler.isAuthenticate_aroundBody42(APIAuthenticationHandler.java:428)
        at org.wso2.carbon.apimgt.gateway.handlers.security.APIAuthenticationHandler.isAuthenticate(APIAuthenticationHandler.java:422)
        at org.wso2.carbon.apimgt.gateway.handlers.security.APIAuthenticationHandler.handleRequest_aroundBody36(APIAuthenticationHandler.java:353)
        at org.wso2.carbon.apimgt.gateway.handlers.security.APIAuthenticationHandler.handleRequest(APIAuthenticationHandler.java:317)
        at org.apache.synapse.api.API.process(API.java:389)
        at org.apache.synapse.api.AbstractApiHandler.apiProcessNonDefaultStrategy(AbstractApiHandler.java:107)
        at org.apache.synapse.api.AbstractApiHandler.identifyAPI(AbstractApiHandler.java:127)
        at org.apache.synapse.api.AbstractApiHandler.dispatchToAPI(AbstractApiHandler.java:59)
        at org.apache.synapse.api.rest.RestRequestHandler.dispatchToAPI(RestRequestHandler.java:84)
        at org.apache.synapse.api.rest.RestRequestHandler.process(RestRequestHandler.java:70)
        at org.apache.synapse.rest.RESTRequestHandler.process(RESTRequestHandler.java:54)
        at org.apache.synapse.core.axis2.Axis2SynapseEnvironment.injectMessage(Axis2SynapseEnvironment.java:344)
        at org.apache.synapse.core.axis2.SynapseMessageReceiver.receive(SynapseMessageReceiver.java:101)
        at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:180)
        at org.apache.synapse.transport.passthru.ServerWorker.processNonEntityEnclosingRESTHandler(ServerWorker.java:375)
        at org.apache.synapse.transport.passthru.ServerWorker.run(ServerWorker.java:189)
        at org.apache.axis2.transport.base.threads.NativeWorkerPool$1.run(NativeWorkerPool.java:172)
        at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
        at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)

        at java.base/java.lang.Thread.run(Thread.java:834)
</code>```

Body:
we have upgraded wso2 API manager  from 3.1.0 to 4.0.0 using below link. During upgrade we did not see any error in logs.

https://apim.docs.wso2.com/en/4.0.0/install-and-setup/upgrading-wso2-api-manager/upgrading-from-310-to-400/

But we are getting error while access application end point after publishing to wso2 .

TID: [-1234] [] [2023-01-06 01:22:40,915] ERROR {org.apache.synapse.transport.passthru.ServerWorker} - Error processing GET request for : /pizzashack/2.0/menu. java.lang.NullPointerException
        at org.wso2.carbon.apimgt.gateway.handlers.security.jwt.JWTValidator.<init>(JWTValidator.java:108)
        at org.wso2.carbon.apimgt.gateway.handlers.security.oauth.OAuthAuthenticator.authenticate_aroundBody4(OAuthAuthenticator.java:130)
        at org.wso2.carbon.apimgt.gateway.handlers.security.oauth.OAuthAuthenticator.authenticate(OAuthAuthenticator.java:115)
        at org.wso2.carbon.apimgt.gateway.handlers.security.APIAuthenticationHandler.isAuthenticate_aroundBody42(APIAuthenticationHandler.java:428)
        at org.wso2.carbon.apimgt.gateway.handlers.security.APIAuthenticationHandler.isAuthenticate(APIAuthenticationHandler.java:422)
        at org.wso2.carbon.apimgt.gateway.handlers.security.APIAuthenticationHandler.handleRequest_aroundBody36(APIAuthenticationHandler.java:353)
        at org.wso2.carbon.apimgt.gateway.handlers.security.APIAuthenticationHandler.handleRequest(APIAuthenticationHandler.java:317)
        at org.apache.synapse.api.API.process(API.java:389)
        at org.apache.synapse.api.AbstractApiHandler.apiProcessNonDefaultStrategy(AbstractApiHandler.java:107)
        at org.apache.synapse.api.AbstractApiHandler.identifyAPI(AbstractApiHandler.java:127)
        at org.apache.synapse.api.AbstractApiHandler.dispatchToAPI(AbstractApiHandler.java:59)
        at org.apache.synapse.api.rest.RestRequestHandler.dispatchToAPI(RestRequestHandler.java:84)
        at org.apache.synapse.api.rest.RestRequestHandler.process(RestRequestHandler.java:70)
        at org.apache.synapse.rest.RESTRequestHandler.process(RESTRequestHandler.java:54)
        at org.apache.synapse.core.axis2.Axis2SynapseEnvironment.injectMessage(Axis2SynapseEnvironment.java:344)
        at org.apache.synapse.core.axis2.SynapseMessageReceiver.receive(SynapseMessageReceiver.java:101)
        at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:180)
        at org.apache.synapse.transport.passthru.ServerWorker.processNonEntityEnclosingRESTHandler(ServerWorker.java:375)
        at org.apache.synapse.transport.passthru.ServerWorker.run(ServerWorker.java:189)
        at org.apache.axis2.transport.base.threads.NativeWorkerPool$1.run(NativeWorkerPool.java:172)
        at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
        at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)

        at java.base/java.lang.Thread.run(Thread.java:834)


问:
TS7053: Element implicitly has an 'any' type because expression of type 'any' can't be used to index type 'Node'
I'm trying coding follow this :

https://github.com/ianstormtaylor/slate/blob/main/site/examples/hovering-toolbar.tsx

IDE tips:

TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Omit<BaseText, "text">'.   No index signature with a parameter of type 'string' was found on type 'Omit<BaseText, "text">'.

I seem to sense that I should change the type of 'format', but I've tried many types and they don't work correctly.

Here is the DEMO:

```<code>const isFormatActive = (editor:ReactEditor, format: string) => {
  const [match] = Editor.nodes(editor, {
            match: node => node[format] === true,
            mode: "all",
  });
  return !!match;
}
</code>```

Body:
I'm trying coding follow this :

https://github.com/ianstormtaylor/slate/blob/main/site/examples/hovering-toolbar.tsx

IDE tips:

TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Omit<BaseText, "text">'.   No index signature with a parameter of type 'string' was found on type 'Omit<BaseText, "text">'.

I seem to sense that I should change the type of 'format', but I've tried many types and they don't work correctly.

Here is the DEMO:

const isFormatActive = (editor:ReactEditor, format: string) => {
  const [match] = Editor.nodes(editor, {
            match: node => node[format] === true,
            mode: "all",
  });
  return !!match;
}


问:
Update Java multiple-line console output without adding new lines
I just came to the issue to update java console multiple-line output. What I want to achieve is like this output, and dynamically update the progress text and progress bar without adding new lines.

```<code>Progress: 24/100
[>>>>>>>                      ] 24%
</code>```

I saw there are some similar answers (like using System.out.print() with \r), but mostly for single line.

I'm curious is there a way to achieve the same for multiple lines?

Thanks.

Body:
I just came to the issue to update java console multiple-line output. What I want to achieve is like this output, and dynamically update the progress text and progress bar without adding new lines.

Progress: 24/100
[>>>>>>>                      ] 24%

I saw there are some similar answers (like using System.out.print() with \r), but mostly for single line.

I'm curious is there a way to achieve the same for multiple lines?

Thanks.


问:
Data cardinality is ambiguous:
I am getting an error while running the training proceess

(https://i.stack.imgur.com/rEGTw.png)

Title: Data cardinality is ambiguous:


问:
Change button text on last image of Slider in SwiftUI
I have an image slider with dot indicator named "Onboardingslider". I have used it in my another screen "onboard4" , I want to change the text of "next" button to "get started" only on last image of slider otherwise it stays "next".

I have tried a lot of things but nothing works

Please help me I'm a newbie

```<code>
struct onboard4: View {

    @State var showModal = false
    @State var maxlogoheight: CGFloat = 0
    @State var isLinkActive = false

    var body: some View {

        NavigationView {
            ZStack{

                //max height will be width of the screen
                GeometryReader{ proxy -> AnyView in

                    let height = proxy.frame(in: .global).height

                    DispatchQueue.main.async {
                        if maxlogoheight == 0 {
                            maxlogoheight = height
                        }
                    }

                    return AnyView (
            ZStack{
                Image("Logo")
                    .resizable()
                    .scaledToFit()
                    .offset(x: getReact().width/3.5, y: -height/1.25)

            }//zstack 2
           // .padding(.leading,10)

           )//anyview

          }//end of gr
           .frame(maxHeight: getReact().width)

                VStack{

                      Onboardingslider()

                    Button(action: {
                        showModal = true
                                    }) {
                                        ZStack{
                                           Text("Next")
                                            .foregroundColor(Color.white)
                                            .fontWeight(.bold)
                                            .frame (width: 295, height: 30)
                                            .padding()
                                            .background(Color("YellowAccent"))
                                            .cornerRadius(20)

                                            .shadow(color: .gray, radius: 5, x: 0, y: 4)
                                            Image("NextButtonOnboard")
                                        }
                                        }
                                    .fullScreenCover(isPresented: $showModal) {
                                        LoginView() }
                                    .offset(y: getSafearea().bottom + -55)

                }//vstack

                Button(action: {}, label: {
                    Text("Continue to the listing service")
                        .underline()
                })
                .foregroundColor(Color.black)
                .offset(y: getSafearea().bottom + 310)

            }//zstack
            .background(
                         NavigationLink(destination: LoginView(), isActive: $isLinkActive) {
                                    EmptyView()
                                }
                                .hidden()
                            )
            .toolbar {
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button(action: {
                        showModal = true
                                    }) {
                                        Text("Skip").underline()
                                    }

                                    .foregroundColor(Color("YellowAccent"))
                                    .font(.system(size: 20,weight: .semibold,design: .serif))
                                    .frame(width: 100, height: 100)
                                    .padding(.top)
                                    .fullScreenCover(isPresented: $showModal) {
                                      LoginView() }

                        //.padding(.bottom)

                }//toolbaritem

        }//toolbar
        }
    }
}

struct onboard4_Previews: PreviewProvider {
    static var previews: some View {
        onboard4()
    }
}
struct Onboardingslider: View {
    private let images = ["1", "2", "3", "4"]
    init() {
        // modify appearance
        UIPageControl.appearance().currentPageIndicatorTintColor = .orange
        UIPageControl.appearance().pageIndicatorTintColor = .gray
      }
    var body: some View {

        TabView {
                    ForEach(images, id: \.self) { item in
                        Image(item)
                            .padding(.leading,24)

                    }
                }
                  .frame(height: 600)
                .tabViewStyle(PageTabViewStyle(indexDisplayMode: .always))

    }
}

</code>```

Body:
I have an image slider with dot indicator named "Onboardingslider". I have used it in my another screen "onboard4" , I want to change the text of "next" button to "get started" only on last image of slider otherwise it stays "next".

I have tried a lot of things but nothing works

Please help me I'm a newbie

struct onboard4: View {

    @State var showModal = false
    @State var maxlogoheight: CGFloat = 0
    @State var isLinkActive = false

    var body: some View {

        NavigationView {
            ZStack{

                //max height will be width of the screen
                GeometryReader{ proxy -> AnyView in

                    let height = proxy.frame(in: .global).height

                    DispatchQueue.main.async {
                        if maxlogoheight == 0 {
                            maxlogoheight = height
                        }
                    }

                    return AnyView (
            ZStack{
                Image("Logo")
                    .resizable()
                    .scaledToFit()
                    .offset(x: getReact().width/3.5, y: -height/1.25)

            }//zstack 2
           // .padding(.leading,10)

           )//anyview

          }//end of gr
           .frame(maxHeight: getReact().width)

                VStack{

                      Onboardingslider()

                    Button(action: {
                        showModal = true
                                    }) {
                                        ZStack{
                                           Text("Next")
                                            .foregroundColor(Color.white)
                                            .fontWeight(.bold)
                                            .frame (width: 295, height: 30)
                                            .padding()
                                            .background(Color("YellowAccent"))
                                            .cornerRadius(20)

                                            .shadow(color: .gray, radius: 5, x: 0, y: 4)
                                            Image("NextButtonOnboard")
                                        }
                                        }
                                    .fullScreenCover(isPresented: $showModal) {
                                        LoginView() }
                                    .offset(y: getSafearea().bottom + -55)

                }//vstack

                Button(action: {}, label: {
                    Text("Continue to the listing service")
                        .underline()
                })
                .foregroundColor(Color.black)
                .offset(y: getSafearea().bottom + 310)

            }//zstack
            .background(
                         NavigationLink(destination: LoginView(), isActive: $isLinkActive) {
                                    EmptyView()
                                }
                                .hidden()
                            )
            .toolbar {
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button(action: {
                        showModal = true
                                    }) {
                                        Text("Skip").underline()
                                    }

                                    .foregroundColor(Color("YellowAccent"))
                                    .font(.system(size: 20,weight: .semibold,design: .serif))
                                    .frame(width: 100, height: 100)
                                    .padding(.top)
                                    .fullScreenCover(isPresented: $showModal) {
                                      LoginView() }

                        //.padding(.bottom)

                }//toolbaritem

        }//toolbar
        }
    }
}

struct onboard4_Previews: PreviewProvider {
    static var previews: some View {
        onboard4()
    }
}
struct Onboardingslider: View {
    private let images = ["1", "2", "3", "4"]
    init() {
        // modify appearance
        UIPageControl.appearance().currentPageIndicatorTintColor = .orange
        UIPageControl.appearance().pageIndicatorTintColor = .gray
      }
    var body: some View {

        TabView {
                    ForEach(images, id: \.self) { item in
                        Image(item)
                            .padding(.leading,24)

                    }
                }
                  .frame(height: 600)
                .tabViewStyle(PageTabViewStyle(indexDisplayMode: .always))

    }
}


问:
Drools: Time continuous drools rules not working
I'm trying to test the following drools rules:

```<code>declare Message
    @role(event)
    @timestamp(timestamp)
    @expires(10s)
end

rule "throttle state activated"
when
    $meta: CurrentState(throttleState == false)
    $lastMessage: Message($lastTimestamp: timestamp)
    not (Message(timestamp > $lastMessage.timestamp))
    $messages: ArrayList(size > 20) from collect(
        $message: Message() over window:time(10s)
    )
then
    $meta.setLastThrottled($lastMessage.getTimestamp());
    $meta.setThrottleState(true);
    update($meta);
end

rule "throttle state deactivated"
when
    $meta: CurrentState(throttleState == true)
    $lastMessage: Message($lastTimestamp: timestamp)
    not (Message(timestamp > $lastMessage.timestamp))
    $messages: ArrayList(size <= 20) from collect(
        $message: Message() over window:time(10s)
    )
then
    $meta.setThrottleState(false);
    update($meta);
end
</code>```

With the following two tests, these are in Scala and are using must matchers:

"rules" must {
  "successfully trigger (activate)" in {
    reset() // Resets the kie session and event listener
    // The insertAndFire function first advances the pseudo clock, then inserts the message, then triggers all
    // drools rules
    (1 to 50).foreach(i => insertAndFire(mockMessage(offsetMSec = 200 * i), timeAdvanceMSec = 200))
    // The sListener simply counts every drools rule fire amount
    sListener.getCount("throttle state activated") mustBe 1 // THIS TEST SUCCEEDS
  }

  "successfully trigger (deactivate)" in {
    reset()
    (1 to 50).foreach(i => insertAndFire(mockMessage(offsetMSec = 200 * i), timeAdvanceMSec = 200))
    (1 to 60).foreach(i => {
      // Now for the next 60 seconds, we advance the clock and fire all rules to force the deactivation to not have 20 messages in the last 10 seconds.
      // This should theoretically already trigger the rule after 10 forloop iterations.
      clock.advanceTime(1, TimeUnit.SECONDS)
      kieSession.fireAllRules
    })
    sListener.getCount("throttle state activated") mustBe 1 // THIS TEST SUCCEEDS
    sListener.getCount("throttle state deactivated") mustBe 1 // !!! THIS TEST FAILS !!!
  }
}
```

I've tried everything, and have already debugged that the throttleState variable in the CurrentState actually turns to true, but for some reason it does not want to actually trigger the deactivation rule.

When using these rules in live code, not testing code, it works fine, so I don't understand why the rules do not properly trigger. I'm using a PseudoSessionClock to simulate time during these tests and this works fine for every single other rule. My suspicion is that it has to do with the collect in the deactivation rule, but I cannot pinpoint it.

I've also tried forcefully waiting 10 seconds using a timer in real life, which of course hogs the test, but this also fails. It would not be logical that this solution would work as the activation rule does properly trigger, but it was worth a try.

MCVE Project: https://github.com/ThijmenL98/DroolsMCVE

Body:
I'm trying to test the following drools rules:

declare Message
    @role(event)
    @timestamp(timestamp)
    @expires(10s)
end

rule "throttle state activated"
when
    $meta: CurrentState(throttleState == false)
    $lastMessage: Message($lastTimestamp: timestamp)
    not (Message(timestamp > $lastMessage.timestamp))
    $messages: ArrayList(size > 20) from collect(
        $message: Message() over window:time(10s)
    )
then
    $meta.setLastThrottled($lastMessage.getTimestamp());
    $meta.setThrottleState(true);
    update($meta);
end

rule "throttle state deactivated"
when
    $meta: CurrentState(throttleState == true)
    $lastMessage: Message($lastTimestamp: timestamp)
    not (Message(timestamp > $lastMessage.timestamp))
    $messages: ArrayList(size <= 20) from collect(
        $message: Message() over window:time(10s)
    )
then
    $meta.setThrottleState(false);
    update($meta);
end

With the following two tests, these are in Scala and are using must matchers:

"rules" must {
  "successfully trigger (activate)" in {
    reset() // Resets the kie session and event listener
    // The insertAndFire function first advances the pseudo clock, then inserts the message, then triggers all
    // drools rules
    (1 to 50).foreach(i => insertAndFire(mockMessage(offsetMSec = 200 * i), timeAdvanceMSec = 200))
    // The sListener simply counts every drools rule fire amount
    sListener.getCount("throttle state activated") mustBe 1 // THIS TEST SUCCEEDS
  }

  "successfully trigger (deactivate)" in {
    reset()
    (1 to 50).foreach(i => insertAndFire(mockMessage(offsetMSec = 200 * i), timeAdvanceMSec = 200))
    (1 to 60).foreach(i => {
      // Now for the next 60 seconds, we advance the clock and fire all rules to force the deactivation to not have 20 messages in the last 10 seconds.
      // This should theoretically already trigger the rule after 10 forloop iterations.
      clock.advanceTime(1, TimeUnit.SECONDS)
      kieSession.fireAllRules
    })
    sListener.getCount("throttle state activated") mustBe 1 // THIS TEST SUCCEEDS
    sListener.getCount("throttle state deactivated") mustBe 1 // !!! THIS TEST FAILS !!!
  }
}

I've tried everything, and have already debugged that the throttleState variable in the CurrentState actually turns to true, but for some reason it does not want to actually trigger the deactivation rule.

When using these rules in live code, not testing code, it works fine, so I don't understand why the rules do not properly trigger. I'm using a PseudoSessionClock to simulate time during these tests and this works fine for every single other rule. My suspicion is that it has to do with the collect in the deactivation rule, but I cannot pinpoint it.

I've also tried forcefully waiting 10 seconds using a timer in real life, which of course hogs the test, but this also fails. It would not be logical that this solution would work as the activation rule does properly trigger, but it was worth a try.

MCVE Project: https://github.com/ThijmenL98/DroolsMCVE


问:
ReportViewer 15.0.0.0 - Remove PageWidth and WholePage option from Zoom dropdown
We have an MVC web application, and recently we migrated from Microsoft ReportViewer from 11.0.0.0 to 15.0.0.0 version.

We started having different issues in terms of UI, one of which is mentioned as below.

The Page width and Whole Page options in zoom dropdown are not working as expected. When we select any percentage like 100% or 200% the report zooms properly.

However on selection of Page Width or Whole Page nothing happens. And the report remains in the zoom which ever it was already.

So I have below 2 questions

Does any one have idea why these options does not work with ReportViewer 15.0.0.0 ?

As a work around we would like to remove these options from this dropdown. How can we remove these 2 options from this zoom options related dropdown

Below image shows about which dropdown I am talking about. Please note that this issue comes when we use ReportViewer control 15.0.0.0 with our MVC web application.


问:
Supabase `and` in the `or` query
How would I construct this filter in a select statement (I am using dart)

```<code>(senttouid = userid or (uid=userid and parent is true))
</code>```

we have the or({}) construct, which AFAIK will support the senttouid = userid or uid=userid filter, but not if the second part of 'or' has a compound filter

Using a stored procedure seems to be the way to go, but is there a direct way to construct this in the dart query?

Title: Supabase `and` in the `or` query

Body:
How would I construct this filter in a select statement (I am using dart)

(senttouid = userid or (uid=userid and parent is true))

we have the or({}) construct, which AFAIK will support the senttouid = userid or uid=userid filter, but not if the second part of 'or' has a compound filter

Using a stored procedure seems to be the way to go, but is there a direct way to construct this in the dart query?


问:
React-Laravel : Getting cors error while making an api request
I am working on a react project where I am using laravel for the backend. APIs are being called perfectly in postman but when I make a post request through react js it throws cors error and unauthorized 401

When I use axios i get Unauthorized error when I use fetch() i get cors error.

Here is my code...

api.php

```<code>Route::middleware(
    [
        'auth:sanctum',
        'CORS',
    ]
)->group(function () {
    Route::post("/admin/customer/store", [CustomerController::class, 'store']);

});
</code>```

react js code

```<code>Route::middleware(
    [
        'auth:sanctum',
        'CORS',
    ]
)->group(function () {
    Route::post("/admin/customer/store", [CustomerController::class, 'store']);

});

</code>```

Body:
I am working on a react project where I am using laravel for the backend. APIs are being called perfectly in postman but when I make a post request through react js it throws cors error and unauthorized 401

When I use axios i get Unauthorized error when I use fetch() i get cors error.

Here is my code...

api.php

Route::middleware(
    [
        'auth:sanctum',
        'CORS',
    ]
)->group(function () {
    Route::post("/admin/customer/store", [CustomerController::class, 'store']);

});

react js code

Route::middleware(
    [
        'auth:sanctum',
        'CORS',
    ]
)->group(function () {
    Route::post("/admin/customer/store", [CustomerController::class, 'store']);

});


问:
how to write a countifs formula referring to a different tab, tab ref is static, column ref should by dynamic (indirect function) based on cell value
I have an excel file with lots of variables in columns. I want to make nice tables in a different tab (and do not want to use 100s of pivot tables). I need to check each column for specific values. In fact each column becomes a table. I am using the countifs function. To efficiently do that I want to refer in the tab where I make the tables to the tab where the data is stored (same file), that reference is static. For each and every table I need to refer to a different column, so that is the dynamic part. In stead of changing all formulas for each table, I prefer to have a reference to the specific column in one cell (for each table). I know I have to use the indirect function, but can't get it work.

```<code>=countifs(worksheet!E:E;b4)
</code>```

where the E:E part should be dynamic

=countifs(indirect("Worksheet!"&a4);b4) or countifs(indirect("Worksheet!"&a4;b4)) both do not seem to work

Body:
I have an excel file with lots of variables in columns. I want to make nice tables in a different tab (and do not want to use 100s of pivot tables). I need to check each column for specific values. In fact each column becomes a table. I am using the countifs function. To efficiently do that I want to refer in the tab where I make the tables to the tab where the data is stored (same file), that reference is static. For each and every table I need to refer to a different column, so that is the dynamic part. In stead of changing all formulas for each table, I prefer to have a reference to the specific column in one cell (for each table). I know I have to use the indirect function, but can't get it work.

=countifs(worksheet!E:E;b4)

where the E:E part should be dynamic

=countifs(indirect("Worksheet!"&a4);b4) or countifs(indirect("Worksheet!"&a4;b4)) both do not seem to work


问:
Is it possible that a React app serves raw json directly?
Is it possible that the React app - similar to an API endpoint - serves a raw JSON file on a specific route?

Looking for direction regarding "architecture" of how to solve that problem


问:
include css styles of shadowed elements into extracted print content
I want to print only a part of a website for this I construct a seconds window like follows:

    const prtStyles = document.getElementsByTagName('style');
    const prtContent = document.getElementsByTagName('some-container')[0];
    const WinPrint = window.open('', '', 'left=0,top=0,width=800,height=900,toolbar=0,scrollbars=0,status=0');
    WinPrint.document.write(extractStyles(prtStyles) + prtContent.innerHTML);
    WinPrint.document.close();
    WinPrint.focus();
    WinPrint.print();
    WinPrint.close();

    function extractStyles(prtStyles) {
      let styles = '';
      for (let i = 0; i < prtStyles.length; i++) {
        styles += prtStyles[i].outerHTML;
      }
      return styles;
    }
```

This works quite fine but now, because I use WebComponents with shadowedRoot to display certain parts like headings or buttons those stylings added to these components are inside a constructed Stylesheet.

Is it possible to access those shadowed styles in some way and include them into new print window?
I can't find those styles rendered inside the dom itself.

Body:
I want to print only a part of a website for this I construct a seconds window like follows:

    const prtStyles = document.getElementsByTagName('style');
    const prtContent = document.getElementsByTagName('some-container')[0];
    const WinPrint = window.open('', '', 'left=0,top=0,width=800,height=900,toolbar=0,scrollbars=0,status=0');
    WinPrint.document.write(extractStyles(prtStyles) + prtContent.innerHTML);
    WinPrint.document.close();
    WinPrint.focus();
    WinPrint.print();
    WinPrint.close();

    function extractStyles(prtStyles) {
      let styles = '';
      for (let i = 0; i < prtStyles.length; i++) {
        styles += prtStyles[i].outerHTML;
      }
      return styles;
    }

This works quite fine but now, because I use WebComponents with shadowedRoot to display certain parts like headings or buttons those stylings added to these components are inside a constructed Stylesheet.

Is it possible to access those shadowed styles in some way and include them into new print window?
I can't find those styles rendered inside the dom itself.


问:
Getting `S3Exception` when executing download operation with `S3TransferManager` AWS SDK 2.19
I am using the S3TransferManager with S3AsyncClient in my service code. I am testing this code with localstack docker S3 service. I have the local stack S3 service and created the bucket test and uploaded one file test.txt on docker service startup.

S3Config.java

@Configuration
public class S3Configuration {
  @Value("${aws.access-key}")
  private String accessKey;
  @Value("${aws.secret-key}")
  private String secretKey;
  @Value("${aws.region}")
  private String region;
  @Value("${aws.endpoint:#{null}}")
  private String endpoint;

  @Bean
  public S3AsyncClient s3AsyncClient(AwsCredentialsProvider awsCredentialsProvider) {
    S3CrtAsyncClientBuilder s3CrtAsyncClientBuilder = S3AsyncClient.crtBuilder()
      .region(Region.of(region))
      .credentialsProvider(awsCredentialsProvider)
      .targetThroughputInGbps(20.0)
      .minimumPartSizeInBytes(8 * MB);
    if (StringUtils.hasText(endpoint)) {
      s3CrtAsyncClientBuilder.endpointOverride(URI.create(endpoint));
    }
    return s3CrtAsyncClientBuilder.build();
  }
  @Bean
  AwsCredentialsProvider awsCredentialsProvider() {
    return () -> AwsBasicCredentials.create(accessKey, secretKey);
  }
}
```
<p>S3StorageServiceImpl:</p>
<pre class="lang-java prettyprint-override"><code>@Service
@Primary
public class S3StorageServiceImpl implements S3StorageService {

  public static final String ERROR_MSG_FORMAT = "Error performing S3 client operation";
  private static final Logger LOG = LoggerFactory.getLogger(S3StorageServiceImpl.class);
  private final S3AsyncClient s3AsyncClient;

  public S3StorageServiceImpl(S3AsyncClient s3AsyncClient) {
    this.s3AsyncClient = s3AsyncClient;
  }

  @Override
  public byte[] downloadAsByteArray(String bucketName, String keyName) {
    try (S3TransferManager transferManager = S3TransferManager.builder().s3Client(s3AsyncClient).build()) {
      DownloadRequest < ResponseBytes < GetObjectResponse >> downloadFileRequest =
        DownloadRequest.builder()
        .getObjectRequest(req -> req.bucket(bucketName).key(keyName))
        .responseTransformer(AsyncResponseTransformer.toBytes())
        .addTransferListener(LoggingTransferListener.create())
        .build();

      // Wait for the transfer to complete
      return transferManager.download(downloadFileRequest).completionFuture()
        .thenApply(CompletedDownload::result)
        .thenApply(BytesWrapper::asByteArray)
        .join();
    } catch (CompletionException e) {
      LOG.error(ERROR_MSG_FORMAT, e);
      return new byte[0];
    }
  }
}
</code>```

docker compose for localstack service:

version: '3.4'
  localstack:
    container_name: "localstack_main"
    image: localstack/localstack
    ports:
      - "4566-4599:4566-4599"
    environment:
      - SERVICES=s3
      - AWS_DEFAULT_REGION=us-east-1
    volumes:
      - ./docker/files/test.txt:/home/docker/data/test.txt
      - ./docker/files/init-s3-bucket.sh:/docker-entrypoint-initaws.d/init-s3-bucket.sh
```
<p>Above <code>/docker/files/</code> is local directory from project. And init-s3-bucket.sh contains the AWS cli code to create the test bucket and upload the test.txt file.</p>
<p>Spring Boot test :</p>
<pre class="lang-java prettyprint-override"><code>@SpringBootTest(classes = {
  S3StorageServiceImpl.class,
  S3Configuration.class
})
class S3StorageServiceImplTest {

  @Autowired
  private S3StorageService s3StorageService;

  @Test
  void downloadAsByteArray() {
    byte[] byteArray = s3StorageService.downloadAsByteArray("test", "test.txt");
    assertThat(byteArray).isNotEmpty();
  }
}
</code>```

applicaton-test.yml has aws.endpoint=http://localhost:4566 so that it can connect localstack container.

When I am running the test getting below error

```<code>java.util.concurrent.CompletionException: software.amazon.awssdk.services.s3.model.S3Exception: null (Service: S3, Status Code: 404, Request ID: 98gby23UsHdBcGi4dwT3T4BNjeMa3hyFMS0coOqQMmD1Y3TL4sVu, Extended Request ID: MzRISOwyjmnup7C0E0AFC7D5516C77/JypPGXLh0OVFGcJaaO3KW/hRAqKOpIEEp)
    at software.amazon.awssdk.utils.CompletableFutureUtils.errorAsCompletionException(CompletableFutureUtils.java:65)
    at software.amazon.awssdk.core.internal.http.pipeline.stages.AsyncExecutionFailureExceptionReportingStage.lambda$execute$0(AsyncExecutionFailureExceptionReportingStage.java:51)
    at java.base/java.util.concurrent.CompletableFuture.uniHandle(CompletableFuture.java:934)
    at java.base/java.util.concurrent.CompletableFuture$UniHandle.tryFire(CompletableFuture.java:911)
    at java.base/java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:510)
    at java.base/java.util.concurrent.CompletableFuture.completeExceptionally(CompletableFuture.java:2162)
    at software.amazon.awssdk.utils.CompletableFutureUtils.lambda$forwardExceptionTo$0(CompletableFutureUtils.java:79)
    at java.base/java.util.concurrent.CompletableFuture.uniWhenComplete(CompletableFuture.java:863)
    at java.base/java.util.concurrent.CompletableFuture$UniWhenComplete.tryFire(CompletableFuture.java:841)
    at java.base/java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:510)
    at java.base/java.util.concurrent.CompletableFuture.completeExceptionally(CompletableFuture.java:2162)
    at software.amazon.awssdk.core.internal.http.pipeline.stages.AsyncRetryableStage$RetryingExecutor.maybeAttemptExecute(AsyncRetryableStage.java:103)
    at software.amazon.awssdk.core.internal.http.pipeline.stages.AsyncRetryableStage$RetryingExecutor.maybeRetryExecute(AsyncRetryableStage.java:184)
    at software.amazon.awssdk.core.internal.http.pipeline.stages.AsyncRetryableStage$RetryingExecutor.lambda$attemptExecute$1(AsyncRetryableStage.java:170)
    at java.base/java.util.concurrent.CompletableFuture.uniWhenComplete(CompletableFuture.java:863)
    at java.base/java.util.concurrent.CompletableFuture$UniWhenComplete.tryFire(CompletableFuture.java:841)
    at java.base/java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:510)
    at java.base/java.util.concurrent.CompletableFuture.complete(CompletableFuture.java:2147)
    at software.amazon.awssdk.core.internal.http.pipeline.stages.MakeAsyncHttpRequestStage.lambda$null$0(MakeAsyncHttpRequestStage.java:105)
    at java.base/java.util.concurrent.CompletableFuture.uniWhenComplete(CompletableFuture.java:863)
    at java.base/java.util.concurrent.CompletableFuture$UniWhenComplete.tryFire(CompletableFuture.java:841)
    at java.base/java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:510)
    at java.base/java.util.concurrent.CompletableFuture.complete(CompletableFuture.java:2147)
    at software.amazon.awssdk.core.internal.http.pipeline.stages.MakeAsyncHttpRequestStage.lambda$executeHttpRequest$3(MakeAsyncHttpRequestStage.java:163)
    at java.base/java.util.concurrent.CompletableFuture.uniWhenComplete(CompletableFuture.java:863)
    at java.base/java.util.concurrent.CompletableFuture$UniWhenComplete.tryFire(CompletableFuture.java:841)
    at java.base/java.util.concurrent.CompletableFuture$Completion.run(CompletableFuture.java:482)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
    at java.base/java.lang.Thread.run(Thread.java:833)
Caused by: software.amazon.awssdk.services.s3.model.S3Exception: null (Service: S3, Status Code: 404, Request ID: 98gby23UsHdBcGi4dwT3T4BNjeMa3hyFMS0coOqQMmD1Y3TL4sVu, Extended Request ID: MzRISOwyjmnup7C0E0AFC7D5516C77/JypPGXLh0OVFGcJaaO3KW/hRAqKOpIEEp)
    at software.amazon.awssdk.services.s3.model.S3Exception$BuilderImpl.build(S3Exception.java:104)
    at software.amazon.awssdk.services.s3.model.S3Exception$BuilderImpl.build(S3Exception.java:58)
    at software.amazon.awssdk.protocols.query.internal.unmarshall.AwsXmlErrorUnmarshaller.unmarshall(AwsXmlErrorUnmarshaller.java:99)
    at software.amazon.awssdk.protocols.query.unmarshall.AwsXmlErrorProtocolUnmarshaller.handle(AwsXmlErrorProtocolUnmarshaller.java:102)
    at software.amazon.awssdk.protocols.query.unmarshall.AwsXmlErrorProtocolUnmarshaller.handle(AwsXmlErrorProtocolUnmarshaller.java:82)
    at software.amazon.awssdk.core.http.MetricCollectingHttpResponseHandler.lambda$handle$0(MetricCollectingHttpResponseHandler.java:52)
    at software.amazon.awssdk.core.internal.util.MetricUtils.measureDurationUnsafe(MetricUtils.java:63)
    at software.amazon.awssdk.core.http.MetricCollectingHttpResponseHandler.handle(MetricCollectingHttpResponseHandler.java:52)
    at software.amazon.awssdk.core.internal.http.async.AsyncResponseHandler.lambda$prepare$0(AsyncResponseHandler.java:89)
    at java.base/java.util.concurrent.CompletableFuture$UniCompose.tryFire(CompletableFuture.java:1150)
    at java.base/java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:510)
    at java.base/java.util.concurrent.CompletableFuture.complete(CompletableFuture.java:2147)
    at software.amazon.awssdk.core.internal.http.async.AsyncResponseHandler$BaosSubscriber.onComplete(AsyncResponseHandler.java:132)
    at software.amazon.awssdk.utils.async.SimplePublisher.doProcessQueue(SimplePublisher.java:275)
    at software.amazon.awssdk.utils.async.SimplePublisher.processEventQueue(SimplePublisher.java:224)
    at software.amazon.awssdk.utils.async.SimplePublisher.complete(SimplePublisher.java:157)
    at java.base/java.util.concurrent.CompletableFuture.uniRunNow(CompletableFuture.java:819)
    at java.base/java.util.concurrent.CompletableFuture.uniRunStage(CompletableFuture.java:803)
    at java.base/java.util.concurrent.CompletableFuture.thenRun(CompletableFuture.java:2195)
    at software.amazon.awssdk.services.s3.internal.crt.S3CrtResponseHandlerAdapter.onErrorResponseComplete(S3CrtResponseHandlerAdapter.java:135)
    at software.amazon.awssdk.services.s3.internal.crt.S3CrtResponseHandlerAdapter.handleError(S3CrtResponseHandlerAdapter.java:124)
    at software.amazon.awssdk.services.s3.internal.crt.S3CrtResponseHandlerAdapter.onFinished(S3CrtResponseHandlerAdapter.java:93)
    at software.amazon.awssdk.crt.s3.S3MetaRequestResponseHandlerNativeAdapter.onFinished(S3MetaRequestResponseHandlerNativeAdapter.java:24)

java.lang.AssertionError:
Expecting actual not to be empty
</code>```

I have created repo with miniman reproducible example. Please find it here

Body:
I am using the S3TransferManager with S3AsyncClient in my service code. I am testing this code with localstack docker S3 service. I have the local stack S3 service and created the bucket test and uploaded one file test.txt on docker service startup.

S3Config.java

@Configuration
public class S3Configuration {
  @Value("${aws.access-key}")
  private String accessKey;
  @Value("${aws.secret-key}")
  private String secretKey;
  @Value("${aws.region}")
  private String region;
  @Value("${aws.endpoint:#{null}}")
  private String endpoint;

  @Bean
  public S3AsyncClient s3AsyncClient(AwsCredentialsProvider awsCredentialsProvider) {
    S3CrtAsyncClientBuilder s3CrtAsyncClientBuilder = S3AsyncClient.crtBuilder()
      .region(Region.of(region))
      .credentialsProvider(awsCredentialsProvider)
      .targetThroughputInGbps(20.0)
      .minimumPartSizeInBytes(8 * MB);
    if (StringUtils.hasText(endpoint)) {
      s3CrtAsyncClientBuilder.endpointOverride(URI.create(endpoint));
    }
    return s3CrtAsyncClientBuilder.build();
  }
  @Bean
  AwsCredentialsProvider awsCredentialsProvider() {
    return () -> AwsBasicCredentials.create(accessKey, secretKey);
  }
}

S3StorageServiceImpl:

@Service
@Primary
public class S3StorageServiceImpl implements S3StorageService {

  public static final String ERROR_MSG_FORMAT = "Error performing S3 client operation";
  private static final Logger LOG = LoggerFactory.getLogger(S3StorageServiceImpl.class);
  private final S3AsyncClient s3AsyncClient;

  public S3StorageServiceImpl(S3AsyncClient s3AsyncClient) {
    this.s3AsyncClient = s3AsyncClient;
  }

  @Override
  public byte[] downloadAsByteArray(String bucketName, String keyName) {
    try (S3TransferManager transferManager = S3TransferManager.builder().s3Client(s3AsyncClient).build()) {
      DownloadRequest < ResponseBytes < GetObjectResponse >> downloadFileRequest =
        DownloadRequest.builder()
        .getObjectRequest(req -> req.bucket(bucketName).key(keyName))
        .responseTransformer(AsyncResponseTransformer.toBytes())
        .addTransferListener(LoggingTransferListener.create())
        .build();

      // Wait for the transfer to complete
      return transferManager.download(downloadFileRequest).completionFuture()
        .thenApply(CompletedDownload::result)
        .thenApply(BytesWrapper::asByteArray)
        .join();
    } catch (CompletionException e) {
      LOG.error(ERROR_MSG_FORMAT, e);
      return new byte[0];
    }
  }
}

docker compose for localstack service:

version: '3.4'
  localstack:
    container_name: "localstack_main"
    image: localstack/localstack
    ports:
      - "4566-4599:4566-4599"
    environment:
      - SERVICES=s3
      - AWS_DEFAULT_REGION=us-east-1
    volumes:
      - ./docker/files/test.txt:/home/docker/data/test.txt
      - ./docker/files/init-s3-bucket.sh:/docker-entrypoint-initaws.d/init-s3-bucket.sh

Above /docker/files/ is local directory from project. And init-s3-bucket.sh contains the AWS cli code to create the test bucket and upload the test.txt file.

Spring Boot test :

@SpringBootTest(classes = {
  S3StorageServiceImpl.class,
  S3Configuration.class
})
class S3StorageServiceImplTest {

  @Autowired
  private S3StorageService s3StorageService;

  @Test
  void downloadAsByteArray() {
    byte[] byteArray = s3StorageService.downloadAsByteArray("test", "test.txt");
    assertThat(byteArray).isNotEmpty();
  }
}

applicaton-test.yml has aws.endpoint=http://localhost:4566 so that it can connect localstack container.

When I am running the test getting below error

java.util.concurrent.CompletionException: software.amazon.awssdk.services.s3.model.S3Exception: null (Service: S3, Status Code: 404, Request ID: 98gby23UsHdBcGi4dwT3T4BNjeMa3hyFMS0coOqQMmD1Y3TL4sVu, Extended Request ID: MzRISOwyjmnup7C0E0AFC7D5516C77/JypPGXLh0OVFGcJaaO3KW/hRAqKOpIEEp)
    at software.amazon.awssdk.utils.CompletableFutureUtils.errorAsCompletionException(CompletableFutureUtils.java:65)
    at software.amazon.awssdk.core.internal.http.pipeline.stages.AsyncExecutionFailureExceptionReportingStage.lambda$execute$0(AsyncExecutionFailureExceptionReportingStage.java:51)
    at java.base/java.util.concurrent.CompletableFuture.uniHandle(CompletableFuture.java:934)
    at java.base/java.util.concurrent.CompletableFuture$UniHandle.tryFire(CompletableFuture.java:911)
    at java.base/java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:510)
    at java.base/java.util.concurrent.CompletableFuture.completeExceptionally(CompletableFuture.java:2162)
    at software.amazon.awssdk.utils.CompletableFutureUtils.lambda$forwardExceptionTo$0(CompletableFutureUtils.java:79)
    at java.base/java.util.concurrent.CompletableFuture.uniWhenComplete(CompletableFuture.java:863)
    at java.base/java.util.concurrent.CompletableFuture$UniWhenComplete.tryFire(CompletableFuture.java:841)
    at java.base/java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:510)
    at java.base/java.util.concurrent.CompletableFuture.completeExceptionally(CompletableFuture.java:2162)
    at software.amazon.awssdk.core.internal.http.pipeline.stages.AsyncRetryableStage$RetryingExecutor.maybeAttemptExecute(AsyncRetryableStage.java:103)
    at software.amazon.awssdk.core.internal.http.pipeline.stages.AsyncRetryableStage$RetryingExecutor.maybeRetryExecute(AsyncRetryableStage.java:184)
    at software.amazon.awssdk.core.internal.http.pipeline.stages.AsyncRetryableStage$RetryingExecutor.lambda$attemptExecute$1(AsyncRetryableStage.java:170)
    at java.base/java.util.concurrent.CompletableFuture.uniWhenComplete(CompletableFuture.java:863)
    at java.base/java.util.concurrent.CompletableFuture$UniWhenComplete.tryFire(CompletableFuture.java:841)
    at java.base/java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:510)
    at java.base/java.util.concurrent.CompletableFuture.complete(CompletableFuture.java:2147)
    at software.amazon.awssdk.core.internal.http.pipeline.stages.MakeAsyncHttpRequestStage.lambda$null$0(MakeAsyncHttpRequestStage.java:105)
    at java.base/java.util.concurrent.CompletableFuture.uniWhenComplete(CompletableFuture.java:863)
    at java.base/java.util.concurrent.CompletableFuture$UniWhenComplete.tryFire(CompletableFuture.java:841)
    at java.base/java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:510)
    at java.base/java.util.concurrent.CompletableFuture.complete(CompletableFuture.java:2147)
    at software.amazon.awssdk.core.internal.http.pipeline.stages.MakeAsyncHttpRequestStage.lambda$executeHttpRequest$3(MakeAsyncHttpRequestStage.java:163)
    at java.base/java.util.concurrent.CompletableFuture.uniWhenComplete(CompletableFuture.java:863)
    at java.base/java.util.concurrent.CompletableFuture$UniWhenComplete.tryFire(CompletableFuture.java:841)
    at java.base/java.util.concurrent.CompletableFuture$Completion.run(CompletableFuture.java:482)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
    at java.base/java.lang.Thread.run(Thread.java:833)
Caused by: software.amazon.awssdk.services.s3.model.S3Exception: null (Service: S3, Status Code: 404, Request ID: 98gby23UsHdBcGi4dwT3T4BNjeMa3hyFMS0coOqQMmD1Y3TL4sVu, Extended Request ID: MzRISOwyjmnup7C0E0AFC7D5516C77/JypPGXLh0OVFGcJaaO3KW/hRAqKOpIEEp)
    at software.amazon.awssdk.services.s3.model.S3Exception$BuilderImpl.build(S3Exception.java:104)
    at software.amazon.awssdk.services.s3.model.S3Exception$BuilderImpl.build(S3Exception.java:58)
    at software.amazon.awssdk.protocols.query.internal.unmarshall.AwsXmlErrorUnmarshaller.unmarshall(AwsXmlErrorUnmarshaller.java:99)
    at software.amazon.awssdk.protocols.query.unmarshall.AwsXmlErrorProtocolUnmarshaller.handle(AwsXmlErrorProtocolUnmarshaller.java:102)
    at software.amazon.awssdk.protocols.query.unmarshall.AwsXmlErrorProtocolUnmarshaller.handle(AwsXmlErrorProtocolUnmarshaller.java:82)
    at software.amazon.awssdk.core.http.MetricCollectingHttpResponseHandler.lambda$handle$0(MetricCollectingHttpResponseHandler.java:52)
    at software.amazon.awssdk.core.internal.util.MetricUtils.measureDurationUnsafe(MetricUtils.java:63)
    at software.amazon.awssdk.core.http.MetricCollectingHttpResponseHandler.handle(MetricCollectingHttpResponseHandler.java:52)
    at software.amazon.awssdk.core.internal.http.async.AsyncResponseHandler.lambda$prepare$0(AsyncResponseHandler.java:89)
    at java.base/java.util.concurrent.CompletableFuture$UniCompose.tryFire(CompletableFuture.java:1150)
    at java.base/java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:510)
    at java.base/java.util.concurrent.CompletableFuture.complete(CompletableFuture.java:2147)
    at software.amazon.awssdk.core.internal.http.async.AsyncResponseHandler$BaosSubscriber.onComplete(AsyncResponseHandler.java:132)
    at software.amazon.awssdk.utils.async.SimplePublisher.doProcessQueue(SimplePublisher.java:275)
    at software.amazon.awssdk.utils.async.SimplePublisher.processEventQueue(SimplePublisher.java:224)
    at software.amazon.awssdk.utils.async.SimplePublisher.complete(SimplePublisher.java:157)
    at java.base/java.util.concurrent.CompletableFuture.uniRunNow(CompletableFuture.java:819)
    at java.base/java.util.concurrent.CompletableFuture.uniRunStage(CompletableFuture.java:803)
    at java.base/java.util.concurrent.CompletableFuture.thenRun(CompletableFuture.java:2195)
    at software.amazon.awssdk.services.s3.internal.crt.S3CrtResponseHandlerAdapter.onErrorResponseComplete(S3CrtResponseHandlerAdapter.java:135)
    at software.amazon.awssdk.services.s3.internal.crt.S3CrtResponseHandlerAdapter.handleError(S3CrtResponseHandlerAdapter.java:124)
    at software.amazon.awssdk.services.s3.internal.crt.S3CrtResponseHandlerAdapter.onFinished(S3CrtResponseHandlerAdapter.java:93)
    at software.amazon.awssdk.crt.s3.S3MetaRequestResponseHandlerNativeAdapter.onFinished(S3MetaRequestResponseHandlerNativeAdapter.java:24)

java.lang.AssertionError:
Expecting actual not to be empty

I have created repo with miniman reproducible example. Please find it here


问:
Pywebview & pyinstaller: How to set inbuilt-http server root as current folder as exe
I am trying to use pywebview to display html file using inbuilt http server. This ways I can load xlsx file over http fetch() witth Javascript.

Everything works until I pack this into single exe using pyinstaller. It says "Path /index.html not found".

I use this command to build exe: pyinstaller.exe --onefile --noconsole --icon=favicon.ico .\httpd.py

I want to keep index.html and excel file in the same directory as .exe file. (I don't want to pack it to exec, so that excel file can be updated). There is not option set http server root folder as current directory as exe.

Here is httpd.py

```
import webview
import os
cwd = os.getcwd()

def get_current_url(window):
    window.load_url(window.get_current_url()+'/index.html')
    print(window.get_current_url())

if __name__ == '__main__':
    window = webview.create_window('Application Chart v1', 'index.html', min_size= (1000,800), width=1280, height=1024)
    webview.start(get_current_url, window, http_server=True, debug=True)
```

Please help!

Body:
I am trying to use pywebview to display html file using inbuilt http server. This ways I can load xlsx file over http fetch() witth Javascript.

Everything works until I pack this into single exe using pyinstaller. It says "Path /index.html not found".

I use this command to build exe: pyinstaller.exe --onefile --noconsole --icon=favicon.ico .\httpd.py

I want to keep index.html and excel file in the same directory as .exe file. (I don't want to pack it to exec, so that excel file can be updated). There is not option set http server root folder as current directory as exe.

Here is httpd.py

import webview
import os
cwd = os.getcwd()

def get_current_url(window):
    window.load_url(window.get_current_url()+'/index.html')
    print(window.get_current_url())

if __name__ == '__main__':
    window = webview.create_window('Application Chart v1', 'index.html', min_size= (1000,800), width=1280, height=1024)
    webview.start(get_current_url, window, http_server=True, debug=True)

Please help!