问:
Multipart request rejected because no bounday were found while boundary is already sent
I went through the other similar questions but couldn't find any solution. We have a backend service running by Spring Boot and has been working for a while now. But there is a new user of this service recently and they are using MuleSoft to send their request. But all attempts to send a file to our service fails with this error:

```<code>Failed to parse multipart servlet request; nested exception is java.io.IOException: org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found"
</code>```

The only difference we could find between a request from MuleSoft and say a curl command is that MuleSoft always sends the request with boundary value wrapped with double quotes

Mule request:

```<code><Header name="Content-Type">multipart/form-data; charset=UTF-8; boundary="--------------------------669816398596264398718285"</Header>
</code>```

Versus Postman/curl request:

```<code>*  SSL certificate verify ok.
* Using HTTP2, server supports multiplexing
* Connection state changed (HTTP/2 confirmed)
* Copying HTTP/2 data in stream buffer to connection buffer after upgrade: len=0
* Using Stream ID: 1 (easy handle 0x7fd656810a00)
> POST /api/upload HTTP/2
> Host: myhost
> user-agent: curl/7.79.1
> accept: */*
> content-length: 97255
> content-type: multipart/form-data; boundary=------------------------111fd08cb4fafe1c
>
* Connection state changed (MAX_CONCURRENT_STREAMS == 128)!
* We are completely uploaded and fine
< HTTP/2 200
< date: Mon, 19 Dec 2022 04:56:25 GMT
< content-length: 0
</code>```

Our controller in Spring is very simple:

```<code>@RestController
class MyController {

    @PostMapping("/upload", consumes = [MediaType.MULTIPART_FORM_DATA_VALUE])
    @ResponseStatus(HttpStatus.OK)
    fun uploadDocument(@RequestPart("file") file: MultipartFile) {
        logger.info { "ContentType: ${file.contentType}" }
        logger.info { "Name: ${file.name}" }
        logger.info { "Byte: ${String(file.bytes)}" }
    }
}
</code>```

The following curl command works fine:

```<code>curl -v -X POST -F file=@/Users/myhomefolder/Documents/some-file.jpg https://host-name/api/upload
</code>```

But this script from MuleSoft doesn't (Sorry I'm not familiar with Mule, I got this code from their team):

```<code>import dw::module::Multipart
output multipart/form-data boundary = "---WebKitFormBoundary7MA4YWxkTrZu0gW"
---
{
               parts : {
                    file : {
                        headers : {
                            "Content-Disposition" : {
                                "name": "file",
                                "filename": payload.name
                             },
                            "Content-Type" : "multipart/form-data"
                        },
                        content : payload.byteArray
                    }
               }

}
</code>```

Is there any configuration in Spring that accepts double quotes for boundary? Is there anything missing in our backend configuration that should be added to support different HTTP client?

Body:
I went through the other similar questions but couldn't find any solution. We have a backend service running by Spring Boot and has been working for a while now. But there is a new user of this service recently and they are using MuleSoft to send their request. But all attempts to send a file to our service fails with this error:

Failed to parse multipart servlet request; nested exception is java.io.IOException: org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found"

The only difference we could find between a request from MuleSoft and say a curl command is that MuleSoft always sends the request with boundary value wrapped with double quotes

Mule request:

multipart/form-data; charset=UTF-8; boundary="--------------------------669816398596264398718285"

Versus Postman/curl request:

*  SSL certificate verify ok.
* Using HTTP2, server supports multiplexing
* Connection state changed (HTTP/2 confirmed)
* Copying HTTP/2 data in stream buffer to connection buffer after upgrade: len=0
* Using Stream ID: 1 (easy handle 0x7fd656810a00)
> POST /api/upload HTTP/2
> Host: myhost
> user-agent: curl/7.79.1
> accept: */*
> content-length: 97255
> content-type: multipart/form-data; boundary=------------------------111fd08cb4fafe1c
>
* Connection state changed (MAX_CONCURRENT_STREAMS == 128)!
* We are completely uploaded and fine
< HTTP/2 200
< date: Mon, 19 Dec 2022 04:56:25 GMT
< content-length: 0

Our controller in Spring is very simple:

@RestController
class MyController {

    @PostMapping("/upload", consumes = [MediaType.MULTIPART_FORM_DATA_VALUE])
    @ResponseStatus(HttpStatus.OK)
    fun uploadDocument(@RequestPart("file") file: MultipartFile) {
        logger.info { "ContentType: ${file.contentType}" }
        logger.info { "Name: ${file.name}" }
        logger.info { "Byte: ${String(file.bytes)}" }
    }
}

The following curl command works fine:

curl -v -X POST -F file=@/Users/myhomefolder/Documents/some-file.jpg https://host-name/api/upload

But this script from MuleSoft doesn't (Sorry I'm not familiar with Mule, I got this code from their team):

import dw::module::Multipart
output multipart/form-data boundary = "---WebKitFormBoundary7MA4YWxkTrZu0gW"
---
{
               parts : {
                    file : {
                        headers : {
                            "Content-Disposition" : {
                                "name": "file",
                                "filename": payload.name
                             },
                            "Content-Type" : "multipart/form-data"
                        },
                        content : payload.byteArray
                    }
               }

}

Is there any configuration in Spring that accepts double quotes for boundary? Is there anything missing in our backend configuration that should be added to support different HTTP client?


来源: stackexchange

问:
AWS CloudTrail event referenced resources parsing
In CloudTrail, the referenced resources section behaves in unexpected ways. For example, in the CreateUser event, there are 3 referenced resources, but they all actually point to the same user. This makes it difficult to parse programatically. On the other hand, what if there is another event type with 2 or more referenced resource of the same type, but they actually point to two different resources? How can one programatically parse the referenced resources in cloudtrail events in a correct and consistent way?

ContentLicense: CC BY-SA 4.0


问:
Filtering on index in dask dataframe is not any faster than filtering on any other column
I'm loading a dask dataframe from a parquet collection of around 1300 parquet files, total of 250 milions entries. Dataset is a time series and has a datetime index.

In general I'm pretty happy with performance of queries considering the size of the dataset (6-7 min approx).

One thing I don't understand is why index filtering is no faster than any other column filtering.

What I mean is that if I take a slice of the ddf on timestamp (index) or if I take a slice based on any other field, the time it takes to compute the dataframe is basically identical.

Am I doing something wrong? I would have imagined filter on index would be much faster

Tried to reindex a second time but didn't help.

I've checked suggestions on this post: https://www.coiled.io/blog/dask-set-index-dataframe

import dask.dataframe as dd

dask.config.set(scheduler=dask.multiprocessing.get)
ddf = dd.read_parquet(data_lake + asset_class, engine='pyarrow',columns=['Close','Open','Symbol', 'TradeHigh', 'TradeLow', 'CloseCumulativeVolume', 'CloseDate', 'CloseCumulativeValue', 'TradeCount'])

q1_21 = ddf['2021-01-01':'2021-04-01'].compute()
#Wall time: 2min 59s

df = ddf.loc[ddf['Symbol'].str.contains('MSFT|TSLA')].compute()
#Wall time: 3min 2s
```


问:
Read/Write C# array from C++ application
Previously I had a c++ console application and I rewrote everything to C# WPF application so I have now UI, but I cant figure out how to get a correct offset (pointer) to change or read a value via C++ application.

In c++ it was so easy to get address

```<code>uint32_t check = 0xABCD;
uint64_t add[1];
add[0] = (uintptr_t)✓
printf("address: 0x%I64x\n", (uint64_t)&add[0] - (uint64_t)GetModuleHandle(NULL));
</code>```

and then from another program I was able to read/write add.
Tried with garbage collector, but everytime address changes + wrong address. Also NativeMemory was not working because I can not use unsafe code.

```<code>public static IntPtr[] add = new IntPtr[1];
protected static int check = 0xABCD;

public static void SomeFunction()
{
GCHandle check_handle = GCHandle.Alloc(check, GCHandleType.Pinned);
IntPtr check_ptr = check_handle.AddrOfPinnedObject();
add[0] = check_ptr;
Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate
 {
 if (long.TryParse(add[0].ToString(), out long add0))
 {
    long offset_addr = (long)add[0] - (long)GetModuleHandle(null);
    a.add_offset_textbox.Text = "0x" + offset_addr.ToString("X");
 }
 }));
}
</code>```

Body:
Previously I had a c++ console application and I rewrote everything to C# WPF application so I have now UI, but I cant figure out how to get a correct offset (pointer) to change or read a value via C++ application.

In c++ it was so easy to get address

uint32_t check = 0xABCD;
uint64_t add[1];
add[0] = (uintptr_t)✓
printf("address: 0x%I64x\n", (uint64_t)&add[0] - (uint64_t)GetModuleHandle(NULL));

and then from another program I was able to read/write add.
Tried with garbage collector, but everytime address changes + wrong address. Also NativeMemory was not working because I can not use unsafe code.

public static IntPtr[] add = new IntPtr[1];
protected static int check = 0xABCD;

public static void SomeFunction()
{
GCHandle check_handle = GCHandle.Alloc(check, GCHandleType.Pinned);
IntPtr check_ptr = check_handle.AddrOfPinnedObject();
add[0] = check_ptr;
Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate
 {
 if (long.TryParse(add[0].ToString(), out long add0))
 {
    long offset_addr = (long)add[0] - (long)GetModuleHandle(null);
    a.add_offset_textbox.Text = "0x" + offset_addr.ToString("X");
 }
 }));
}


问:
Hide Month name and Day number in AMCHARTS5
I am getting the list of timestamps from the backend. My task is to map the datapoints to one day. I have written the logic to do that and it is displaying accurately. But, as I have discarded the day, month and year from the timestamp but the problem is that it is now mapping the data to 1st january and 2nd january. It is okay but I want to show only one day not the 1st Jan and 2nd Jan on the Map.

In the documentation I found that we change the date format on the graph like this:

series.data.processor = am5.DataProcessor.new(root, {
  dateFormat:'HH:mm'
  dateFields: ['date'],
});
```
<p>It is displaying the hour and minute but it is also displaying the 1st Jan and 2nd Jan and we could also scroll to the other dates.</p>
<p>I want to disable the scrolling and hide the 1st Jan and 2nd Jan displayed at both end.</p>
<p><img src="https://i.stack.imgur.com/LEubt.png" alt="Chart displaying the weekly datapoints" /></p>
<p>I have tried changing the format as per the documentation:</p>
<pre class="lang-js prettyprint-override"><code>series.data.processor = am5.DataProcessor.new(root, {
  dateFormat:'HH:mm'
  dateFields: ['date'],
});
</code>```

But, could not found anything to disable the horizontal scroll or hide the 1st Jan and 2nd Jan.

Body:
I am getting the list of timestamps from the backend. My task is to map the datapoints to one day. I have written the logic to do that and it is displaying accurately. But, as I have discarded the day, month and year from the timestamp but the problem is that it is now mapping the data to 1st january and 2nd january. It is okay but I want to show only one day not the 1st Jan and 2nd Jan on the Map.

In the documentation I found that we change the date format on the graph like this:

series.data.processor = am5.DataProcessor.new(root, {
  dateFormat:'HH:mm'
  dateFields: ['date'],
});

It is displaying the hour and minute but it is also displaying the 1st Jan and 2nd Jan and we could also scroll to the other dates.

I want to disable the scrolling and hide the 1st Jan and 2nd Jan displayed at both end.

I have tried changing the format as per the documentation:

series.data.processor = am5.DataProcessor.new(root, {
  dateFormat:'HH:mm'
  dateFields: ['date'],
});

But, could not found anything to disable the horizontal scroll or hide the 1st Jan and 2nd Jan.


问:
How to configure the session to stop executing all following commands on first error?
Suppose I have a script:

```<code>alter table ....
go

insert into ...
go

alter table ...
go

delete from ..
go
</code>```

How do I configure this session at the beginning of this script, so that if any of the four commands raises any error, all following commands in the script are skipped?

I don't want to do anything to these commands themselves, such as adding "raiseerror" and try/catch etc. All I want to do is to add something at the beginning of the script, so that the "abort on error" will happen automatically.

Body:
Suppose I have a script:

alter table ....
go

insert into ...
go

alter table ...
go

delete from ..
go

How do I configure this session at the beginning of this script, so that if any of the four commands raises any error, all following commands in the script are skipped?

I don't want to do anything to these commands themselves, such as adding "raiseerror" and try/catch etc. All I want to do is to add something at the beginning of the script, so that the "abort on error" will happen automatically.


问:
How to reduce the memory consumption of CUDA init in PyTorch?
I am using PyTorch on NVIDIA Jetson TX2 (GPU and CPU have shared memory), and have only about 2 Gb of free memory.

Specifications:

PyTorch v1.10.0

JetPack 4.6.1

CUDA 10.2

Whenever I try to use GPU, "torch.cuda.init()" would consume about 2Gb of memory.
If I use only the CPU, the memory overhead would be only 180 Mb of memory.

I have been searching the net and found that the reason is a load of kernels.
I understand that a lot of kernels are used for optimal computing, however, I can not even use my GPU due to it.
Also, I think that the overwhelming majority of kernels would be never used by me.

Could you please say how to reduce the memory overhead if I am willing to sacrifice the performance as long as I could use GPU?

Would it be possible to reduce it to the CUDA bare minimum? If it is possible, how to accomplish it?

I am trying to train the relatively small model with Conv2D, Pooling, and Dense layers.

At least how to reduce the memory overhead, so I could train simple models with only Dense layers?

I also can not switch to other libraries due to other reasons.


问:
Install windows feacture asp-net-45 failed in docker build windows server 2019 docker image
Running environment of docker: windows server 2019 standard installed by command below

```<code>Install-Module -Name DockerMsftProvider -Repository PSGallery -Force
Install-Package Docker -ProviderName DockerMsftProvider -Force

</code>```

While building docker image of windows server 2019 with docker file below:

```<code>FROM mcr.microsoft.com/windows/servercore/iis:windowsservercore-ltsc2019
WORKDIR /ViniBeer
COPY . .
RUN PowerShell Install-WindowsFeature NET-Framework-45-ASPNET; Install-WindowsFeature Web-Asp-Net45; \
 Import-Module WebAdministration; \
 New-WebApplication "ViniBeer" -Site 'Default Web Site' -ApplicationPool "DefaultAppPool" -PhysicalPath "C:\ViniBeer"

</code>```

exception thrown in console as below:

```<code>add-windowsfeature : The request to add or remove features on the specified
server failed.
Installation of one or more roles, role services, or features failed. Error:
0x800f0922
At line:1 char:1
+ add-windowsfeature web-asp-net45
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (@{Vhd=; Credent...Name=localh
   ost}:PSObject) [Install-WindowsFeature], Exception
    + FullyQualifiedErrorId : DISMAPI_Error__Failed_To_Enable_Updates,Microsof
   t.Windows.ServerManager.Commands.AddWindowsFeatureCommand
</code>```

Running the same feature installation command in host is worked.

Trying different command like

```<code>add-windowsfeature web-asp-net45
</code>```

is still not working.

Is there any command or opeartion to install this feature without exception or way to build the image successfully?

Body:
Running environment of docker: windows server 2019 standard installed by command below

Install-Module -Name DockerMsftProvider -Repository PSGallery -Force
Install-Package Docker -ProviderName DockerMsftProvider -Force

While building docker image of windows server 2019 with docker file below:

FROM mcr.microsoft.com/windows/servercore/iis:windowsservercore-ltsc2019
WORKDIR /ViniBeer
COPY . .
RUN PowerShell Install-WindowsFeature NET-Framework-45-ASPNET; Install-WindowsFeature Web-Asp-Net45; \
 Import-Module WebAdministration; \
 New-WebApplication "ViniBeer" -Site 'Default Web Site' -ApplicationPool "DefaultAppPool" -PhysicalPath "C:\ViniBeer"

exception thrown in console as below:

add-windowsfeature : The request to add or remove features on the specified
server failed.
Installation of one or more roles, role services, or features failed. Error:
0x800f0922
At line:1 char:1
+ add-windowsfeature web-asp-net45
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (@{Vhd=; Credent...Name=localh
   ost}:PSObject) [Install-WindowsFeature], Exception
    + FullyQualifiedErrorId : DISMAPI_Error__Failed_To_Enable_Updates,Microsof
   t.Windows.ServerManager.Commands.AddWindowsFeatureCommand

Running the same feature installation command in host is worked.

Trying different command like

add-windowsfeature web-asp-net45

is still not working.

Is there any command or opeartion to install this feature without exception or way to build the image successfully?


问:
How to add external styles to Bit dev application or components
Within bit.dev, how can we import external stylesheets into bit.dev as we have an external styleguide we would like to import into our components within bit.dev. We are only using lit-elements within our application so theme providers are not an option. (Well, still cannot use external stylesheets).

I was hoping we could just import an external link within the .mdx files so we can preview components with the external styles applied. But to no luck. Any ideas or direction anyone can point us in?


问:
How can I create an image on my HTML canvas when I press the space bar in JQuery?
I want to create an image when the space bar is pressed to simulate a bullet firing. The issue is that when I call a draw image function inside JQuery after declaring the image and it's path outside the function, the image doesn't appear on the screen at all. How can I make it so that the bullet is created when the space bar is pressed and continues until it gets off the screen?</p>
```<code>var bullet = new Image();
bullet.src = "Resources/bullet.png"

$(document).keydown(function(event) {  //jQuery code to recognize a keydown event
    var keycode = (event.keyCode ? event.keyCode : event.which);

    if (keycode === 32) {
        //gun facing left
        if (facingleft === true) {

^^^ Don't know how to draw the image when the key is pressed ^^^

            collideFunction()
        }
    }

});
</code>```

Body:
I want to create an image when the space bar is pressed to simulate a bullet firing. The issue is that when I call a draw image function inside JQuery after declaring the image and it's path outside the function, the image doesn't appear on the screen at all. How can I make it so that the bullet is created when the space bar is pressed and continues until it gets off the screen?

var bullet = new Image();
bullet.src = "Resources/bullet.png"

$(document).keydown(function(event) {  //jQuery code to recognize a keydown event
    var keycode = (event.keyCode ? event.keyCode : event.which);

    if (keycode === 32) {
        //gun facing left
        if (facingleft === true) {

^^^ Don't know how to draw the image when the key is pressed ^^^

            collideFunction()
        }
    }

});


问:
How can I Deploy a Django App as a .war file or in any other packaged way?
I have a Django Project for which I am trying to find a way to deploy as a .war file.

My objective is

to not reveal the source code during deployment

to De-Couple Django App from Database and deploy as a .war file. This will help me to update the app without re-initializing database.

As Jython is not supported for Python3, is there an alternative?
I also tried to create an exe through PyIntsaller but it acts as a malicious executable.


问:
React - Redux How to filter the global state when redirecting to other component
I have a React app in which a global state is setted by using redux, in one component a Form is filled and based on the inputs I do an axios request to the same endpoint from where redux fetch the data then I want to redirect to another component and filter the state based on this new request. The problem is that when I am redirected the same state that redux defined is shown and no the updated one.

My redux logic is this:

actionsCreator productActions.js

```<code>import { fetchProductsStart, fetchProductsSuccess, fetchProductsFailure } from '../slices/productsSlice';
import { baseUrl } from '../../shared/baseUrl';

export const fetchProducts = () => async dispatch => {
  try {
    dispatch(fetchProductsStart());
    const response = await fetch(baseUrl+"products");
    const data = await response.json();
    dispatch(fetchProductsSuccess(data));
  } catch (error) {
    dispatch(fetchProductsFailure(error));
  }
};
</code>```

the slice reducer is productsSlice.js

```<code>import { createSlice } from "@reduxjs/toolkit";

const productsSlice = createSlice({
  name: "products",
  initialState: {
    products: [],
    loading: false,
    error: null
  },
  reducers: {
    fetchProductsStart(state) {
      state.loading = true;
      state.error = null;
    },
    fetchProductsSuccess(state, action) {
      state.products = action.payload;
      state.loading = false;
    },
    fetchProductsFailure(state, action) {
      state.error = action.payload;
      state.loading = false;
    }
  }
});

export const { fetchProductsStart, fetchProductsSuccess, fetchProductsFailure } = productsSlice.actions;

export default productsSlice.reducer;

</code>```

and my store configureStore.js

```<code>import { configureStore } from "@reduxjs/toolkit"
import productsReducer from "./slices/productsSlice"
export const store = configureStore({
  reducer: {
    products: productsReducer
  }
})
</code>```

the logic in the form that I mentioned above in the handleSubmit is:

```<code>    handleSubmit(event){
        event.preventDefault()

        // redirect to the store component with the search criteria
        // the search criteria will be passed as query parameters
        var tipo  = this.state.tipo
        var marca = toTitleCase(this.state.marca)
        var linea = this.state.linea
        axios.get(baseUrl+'products' + '/?tipo=' + tipo + '&marca=' + marca + '&linea=' + linea )
        .then((response) => {
            console.log('response.data',response.data)

            // here I am using the useNavigate hook to redirect and set the state
            // with the response that is returned with the axios request
            this.props.navigate("/store",{
                state:{
                    products:response.data
                }
            });

        })
        .catch((error) => {
            console.log(error)
        })

    }
</code>```

How could I correctly update my state in order to filter this based on the inputs gotten from the form inputs? Is there a better way to do this I am kinda newbie with redux I can´t figure how to update the state.

EDIT: I forgot to mention that the component from where I am redirecting is a class component and I can´t change it to functional one

EDIT2: I just could change the logic so now the component from where I am redirecting is a functional Component

Body:
I have a React app in which a global state is setted by using redux, in one component a Form is filled and based on the inputs I do an axios request to the same endpoint from where redux fetch the data then I want to redirect to another component and filter the state based on this new request. The problem is that when I am redirected the same state that redux defined is shown and no the updated one.

My redux logic is this:

actionsCreator productActions.js

import { fetchProductsStart, fetchProductsSuccess, fetchProductsFailure } from '../slices/productsSlice';
import { baseUrl } from '../../shared/baseUrl';

export const fetchProducts = () => async dispatch => {
  try {
    dispatch(fetchProductsStart());
    const response = await fetch(baseUrl+"products");
    const data = await response.json();
    dispatch(fetchProductsSuccess(data));
  } catch (error) {
    dispatch(fetchProductsFailure(error));
  }
};

the slice reducer is productsSlice.js

import { createSlice } from "@reduxjs/toolkit";

const productsSlice = createSlice({
  name: "products",
  initialState: {
    products: [],
    loading: false,
    error: null
  },
  reducers: {
    fetchProductsStart(state) {
      state.loading = true;
      state.error = null;
    },
    fetchProductsSuccess(state, action) {
      state.products = action.payload;
      state.loading = false;
    },
    fetchProductsFailure(state, action) {
      state.error = action.payload;
      state.loading = false;
    }
  }
});

export const { fetchProductsStart, fetchProductsSuccess, fetchProductsFailure } = productsSlice.actions;

export default productsSlice.reducer;

and my store configureStore.js

import { configureStore } from "@reduxjs/toolkit"
import productsReducer from "./slices/productsSlice"
export const store = configureStore({
  reducer: {
    products: productsReducer
  }
})

the logic in the form that I mentioned above in the handleSubmit is:

    handleSubmit(event){
        event.preventDefault()

        // redirect to the store component with the search criteria
        // the search criteria will be passed as query parameters
        var tipo  = this.state.tipo
        var marca = toTitleCase(this.state.marca)
        var linea = this.state.linea
        axios.get(baseUrl+'products' + '/?tipo=' + tipo + '&marca=' + marca + '&linea=' + linea )
        .then((response) => {
            console.log('response.data',response.data)

            // here I am using the useNavigate hook to redirect and set the state
            // with the response that is returned with the axios request
            this.props.navigate("/store",{
                state:{
                    products:response.data
                }
            });

        })
        .catch((error) => {
            console.log(error)
        })

    }

How could I correctly update my state in order to filter this based on the inputs gotten from the form inputs? Is there a better way to do this I am kinda newbie with redux I can´t figure how to update the state.

EDIT: I forgot to mention that the component from where I am redirecting is a class component and I can´t change it to functional one

EDIT2: I just could change the logic so now the component from where I am redirecting is a functional Component


问:
ClickOnce and .NET 7: User settings not being updated
I've updated my vb Windows Forms Application from .net 4.7.2 to .net 7
So every time I Use ClickOnce now to Publish, when the new version is Loaded the User Settings are set back to default.
When a user then updates a User Setting it now creates a new folder inside the Appdata/Local/Application Folder, and adds a new user.config file.
Doing research on this Subject its seems I would need to Use a Strong Name to Sign the Assembly in .net5 and .net6, but this tab seems to be missing from the project properties, in Visual Studio 2022 with .net7

ScreenShot of New Folder Creation

ScreenShot of Missing Tab

So what used to Happen is every time I published using ClickOnce, the User settings would stay in the same folder, and now its not recognising that folder and creates a new folder when the user saves a new setting.

Any help here would be appreciated...


问:
Conditionally run app.ts from different src folders - React Native
I have re-written an application copying code from src (old) to src2 (new). Now I want to make a switch between those two apps in run time based on a swagger response. If the swagger returns v2 it should pick the entry point from src2 folder, if it returns v1 start from old src. Since this is something new, I am looking for possible approaches to make the conditional switch.

One is to have the condition in index.js and start the correct app.ts


问:
EMAIL wont Outlook Email using Access form
MS Access 2019 form supplies data to send an email via Outlook 2019.
The recipient (email address) will not populate the email "To" box unless it is text, but will not if it is an email. When 'proving the VBA data transfer via msgbox, it will. I suspect it could be my dim declaration type but I have tried others such as string and variant(illustrated)
The code below will allow the MsgBox to run, but nothing else.
My form fields are named" 'Name' txtRecip,  and 'EMail' txtEmail
Any ideas?
Thanks in advance
Fred</p>
```<code>Private Sub btnSendEmail_Click()
    Dim objOutlook As Outlook.Application
    Dim objOutlookMsg As Outlook.MailItem
    Dim objOutlookRecip As Outlook.Recipient
    Dim objOutlookAttach As Outlook.Attachment
    Dim objEmail As Variant

    ' Create the Outlook session.
    Set objOutlook = CreateObject("Outlook.Application") ' Create the message.
    Set objOutlookMsg = objOutlook.CreateItem(olMailItem)

    With objOutlookMsg
    ' Add the To recipient(s) to the message.
    objEmail = [txtEmail].Value
    response = MsgBox(objEmail)
    Set objOutlookRecip = .Recipients.Add(objEmail)
    objOutlookRecip.Type = olTo
   'response = MsgBox(txtName & Chr(13) & txtEmail)
    ' Add the CC recipient(s) to the message.
   ' Set objOutlookRecip = .Recipients.Add("")
   ' objOutlookRecip.Type = olCC

    ' Set the Subject, Body, and Importance of the message.
    .Subject = "B2B - Brethren Outreach"
    .Body = txtName.Value & "," & Chr(13) & Chr(13) & "
</code>```

Body:
MS Access 2019 form supplies data to send an email via Outlook 2019.
The recipient (email address) will not populate the email "To" box unless it is text, but will not if it is an email. When 'proving the VBA data transfer via msgbox, it will. I suspect it could be my dim declaration type but I have tried others such as string and variant(illustrated)
The code below will allow the MsgBox to run, but nothing else.
My form fields are named" 'Name' txtRecip,  and 'EMail' txtEmail
Any ideas?
Thanks in advance
Fred

Private Sub btnSendEmail_Click()
    Dim objOutlook As Outlook.Application
    Dim objOutlookMsg As Outlook.MailItem
    Dim objOutlookRecip As Outlook.Recipient
    Dim objOutlookAttach As Outlook.Attachment
    Dim objEmail As Variant

    ' Create the Outlook session.
    Set objOutlook = CreateObject("Outlook.Application") ' Create the message.
    Set objOutlookMsg = objOutlook.CreateItem(olMailItem)

    With objOutlookMsg
    ' Add the To recipient(s) to the message.
    objEmail = [txtEmail].Value
    response = MsgBox(objEmail)
    Set objOutlookRecip = .Recipients.Add(objEmail)
    objOutlookRecip.Type = olTo
   'response = MsgBox(txtName & Chr(13) & txtEmail)
    ' Add the CC recipient(s) to the message.
   ' Set objOutlookRecip = .Recipients.Add("")
   ' objOutlookRecip.Type = olCC

    ' Set the Subject, Body, and Importance of the message.
    .Subject = "B2B - Brethren Outreach"
    .Body = txtName.Value & "," & Chr(13) & Chr(13) & "


问:
Do C# NPOI support phonetic text (japanese/chinese text)?
I am converting excel file .xlsx with phonetic text (Japanese text) but the output file gives out warning that there are unreadable contents, and the data are missing from the file.

It seems that the issues were because NPOI can't process the phonetic guide from Microsoft Excel in Japanese language.

This only applies on .xlsx files and not .xls files.

I'm not sure how to attach the sample excel file but the image above shows what it looks like. Basically, if you use Microsoft Excel in Japanese version, there will be automatic phonetic guide for every kanji (Chinese character).

```<code>public void writeoutput(string val)
{
    try
    {
        IWorkbook book;
        string outPath = "<path for input file>";

        using (FileStream file = new FileStream(outPath, FileMode.Open, FileAccess.Read))
        {
            try
            {
                book = new XSSFWorkbook(file);
            }
            catch (Exception e)
            {
                book = null;
            }

            if (book == null)
            {
                book = new HSSFWorkbook(file);
            }

            file.Close();
        }

        //ISheet sheet = outputSheet.GetSheet("Sheet1");
        ISheet sheet = book.GetSheetAt(0);

        sheet.CopySheet("NewSheet", false);

        IRow dataRow = sheet.GetRow(35) ?? sheet.CreateRow(35);
        ICell cell = dataRow.GetCell(8) ?? dataRow.CreateCell(8);

        cell.SetCellValue(val);

        //File.Delete(outPath);
        outPath = "<path for output file>";

        using (FileStream file = new FileStream(outPath, FileMode.OpenOrCreate, FileAccess.Write))
        {
            book.Write(file);
            file.Close();
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
    }
    finally
    {
        textBox2.Text = "done";
    }
}
</code>```

I tried disable the phonetic guide in Microsoft Excel and the processing of the .xlsx file works with no issues but I can only disable the phonetic guide on the text one by one and it is very time consuming.

Body:
I am converting excel file .xlsx with phonetic text (Japanese text) but the output file gives out warning that there are unreadable contents, and the data are missing from the file.

It seems that the issues were because NPOI can't process the phonetic guide from Microsoft Excel in Japanese language.

This only applies on .xlsx files and not .xls files.

I'm not sure how to attach the sample excel file but the image above shows what it looks like. Basically, if you use Microsoft Excel in Japanese version, there will be automatic phonetic guide for every kanji (Chinese character).

public void writeoutput(string val)
{
    try
    {
        IWorkbook book;
        string outPath = "<path for input file>";

        using (FileStream file = new FileStream(outPath, FileMode.Open, FileAccess.Read))
        {
            try
            {
                book = new XSSFWorkbook(file);
            }
            catch (Exception e)
            {
                book = null;
            }

            if (book == null)
            {
                book = new HSSFWorkbook(file);
            }

            file.Close();
        }

        //ISheet sheet = outputSheet.GetSheet("Sheet1");
        ISheet sheet = book.GetSheetAt(0);

        sheet.CopySheet("NewSheet", false);

        IRow dataRow = sheet.GetRow(35) ?? sheet.CreateRow(35);
        ICell cell = dataRow.GetCell(8) ?? dataRow.CreateCell(8);

        cell.SetCellValue(val);

        //File.Delete(outPath);
        outPath = "<path for output file>";

        using (FileStream file = new FileStream(outPath, FileMode.OpenOrCreate, FileAccess.Write))
        {
            book.Write(file);
            file.Close();
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
    }
    finally
    {
        textBox2.Text = "done";
    }
}

I tried disable the phonetic guide in Microsoft Excel and the processing of the .xlsx file works with no issues but I can only disable the phonetic guide on the text one by one and it is very time consuming.


问:
Why aren't changes in an object able to be written into a file?
I am trying to write the same object to a file twice. However, changing a value in the object does not seem to change what is written to the file.

public static void main(String[] args) throws IOException, ClassNotFoundException {

        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("file.txt"));
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("file.txt"));

        MyObj obj = new MyObj();

        obj.val = 1;
        oos.writeObject(obj);

        obj.val = 2;
        oos.writeObject(obj);

        System.out.println( ((MyObj)ois.readObject()).val );
        System.out.println( ((MyObj)ois.readObject()).val );

        oos.close();
        ois.close();
}
```
<p>MyObj implementation:</p>
<pre class="lang-java prettyprint-override"><code>
class MyObj implements Serializable  {
    int val;
}
</code>```

Since obj.val is 1 when I write obj to the file for the first time and 2 the second time, I am expecting the program to print 1 then 2. However, I get 1 printed both times instead.

Why is this the case, and what can I do to get around this?

Body:
I am trying to write the same object to a file twice. However, changing a value in the object does not seem to change what is written to the file.

public static void main(String[] args) throws IOException, ClassNotFoundException {

        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("file.txt"));
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("file.txt"));

        MyObj obj = new MyObj();

        obj.val = 1;
        oos.writeObject(obj);

        obj.val = 2;
        oos.writeObject(obj);

        System.out.println( ((MyObj)ois.readObject()).val );
        System.out.println( ((MyObj)ois.readObject()).val );

        oos.close();
        ois.close();
}

MyObj implementation:

class MyObj implements Serializable  {
    int val;
}

Since obj.val is 1 when I write obj to the file for the first time and 2 the second time, I am expecting the program to print 1 then 2. However, I get 1 printed both times instead.

Why is this the case, and what can I do to get around this?


问:
Is possible to set Carousel Pages visible on condition in Xamarin?
I have the following code in Xamarin.Forms:

```<code><CarouselPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="App.Views.SliderPage"
         xmlns:vm="clr-namespace:App.ViewModels"
         xmlns:d="http://xamarin.com/schemas/2014/forms/design"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:pages="clr-namespace:App.Views"
          mc:Ignorable="d"
         >
<CarouselPage.ToolbarItems>
    <ToolbarItem Text="Complete" Command="{Binding SubmitCommand}" />
</CarouselPage.ToolbarItems>
<pages:APage/>
<pages:BPage/>
<pages:CPage/>
</CarouselPage>
</code>```

I want to display pages regarding condition like IsVisible, but I couldn't find any solution. Is that even possible here?

Body:
I have the following code in Xamarin.Forms:

<CarouselPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="App.Views.SliderPage"
         xmlns:vm="clr-namespace:App.ViewModels"
         xmlns:d="http://xamarin.com/schemas/2014/forms/design"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:pages="clr-namespace:App.Views"
          mc:Ignorable="d"
         >
<CarouselPage.ToolbarItems>
    <ToolbarItem Text="Complete" Command="{Binding SubmitCommand}" />
</CarouselPage.ToolbarItems>
<pages:APage/>
<pages:BPage/>
<pages:CPage/>
</CarouselPage>

I want to display pages regarding condition like IsVisible, but I couldn't find any solution. Is that even possible here?


问:
HIDL to AIDL HAL conversion
I have recently started working on Android side and end up with one issue.
As from Android U onwards all Android HALs will be migrated to AIDLs, I am currently trying to do this migration for my project. With the hidl2aidl tool I am successfully able to generate *.aidl files.

But I am observing the below fixme line in my generated aidl file.

// FIXME: AIDL does not allow int to be an out parameter.
// Move it to return, or add it to a Parcelable.

Is there any know fix for these kind of FixMes? Is there any issue in setting out parameter with AIDL? What if I have multiple out parameters from a function?

Title: HIDL to AIDL HAL conversion


问:
Android - java.lang.IllegalStateException: Theme.getKey() reflection exception
After uploading my app for closed testing the following exception is reported in the prelaunch report:

```<code>Exception java.lang.IllegalStateException: Theme.getKey() reflection exception
  at aufa.b (aufa.java:10)
  at axbv.a (axbv.java:2)
  at androidx.compose.runtime.internal.ComposableLambdaImpl.a (ComposableLambdaImpl.java:5)
  at androidx.compose.ui.platform.ComposeView.a (ComposeView.java)
  at androidx.compose.ui.platform.AbstractComposeView$ensureCompositionCreated$1.a (AbstractComposeView.java:2)
  at androidx.compose.runtime.internal.ComposableLambdaImpl.a (ComposableLambdaImpl.java:5)
  at androidx.compose.runtime.CompositionLocalKt.c (CompositionLocalKt.java:19)
  at androidx.compose.ui.platform.CompositionLocalsKt.a (CompositionLocalsKt.java:6)
  at androidx.compose.ui.platform.AndroidCompositionLocals_androidKt$ProvideAndroidCompositionLocals$3.a (AndroidCompositionLocals_androidKt.java:2)
  at androidx.compose.runtime.internal.ComposableLambdaImpl.a (ComposableLambdaImpl.java:5)
  at androidx.compose.runtime.CompositionLocalKt.c (CompositionLocalKt.java:19)
  at androidx.compose.ui.platform.AndroidCompositionLocals_androidKt.a (AndroidCompositionLocals_androidKt.java:58)
  at androidx.compose.ui.platform.WrappedComposition$setContent$1$1$3.a (WrappedComposition.java:2)
  at androidx.compose.runtime.internal.ComposableLambdaImpl.a (ComposableLambdaImpl.java:5)
  at androidx.compose.runtime.CompositionLocalKt.c (CompositionLocalKt.java:19)
  at androidx.compose.ui.platform.WrappedComposition$setContent$1$1.a (WrappedComposition.java:7)
  at androidx.compose.runtime.internal.ComposableLambdaImpl.a (ComposableLambdaImpl.java:5)
  at androidx.compose.runtime.ActualJvm_jvmKt.a (ActualJvm_jvmKt.java:3)
  at androidx.compose.runtime.ComposerImpl$doCompose$2$5.a (ComposerImpl.java:3)
  at androidx.compose.runtime.SnapshotStateKt__DerivedStateKt.b (SnapshotStateKt__DerivedStateKt.java:6)
  at androidx.compose.runtime.ComposerImpl.U (ComposerImpl.java:15)
  at androidx.compose.runtime.Recomposer.e (Recomposer.java:11)
  at androidx.compose.runtime.CompositionImpl.c (CompositionImpl.java:1)
  at androidx.compose.ui.platform.WrappedComposition$setContent$1.XA (WrappedComposition.java:5)
  at androidx.compose.ui.platform.WrappedComposition.c (WrappedComposition.java:4)
  at androidx.compose.ui.platform.WrappedComposition.afo (WrappedComposition.java:2)
  at bcx.a (bcx.java)
  at bcq.b (bcq.java:6)
  at androidx.compose.ui.platform.WrappedComposition$setContent$1.XA (WrappedComposition.java:6)
  at androidx.compose.ui.platform.AndroidComposeView.onAttachedToWindow (AndroidComposeView.java:9)
  at android.view.View.dispatchAttachedToWindow (View.java:21307)
  at android.view.ViewGroup.dispatchAttachedToWindow (ViewGroup.java:4239)
  at android.view.ViewGroup.dispatchAttachedToWindow (ViewGroup.java:4246)
  at android.view.ViewGroup.addViewInner (ViewGroup.java:6001)
  at android.view.ViewGroup.addView (ViewGroup.java:5777)
  at android.view.ViewGroup.addView (ViewGroup.java:5717)
  at bhnp.aac (bhnp.java:7)
  at bhmx.a (bhmx.java:5)
  at bhmj.g (bhmj.java:4)
  at bhnb.n (bhnb.java:4)
  at axcc.acF (axcc.java:3)
  at bde.c (bde.java:2)
  at bde.f (bde.java:1)
  at bdd.d (bdd.java:5)
  at bde.h (bde.java:3)
  at axeq.a (axeq.java:2)
  at axcd.b (axcd.java:3)
  at bhnb.aac (bhnb.java:3)
  at bhmx.a (bhmx.java:5)
  at bhol.a (bhol.java:5)
  at com.google.android.finsky.uipattern.base.render.RenderTreeHost$observer$1.p (RenderTreeHost.java)
  at androidx.lifecycle.FullLifecycleObserverAdapter.afo (FullLifecycleObserverAdapter.java:7)
  at bcx.a (bcx.java)
  at bcq.k (bcq.java:10)
  at bcq.h (bcq.java:2)
  at bcq.c (bcq.java)
  at dv.a (dv.java)
  at di.d (di.java:138)
  at cy.ar (cy.java:60)
  at cy.at (cy.java:8)
  at cy.aj (cy.java:7)
  at cl.run (cl.java)
  at android.os.Handler.handleCallback (Handler.java:883)
  at android.os.Handler.dispatchMessage (Handler.java:100)
  at android.os.Looper.loop (Looper.java:237)
  at android.app.ActivityThread.main (ActivityThread.java:8016)
  at java.lang.reflect.Method.invoke (Method.java)
  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:493)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1076)
Caused by java.lang.NoSuchMethodException: android.content.res.Resources$Theme.getKey []
  at java.lang.Class.getMethod (Class.java:2072)
  at java.lang.Class.getDeclaredMethod (Class.java:2050)
  at aufa.b (aufa.java:8)
</code>```

It seems like the exception is happening due to some composable view, but I am not using the jetpack compose in my project.

Minimum SDK: 21

Target SDK: 31

AGP Version: 4.1.3

Android Studio Version: Android Studio Chipmunk | 2021.2.1 Patch 1

What could be the reason behind this?

Body:
After uploading my app for closed testing the following exception is reported in the prelaunch report:

Exception java.lang.IllegalStateException: Theme.getKey() reflection exception
  at aufa.b (aufa.java:10)
  at axbv.a (axbv.java:2)
  at androidx.compose.runtime.internal.ComposableLambdaImpl.a (ComposableLambdaImpl.java:5)
  at androidx.compose.ui.platform.ComposeView.a (ComposeView.java)
  at androidx.compose.ui.platform.AbstractComposeView$ensureCompositionCreated$1.a (AbstractComposeView.java:2)
  at androidx.compose.runtime.internal.ComposableLambdaImpl.a (ComposableLambdaImpl.java:5)
  at androidx.compose.runtime.CompositionLocalKt.c (CompositionLocalKt.java:19)
  at androidx.compose.ui.platform.CompositionLocalsKt.a (CompositionLocalsKt.java:6)
  at androidx.compose.ui.platform.AndroidCompositionLocals_androidKt$ProvideAndroidCompositionLocals$3.a (AndroidCompositionLocals_androidKt.java:2)
  at androidx.compose.runtime.internal.ComposableLambdaImpl.a (ComposableLambdaImpl.java:5)
  at androidx.compose.runtime.CompositionLocalKt.c (CompositionLocalKt.java:19)
  at androidx.compose.ui.platform.AndroidCompositionLocals_androidKt.a (AndroidCompositionLocals_androidKt.java:58)
  at androidx.compose.ui.platform.WrappedComposition$setContent$1$1$3.a (WrappedComposition.java:2)
  at androidx.compose.runtime.internal.ComposableLambdaImpl.a (ComposableLambdaImpl.java:5)
  at androidx.compose.runtime.CompositionLocalKt.c (CompositionLocalKt.java:19)
  at androidx.compose.ui.platform.WrappedComposition$setContent$1$1.a (WrappedComposition.java:7)
  at androidx.compose.runtime.internal.ComposableLambdaImpl.a (ComposableLambdaImpl.java:5)
  at androidx.compose.runtime.ActualJvm_jvmKt.a (ActualJvm_jvmKt.java:3)
  at androidx.compose.runtime.ComposerImpl$doCompose$2$5.a (ComposerImpl.java:3)
  at androidx.compose.runtime.SnapshotStateKt__DerivedStateKt.b (SnapshotStateKt__DerivedStateKt.java:6)
  at androidx.compose.runtime.ComposerImpl.U (ComposerImpl.java:15)
  at androidx.compose.runtime.Recomposer.e (Recomposer.java:11)
  at androidx.compose.runtime.CompositionImpl.c (CompositionImpl.java:1)
  at androidx.compose.ui.platform.WrappedComposition$setContent$1.XA (WrappedComposition.java:5)
  at androidx.compose.ui.platform.WrappedComposition.c (WrappedComposition.java:4)
  at androidx.compose.ui.platform.WrappedComposition.afo (WrappedComposition.java:2)
  at bcx.a (bcx.java)
  at bcq.b (bcq.java:6)
  at androidx.compose.ui.platform.WrappedComposition$setContent$1.XA (WrappedComposition.java:6)
  at androidx.compose.ui.platform.AndroidComposeView.onAttachedToWindow (AndroidComposeView.java:9)
  at android.view.View.dispatchAttachedToWindow (View.java:21307)
  at android.view.ViewGroup.dispatchAttachedToWindow (ViewGroup.java:4239)
  at android.view.ViewGroup.dispatchAttachedToWindow (ViewGroup.java:4246)
  at android.view.ViewGroup.addViewInner (ViewGroup.java:6001)
  at android.view.ViewGroup.addView (ViewGroup.java:5777)
  at android.view.ViewGroup.addView (ViewGroup.java:5717)
  at bhnp.aac (bhnp.java:7)
  at bhmx.a (bhmx.java:5)
  at bhmj.g (bhmj.java:4)
  at bhnb.n (bhnb.java:4)
  at axcc.acF (axcc.java:3)
  at bde.c (bde.java:2)
  at bde.f (bde.java:1)
  at bdd.d (bdd.java:5)
  at bde.h (bde.java:3)
  at axeq.a (axeq.java:2)
  at axcd.b (axcd.java:3)
  at bhnb.aac (bhnb.java:3)
  at bhmx.a (bhmx.java:5)
  at bhol.a (bhol.java:5)
  at com.google.android.finsky.uipattern.base.render.RenderTreeHost$observer$1.p (RenderTreeHost.java)
  at androidx.lifecycle.FullLifecycleObserverAdapter.afo (FullLifecycleObserverAdapter.java:7)
  at bcx.a (bcx.java)
  at bcq.k (bcq.java:10)
  at bcq.h (bcq.java:2)
  at bcq.c (bcq.java)
  at dv.a (dv.java)
  at di.d (di.java:138)
  at cy.ar (cy.java:60)
  at cy.at (cy.java:8)
  at cy.aj (cy.java:7)
  at cl.run (cl.java)
  at android.os.Handler.handleCallback (Handler.java:883)
  at android.os.Handler.dispatchMessage (Handler.java:100)
  at android.os.Looper.loop (Looper.java:237)
  at android.app.ActivityThread.main (ActivityThread.java:8016)
  at java.lang.reflect.Method.invoke (Method.java)
  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:493)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1076)
Caused by java.lang.NoSuchMethodException: android.content.res.Resources$Theme.getKey []
  at java.lang.Class.getMethod (Class.java:2072)
  at java.lang.Class.getDeclaredMethod (Class.java:2050)
  at aufa.b (aufa.java:8)

It seems like the exception is happening due to some composable view, but I am not using the jetpack compose in my project.

Minimum SDK: 21

Target SDK: 31

AGP Version: 4.1.3

Android Studio Version: Android Studio Chipmunk | 2021.2.1 Patch 1

What could be the reason behind this?


问:
What change to make in Terraform 1.3.5 file for security group not found error while using security group as data source
I am in the process of changing Terraform version from 1.1.4 to 1.3.5 and aws provider 4.40.0. The aws eks cluster resource is created with:

```<code>    resource "aws_eks_cluster" "eks-cluster" {
     depends_on = [
       aws_cloudwatch_log_group.eks-cluster,
       aws_iam_role_policy_attachment.masters-attach-AmazonEKSClusterPolicy,
       aws_iam_role_policy_attachment.masters-attach-AmazonEKSServicePolicy
     ]
     enabled_cluster_log_types = ["api", "audit"]
     name                      = "${var.prefix}-eks-cluster-${var.active_cluster}"
     role_arn                  = aws_iam_role.masters-iam-role.arn
     version                   = var.k8s_version

     vpc_config {
       endpoint_private_access = true
       security_group_ids      = [aws_security_group.eks-sg.id]
       subnet_ids = [aws_subnet.private-subnet-1.id,
         aws_subnet.private-subnet-2.id,
         aws_subnet.private-subnet-3.id,
         aws_subnet.utility-subnet-1.id,
         aws_subnet.utility-subnet-2.id,
       aws_subnet.utility-subnet-3.id]
     }
    }
</code>```

Aws managed node group inside this eks cluster is created with:

```<code>
    resource "aws_eks_node_group" "worker-node-grp" {
      cluster_name    = aws_eks_cluster.eks-cluster.name
      node_group_name = "${var.prefix}-nodes-${var.active_cluster}"
      node_role_arn   = aws_iam_role.nodes-iam-role.arn
      subnet_ids = [aws_subnet.private-subnet-1.id,
        aws_subnet.private-subnet-2.id, aws_subnet.private-subnet-3.id]
      version = var.k8s_version
      capacity_type   = "ON_DEMAND"
      instance_types = [var.worker_instance_size, var.worker_instance_size_back_up1, var.worker_instance_size_back_up2]

      launch_template {
        id      = aws_launch_template.eks-launch_template.id
        version = aws_launch_template.eks-launch_template.latest_version
      }
      lifecycle{
        create_before_destroy = true
      }
    }
</code>```

I am using data source to get the eks created security group (this is created by aws when it creates the managed node group) like this:

```<code>
    data "aws_security_group" "worker-node-security-group" {
      filter {
        name   = "tag:Name"
        values = ["eks-cluster-sg-${var.prefix}-eks-cluster-${var.active_cluster}-*"]
      }
      depends_on = [
        aws_eks_node_group.worker-node-grp,
        aws_eks_cluster.eks-cluster
      ]
    }
</code>```

The problem is that with Terraform version 1.1.4, the above code works without any issues, however with terraform 1.3.5 and aws provider 4.40.0 it gives the below error. I Have been trying for a many days now and I dont understand why 1.3.5 causes this issue. How do I fix this?

```<code>
    [31m[31m╷[0m[0m
    [31m│[0m [0m[1m[31mError: [0m[0m[1mno matching EC2 Security Group found[0m
    [31m│[0m [0m
    [31m│[0m [0m[0m  with module.eks-cluster.data.aws_security_group.worker-node-security-group,
    [31m│[0m [0m  on eks-cluster/main.tf line 221, in data "aws_security_group" "worker-node-security-group":
    [31m│[0m [0m 221: data "aws_security_group" "worker-node-security-group" [4m{[0m[0m
    [31m│[0m [0m
    [31m╵[0m[0m
    [0m[0m

</code>```

This is the security group in question. https://docs.aws.amazon.com/eks/latest/userguide/sec-group-reqs.html
we dont want to give ssh access to the worker nodes by using the remote_access attribute

Body:
I am in the process of changing Terraform version from 1.1.4 to 1.3.5 and aws provider 4.40.0. The aws eks cluster resource is created with:

    resource "aws_eks_cluster" "eks-cluster" {
     depends_on = [
       aws_cloudwatch_log_group.eks-cluster,
       aws_iam_role_policy_attachment.masters-attach-AmazonEKSClusterPolicy,
       aws_iam_role_policy_attachment.masters-attach-AmazonEKSServicePolicy
     ]
     enabled_cluster_log_types = ["api", "audit"]
     name                      = "${var.prefix}-eks-cluster-${var.active_cluster}"
     role_arn                  = aws_iam_role.masters-iam-role.arn
     version                   = var.k8s_version

     vpc_config {
       endpoint_private_access = true
       security_group_ids      = [aws_security_group.eks-sg.id]
       subnet_ids = [aws_subnet.private-subnet-1.id,
         aws_subnet.private-subnet-2.id,
         aws_subnet.private-subnet-3.id,
         aws_subnet.utility-subnet-1.id,
         aws_subnet.utility-subnet-2.id,
       aws_subnet.utility-subnet-3.id]
     }
    }

Aws managed node group inside this eks cluster is created with:

    resource "aws_eks_node_group" "worker-node-grp" {
      cluster_name    = aws_eks_cluster.eks-cluster.name
      node_group_name = "${var.prefix}-nodes-${var.active_cluster}"
      node_role_arn   = aws_iam_role.nodes-iam-role.arn
      subnet_ids = [aws_subnet.private-subnet-1.id,
        aws_subnet.private-subnet-2.id, aws_subnet.private-subnet-3.id]
      version = var.k8s_version
      capacity_type   = "ON_DEMAND"
      instance_types = [var.worker_instance_size, var.worker_instance_size_back_up1, var.worker_instance_size_back_up2]

      launch_template {
        id      = aws_launch_template.eks-launch_template.id
        version = aws_launch_template.eks-launch_template.latest_version
      }
      lifecycle{
        create_before_destroy = true
      }
    }

I am using data source to get the eks created security group (this is created by aws when it creates the managed node group) like this:

    data "aws_security_group" "worker-node-security-group" {
      filter {
        name   = "tag:Name"
        values = ["eks-cluster-sg-${var.prefix}-eks-cluster-${var.active_cluster}-*"]
      }
      depends_on = [
        aws_eks_node_group.worker-node-grp,
        aws_eks_cluster.eks-cluster
      ]
    }

The problem is that with Terraform version 1.1.4, the above code works without any issues, however with terraform 1.3.5 and aws provider 4.40.0 it gives the below error. I Have been trying for a many days now and I dont understand why 1.3.5 causes this issue. How do I fix this?

    [31m[31m╷[0m[0m
    [31m│[0m [0m[1m[31mError: [0m[0m[1mno matching EC2 Security Group found[0m
    [31m│[0m [0m
    [31m│[0m [0m[0m  with module.eks-cluster.data.aws_security_group.worker-node-security-group,
    [31m│[0m [0m  on eks-cluster/main.tf line 221, in data "aws_security_group" "worker-node-security-group":
    [31m│[0m [0m 221: data "aws_security_group" "worker-node-security-group" [4m{[0m[0m
    [31m│[0m [0m
    [31m╵[0m[0m
    [0m[0m

This is the security group in question. https://docs.aws.amazon.com/eks/latest/userguide/sec-group-reqs.html
we dont want to give ssh access to the worker nodes by using the remote_access attribute


问:
With NX/Angular, how can I debug an app production build failure?
I'm getting the following error, and I want to know how to debug it.

The command is nx run my-app:build:production

and the output includes (with a bunch of warnings omitted):

```<code>Error: Optimization error [main.64ff99fef94b1aca.js]: Error: Transform failed with 1 error:
main.64ff99fef94b1aca.js:22080:5: ERROR: Expected identifier but found "="
</code>```

Now what I would like to do is to go to this main.js file at the line stated and make sense of what bit of the code is going wrong and where, however it doesn't exist in the dist folder so I can't even see where to begin?

Body:
I'm getting the following error, and I want to know how to debug it.

The command is nx run my-app:build:production

and the output includes (with a bunch of warnings omitted):

Error: Optimization error [main.64ff99fef94b1aca.js]: Error: Transform failed with 1 error:
main.64ff99fef94b1aca.js:22080:5: ERROR: Expected identifier but found "="

Now what I would like to do is to go to this main.js file at the line stated and make sense of what bit of the code is going wrong and where, however it doesn't exist in the dist folder so I can't even see where to begin?


问:
Docker container not created
sh: 1: nodemon: not found
npm ERR! code ELIFECYCLE
npm ERR! syscall spawn
npm ERR! file sh
npm ERR! errno ENOENT
npm ERR! server.js@1.0.0 dev: nodemon server.js
npm ERR! spawn ENOENT
npm ERR!
npm ERR! Failed at the server.js@1.0.0 dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2022-12-19T04_18_54_441Z-debug.log

Please guide me to rectify code or why this error, already run nodemon in terminal

Title: Docker container not created


问:
Why does my program ignore repaint() method?
I have been working on this implementation of stratego using socket networking with java for some time and I am stuck trying to make the attacks visible for both players.
(In stratego you cannot see your opponents' pawns except when two pawns attack and they are both revealed before one or both get discarded as a result of the battle)

I have a JPanel named Board which paints each cell depending on conditions (is there a pawn on the cell, is the pawn visible by the player etc...)

The way I laid it out is when a player makes an attack it splits the move in two parts, in the first one, both pawns are visible to both player and then the attack actually takes place.

For some reason, my program ignores the repaint() method when I want to show the two pawns and so they do not become visible. To add to that, the problem only occurs for the current player, not the player receiving the information, which is weird because they go through the same function in the Board class.

This code segment runs when the current player presses ENTER and it's that player's turn

```<code>               else if(myTurn)
               {
                   int []tempArr=board.enterKeyPressed(setupDone,true,true);

                    if(tempArr[4]==Utils.ATTACK)
                    {
                        sendMove(tempArr);

                        try {
                            TimeUnit.SECONDS.sleep(2);
                        } catch (InterruptedException e1) {
                            e1.printStackTrace();
                        }

                       tempArr=board.enterKeyPressed(setupDone,true,false);

                       notifyAll();
                       myTurn=false;
                   }
                   else if(tempArr[4]==Utils.MOVE)
                   {
                       sendMove(tempArr);
                       notifyAll();
                       myTurn=false;
                   }
                   gameOver=board.isGameOver();
               }
</code>```

This is the enterKeyPressed method

For some reason, when begginingOfTurn is false and attackInProgress is true (which means that pawns involved in the battled will be visible in paintComponent) repaint() will not run properly. I have tried debugging by placing a breakpoint at the paintComponent function and it will be called every single time except for this specific instance.
Another odd thing is that it does work when thisPlayer is true (which means that the move is coming from the other player)

```<code> public int[]enterKeyPressed(boolean settupDone, boolean thisPlayer, boolean begginingOfTurn)
    {
        int []moveLocation= {-1,-1,-1,-1,-1};

        Alliance tempAlliance;
        if(thisPlayer)
            tempAlliance=boardAlliance;
        else
            tempAlliance=Alliance.getOppositeAlliance(boardAlliance);

        settingUpDone=settupDone;
        attackInProgress=false;

        if(!settupDone) //During setupPhase
        {
            settupAction();
        }
        else  //During battle phase
        {
            if(!squareSelected) //if no square is currently selected
            {
                if(canPawnMove()) //Checks if the pawn in the square has at least one available move
                {
                    xSelected=xSelector; //Make current square selected
                    ySelected=ySelector;
                    squareSelected=true;
                }
                moveLocation[4]=Utils.SELECTED;
            }
            else //if a square is currently selected
            {
                if(canPawnMoveToSquare(xSelector, ySelector) || !thisPlayer) //if the selector is at a square where the selected pawn can move
                {
                    if(square[xSelector][ySelector].isEmpty()) //move the pawn to that square
                    {
                        movePawn(thisPlayer);
                        moveLocation[4]=Utils.MOVE;
                        squareSelected=false;
                    }
                    else if(square[xSelector][ySelector].getPawn().playerAlliance==Alliance.getOppositeAlliance(tempAlliance))
                    {
                        if(begginingOfTurn)
                        {
                            attackInProgress=true;
                        }
                        else
                        {
                            attack(thisPlayer);
                            squareSelected=false;
                        }
                        moveLocation[4]=Utils.ATTACK;
                    }

                    moveLocation[0]=xSelected;
                    moveLocation[1]=ySelected;
                    moveLocation[2]=xSelector;
                    moveLocation[3]=ySelector;

                }
                else
                {
                    if(xSelector==xSelected && ySelector==ySelected) //if selector and selected are the same then square is deselected
                        squareSelected=false;

                    else if(square[xSelector][ySelector].getPawn().playerAlliance==boardAlliance  && canPawnMove())  //if it is a player's pawn that can move then selected square is moved to that square
                        xSelected=xSelector; ySelected=ySelector;

                    moveLocation[4]=Utils.SELECTED;
                }
            }
        }

        repaint();
        return moveLocation;
    }
</code>```

paintComponent method

```<code>    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);

        Graphics2D g2d = (Graphics2D) g;

        BufferedImage strategoLogo=null;
        try {
                strategoLogo= ImageIO.read(new File(Paths.get("","images","Stratego_logo_final.png").toString()));
            } catch (IOException e) {
                e.printStackTrace();
            }

        Image strategoImage= strategoLogo.getScaledInstance(350,350/4,Image.SCALE_SMOOTH);

        if(!gameOver)
            g2d.drawImage(strategoImage,435,0,this);

        Rectangle bigRect = new Rectangle(Utils.INITIAL_BOARD_X, Utils.INITIAL_BOARD_Y,   //Paints the board
                (Utils.TILE_LENGTH * 10), (Utils.TILE_LENGTH * 10));

        g2d.setColor(Utils.SQUARE_COLOR);
        g2d.fill(bigRect);

        for (int i = 0; i < 10; i++)  // Paints each cell
        {
            for (int j = 0; j < 10; j++) {
                paintCell(i, j, g2d);
            }
        }
    }
</code>```

Any help would be much appreciated I don't think I can figure this one out on my own
I can also add more code segments if it helps paint a clearer picture of the program

Body:
I have been working on this implementation of stratego using socket networking with java for some time and I am stuck trying to make the attacks visible for both players.
(In stratego you cannot see your opponents' pawns except when two pawns attack and they are both revealed before one or both get discarded as a result of the battle)

I have a JPanel named Board which paints each cell depending on conditions (is there a pawn on the cell, is the pawn visible by the player etc...)

The way I laid it out is when a player makes an attack it splits the move in two parts, in the first one, both pawns are visible to both player and then the attack actually takes place.

For some reason, my program ignores the repaint() method when I want to show the two pawns and so they do not become visible. To add to that, the problem only occurs for the current player, not the player receiving the information, which is weird because they go through the same function in the Board class.

This code segment runs when the current player presses ENTER and it's that player's turn

               else if(myTurn)
               {
                   int []tempArr=board.enterKeyPressed(setupDone,true,true);

                    if(tempArr[4]==Utils.ATTACK)
                    {
                        sendMove(tempArr);

                        try {
                            TimeUnit.SECONDS.sleep(2);
                        } catch (InterruptedException e1) {
                            e1.printStackTrace();
                        }

                       tempArr=board.enterKeyPressed(setupDone,true,false);

                       notifyAll();
                       myTurn=false;
                   }
                   else if(tempArr[4]==Utils.MOVE)
                   {
                       sendMove(tempArr);
                       notifyAll();
                       myTurn=false;
                   }
                   gameOver=board.isGameOver();
               }

This is the enterKeyPressed method

For some reason, when begginingOfTurn is false and attackInProgress is true (which means that pawns involved in the battled will be visible in paintComponent) repaint() will not run properly. I have tried debugging by placing a breakpoint at the paintComponent function and it will be called every single time except for this specific instance.
Another odd thing is that it does work when thisPlayer is true (which means that the move is coming from the other player)

 public int[]enterKeyPressed(boolean settupDone, boolean thisPlayer, boolean begginingOfTurn)
    {
        int []moveLocation= {-1,-1,-1,-1,-1};

        Alliance tempAlliance;
        if(thisPlayer)
            tempAlliance=boardAlliance;
        else
            tempAlliance=Alliance.getOppositeAlliance(boardAlliance);

        settingUpDone=settupDone;
        attackInProgress=false;

        if(!settupDone) //During setupPhase
        {
            settupAction();
        }
        else  //During battle phase
        {
            if(!squareSelected) //if no square is currently selected
            {
                if(canPawnMove()) //Checks if the pawn in the square has at least one available move
                {
                    xSelected=xSelector; //Make current square selected
                    ySelected=ySelector;
                    squareSelected=true;
                }
                moveLocation[4]=Utils.SELECTED;
            }
            else //if a square is currently selected
            {
                if(canPawnMoveToSquare(xSelector, ySelector) || !thisPlayer) //if the selector is at a square where the selected pawn can move
                {
                    if(square[xSelector][ySelector].isEmpty()) //move the pawn to that square
                    {
                        movePawn(thisPlayer);
                        moveLocation[4]=Utils.MOVE;
                        squareSelected=false;
                    }
                    else if(square[xSelector][ySelector].getPawn().playerAlliance==Alliance.getOppositeAlliance(tempAlliance))
                    {
                        if(begginingOfTurn)
                        {
                            attackInProgress=true;
                        }
                        else
                        {
                            attack(thisPlayer);
                            squareSelected=false;
                        }
                        moveLocation[4]=Utils.ATTACK;
                    }

                    moveLocation[0]=xSelected;
                    moveLocation[1]=ySelected;
                    moveLocation[2]=xSelector;
                    moveLocation[3]=ySelector;

                }
                else
                {
                    if(xSelector==xSelected && ySelector==ySelected) //if selector and selected are the same then square is deselected
                        squareSelected=false;

                    else if(square[xSelector][ySelector].getPawn().playerAlliance==boardAlliance  && canPawnMove())  //if it is a player's pawn that can move then selected square is moved to that square
                        xSelected=xSelector; ySelected=ySelector;

                    moveLocation[4]=Utils.SELECTED;
                }
            }
        }

        repaint();
        return moveLocation;
    }

paintComponent method

    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);

        Graphics2D g2d = (Graphics2D) g;

        BufferedImage strategoLogo=null;
        try {
                strategoLogo= ImageIO.read(new File(Paths.get("","images","Stratego_logo_final.png").toString()));
            } catch (IOException e) {
                e.printStackTrace();
            }

        Image strategoImage= strategoLogo.getScaledInstance(350,350/4,Image.SCALE_SMOOTH);

        if(!gameOver)
            g2d.drawImage(strategoImage,435,0,this);

        Rectangle bigRect = new Rectangle(Utils.INITIAL_BOARD_X, Utils.INITIAL_BOARD_Y,   //Paints the board
                (Utils.TILE_LENGTH * 10), (Utils.TILE_LENGTH * 10));

        g2d.setColor(Utils.SQUARE_COLOR);
        g2d.fill(bigRect);

        for (int i = 0; i < 10; i++)  // Paints each cell
        {
            for (int j = 0; j < 10; j++) {
                paintCell(i, j, g2d);
            }
        }
    }

Any help would be much appreciated I don't think I can figure this one out on my own
I can also add more code segments if it helps paint a clearer picture of the program


问:
Mocking Azure BlobServiceClient in Python
I am trying to write a unit test that will test azure.storage.blob.BlobServiceClient class and its methods. Below is my code

A fixture in the conftest.py

@pytest.fixture
def mock_BlobServiceClient(mocker):

    azure_ContainerClient = mocker.patch("azure.storage.blob.ContainerClient", mocker.MagicMock())

    azure_BlobServiceClient= mocker.patch("azure_module.BlobServiceClient", mocker.MagicMock())
    azure_BlobServiceClient.from_connection_string.return_value
    azure_BlobServiceClient.get_container_client.return_value = azure_ContainerClient
    azure_ContainerClient.list_blob_names.return_value = "test"
    azure_ContainerClient.get_container_client.list_blobs.return_value = ["test"]

    yield azure_BlobServiceClient

```
<p>Contents of the test file</p>
<pre class="lang-py prettyprint-override"><code>from azure_module import AzureBlob

def test_AzureBlob(mock_BlobServiceClient):
    azure_blob = AzureBlob()

    # This assertion passes
    mock_BlobServiceClient.from_connection_string.assert_called_once_with("testconnectionstring")

    # This assertion fails
    mock_BlobServiceClient.get_container_client.assert_called()

</code>```

Contents of the azure_module.py

from azure.storage.blob import BlobServiceClient
import os

class AzureBlob:

    def __init__(self) -> None:
        """Initialize the azure blob"""
        self.azure_blob_obj = BlobServiceClient.from_connection_string(os.environ["AZURE_STORAGE_CONNECTION_STRING"])
        self.azure_container = self.azure_blob_obj.get_container_client(os.environ["AZURE_CONTAINER_NAME"])
```
<p>My test fails when I execute it with below error message</p>
```>       mock_BlobServiceClient.get_container_client.assert_called()
E       AssertionError: Expected 'get_container_client' to have been called.
```
<p>I am not sure why it says that the <code>get_container_client</code> wasn't called when it was called during the <code>AzureBlob</code>'s initialization.</p>
<p>Any help is very much appreciated.</p>
<p><strong>Update 1</strong></p>
<p>I believe this is a bug in the <code>unittest</code>'s <code>MagicMock</code> itself. Per
Michael Delgado suggested that I dialed the code to a bare minimum to test and identify the issue, and I concluded that the <code>MagicMock</code> was causing the problem. Below are my findings:</p>
<p><strong>conftest.py</strong></p>
<pre class="lang-py prettyprint-override"><code>@pytest.fixture
def mock_Blob(mocker):
    yield mocker.patch("module.BlobServiceClient")
</code>```

test_azureblob.py

def test_AzureBlob(mock_Blob):

    azure_blob = AzureBlob()
    print(mock_Blob)
    print(mock_Blob.mock_calls)
    print(mock_Blob.from_connection_string.mock_calls)
    print(mock_Blob.from_connection_string.get_container_client.mock_calls)
    assert False  # <- Intentional fail

```
<p>After running the test, I got the following results.</p>
<pre class="lang-bash prettyprint-override"><code>$ pytest -vv
.
.
.
------------------------------------------------------------------------------------------- Captured stdout call -------------------------------------------------------------------------------------------
<MagicMock name='BlobServiceClient' id='140704187870944'>
[call.from_connection_string('AZURE_STORAGE_CONNECTION_STRING'),
 call.from_connection_string().get_container_client('AZURE_CONTAINER_NAME')]
[call('AZURE_STORAGE_CONNECTION_STRING'),
 call().get_container_client('AZURE_CONTAINER_NAME')]
[]
.
.
.
</code>```

The prints clearly show that the get_container_client was seen being called, but the mocked method did not register it at its level. That led me to conclude that the MagicMock has a bug which I will report to the developers for further investigation.

Body:
I am trying to write a unit test that will test azure.storage.blob.BlobServiceClient class and its methods. Below is my code

A fixture in the conftest.py

@pytest.fixture
def mock_BlobServiceClient(mocker):

    azure_ContainerClient = mocker.patch("azure.storage.blob.ContainerClient", mocker.MagicMock())

    azure_BlobServiceClient= mocker.patch("azure_module.BlobServiceClient", mocker.MagicMock())
    azure_BlobServiceClient.from_connection_string.return_value
    azure_BlobServiceClient.get_container_client.return_value = azure_ContainerClient
    azure_ContainerClient.list_blob_names.return_value = "test"
    azure_ContainerClient.get_container_client.list_blobs.return_value = ["test"]

    yield azure_BlobServiceClient

Contents of the test file

from azure_module import AzureBlob

def test_AzureBlob(mock_BlobServiceClient):
    azure_blob = AzureBlob()

    # This assertion passes
    mock_BlobServiceClient.from_connection_string.assert_called_once_with("testconnectionstring")

    # This assertion fails
    mock_BlobServiceClient.get_container_client.assert_called()

Contents of the azure_module.py

from azure.storage.blob import BlobServiceClient
import os

class AzureBlob:

    def __init__(self) -> None:
        """Initialize the azure blob"""
        self.azure_blob_obj = BlobServiceClient.from_connection_string(os.environ["AZURE_STORAGE_CONNECTION_STRING"])
        self.azure_container = self.azure_blob_obj.get_container_client(os.environ["AZURE_CONTAINER_NAME"])

My test fails when I execute it with below error message

>       mock_BlobServiceClient.get_container_client.assert_called()
E       AssertionError: Expected 'get_container_client' to have been called.

I am not sure why it says that the get_container_client wasn't called when it was called during the AzureBlob's initialization.

Any help is very much appreciated.

Update 1

I believe this is a bug in the unittest's MagicMock itself. Per
Michael Delgado suggested that I dialed the code to a bare minimum to test and identify the issue, and I concluded that the MagicMock was causing the problem. Below are my findings:

conftest.py

@pytest.fixture
def mock_Blob(mocker):
    yield mocker.patch("module.BlobServiceClient")

test_azureblob.py

def test_AzureBlob(mock_Blob):

    azure_blob = AzureBlob()
    print(mock_Blob)
    print(mock_Blob.mock_calls)
    print(mock_Blob.from_connection_string.mock_calls)
    print(mock_Blob.from_connection_string.get_container_client.mock_calls)
    assert False  # <- Intentional fail

After running the test, I got the following results.

$ pytest -vv
.
.
.
------------------------------------------------------------------------------------------- Captured stdout call -------------------------------------------------------------------------------------------
<MagicMock name='BlobServiceClient' id='140704187870944'>
[call.from_connection_string('AZURE_STORAGE_CONNECTION_STRING'),
 call.from_connection_string().get_container_client('AZURE_CONTAINER_NAME')]
[call('AZURE_STORAGE_CONNECTION_STRING'),
 call().get_container_client('AZURE_CONTAINER_NAME')]
[]
.
.
.

The prints clearly show that the get_container_client was seen being called, but the mocked method did not register it at its level. That led me to conclude that the MagicMock has a bug which I will report to the developers for further investigation.


问:
libwebsockets throws CLIENT_CONNECTION_ERROR: Unable to connect when performing Ping operation
I have sort of hit a dead end. Can someone please help.
I have never used libwebsockets before. I have an RPI4(Installed Ubuntu 22.04), where my code is running which tries to ping my Laptop(Windows 10). Both are on same Wi-Fi network. I am able to Ping each other through command prompt, however through code it throws an error CLIENT_CONNECTION_ERROR.
Same code works properly on Ubuntu 20.04 running on x86_64 Virtual Box.
However it does not work when we run it on an RPI4.
Here's the error log:

```<code>[2022/12/18 14:52:36:0612] N: lws_create_context: LWS: 4.3.99-v4.3.0-275-gec6d5ac6, NET CLI SRV H1 H2 WS SS-JSON-POL ConMon IPv6-absent
[2022/12/18 14:52:36:0716] N: __lws_lc_tag:  ++ [wsi|0|pipe] (1)
[2022/12/18 14:52:36:0758] N: __lws_lc_tag:  ++ [vh|0|netlink] (1)
[2022/12/18 14:52:36:0781] N: __lws_lc_tag:  ++ [vh|1|default||-1] (2)
[2022/12/18 14:52:36:0845] N: lws_tls_client_create_vhost_context: doing cert filepath
[2022/12/18 14:52:36:0895] N: HttpPing: connecting to 192.168.1.4:7778
[2022/12/18 14:52:36:0905] N: __lws_lc_tag:  ++ [wsicli|0|GET/h1/default/192.168.1.4] (1)
[2022/12/18 14:52:36:0907] N: [wsicli|0|GET/h1/default/192.168.1.4]: lws_client_connect_3_connect: trying 192.168.1.4
CLIENT_CONNECTION_ERROR: Unable to connect
[2022/12/18 14:52:38:0927] N: __lws_lc_untag:  -- [wsicli|0|GET/h1/default/192.168.1.4] (0) 2.002s
[2022/12/18 14:52:38:0932] N: __lws_lc_untag:  -- [wsi|0|pipe] (0) 2.021s
[2022/12/18 14:52:38:0933] N: __lws_lc_untag:  -- [vh|0|netlink] (1) 2.017s
[2022/12/18 14:52:38:0934] N: __lws_lc_untag:  -- [vh|1|default||-1] (0) 2.015s

</code>```

Things tried:

Disabled IPV6 while compiling libwebsockets by using the command -> cmake .. -DLWS_IPV6=OFF

Turned off Firewall on ubuntu

Body:
I have sort of hit a dead end. Can someone please help.
I have never used libwebsockets before. I have an RPI4(Installed Ubuntu 22.04), where my code is running which tries to ping my Laptop(Windows 10). Both are on same Wi-Fi network. I am able to Ping each other through command prompt, however through code it throws an error CLIENT_CONNECTION_ERROR.
Same code works properly on Ubuntu 20.04 running on x86_64 Virtual Box.
However it does not work when we run it on an RPI4.
Here's the error log:

[2022/12/18 14:52:36:0612] N: lws_create_context: LWS: 4.3.99-v4.3.0-275-gec6d5ac6, NET CLI SRV H1 H2 WS SS-JSON-POL ConMon IPv6-absent
[2022/12/18 14:52:36:0716] N: __lws_lc_tag:  ++ [wsi|0|pipe] (1)
[2022/12/18 14:52:36:0758] N: __lws_lc_tag:  ++ [vh|0|netlink] (1)
[2022/12/18 14:52:36:0781] N: __lws_lc_tag:  ++ [vh|1|default||-1] (2)
[2022/12/18 14:52:36:0845] N: lws_tls_client_create_vhost_context: doing cert filepath
[2022/12/18 14:52:36:0895] N: HttpPing: connecting to 192.168.1.4:7778
[2022/12/18 14:52:36:0905] N: __lws_lc_tag:  ++ [wsicli|0|GET/h1/default/192.168.1.4] (1)
[2022/12/18 14:52:36:0907] N: [wsicli|0|GET/h1/default/192.168.1.4]: lws_client_connect_3_connect: trying 192.168.1.4
CLIENT_CONNECTION_ERROR: Unable to connect
[2022/12/18 14:52:38:0927] N: __lws_lc_untag:  -- [wsicli|0|GET/h1/default/192.168.1.4] (0) 2.002s
[2022/12/18 14:52:38:0932] N: __lws_lc_untag:  -- [wsi|0|pipe] (0) 2.021s
[2022/12/18 14:52:38:0933] N: __lws_lc_untag:  -- [vh|0|netlink] (1) 2.017s
[2022/12/18 14:52:38:0934] N: __lws_lc_untag:  -- [vh|1|default||-1] (0) 2.015s

Things tried:

Disabled IPV6 while compiling libwebsockets by using the command -> cmake .. -DLWS_IPV6=OFF

Turned off Firewall on ubuntu


问:
Can we use a clustering algorithm to cluster stackoverflow post.xml data dump?
I'm trying to group question posts in Stackoverflow post.xml data dump into their relavant programming language (ex: classify java question posts into java class). We can do this using classification. But I want to use clustering for this. Will it be possible to use clustering? If it is possible How? (My final objective is to cluster posts based on their programming language and predict trending programming languages)

So far I have preprocessed the stackoverflow posts.xml data and ready to cluster. Text preprocessing part is completed.


问:
Libvirt error when trying to pass through radeon graphics to kvm
guestslibvirt.libvirtError: internal error: Non-endpoint PCI devices cannot be assigned to guests

Have tried multiple different things to try and assign Radeon graphics to me but nothing has seemed to work.


问:
Firebase Messaging - Validate incoming background messages based on user logged in
I'm creating a chat app (kind of WhatsApp-like messaging) using Flutter.
First, the notifications mechanism is working as intended, whenever I send a message from 1 device to another device, the notification would pop up.

I created a local_notification_service.dart to handle the foreground notification & sending a not

```<code>import 'dart:math';
import 'package:get/get.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';

class LocalNotificationService extends GetConnect {
  String serverKey ='xxxxxxxxxxxxxxxxxxxx'
  static final FlutterLocalNotificationsPlugin _flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();

  static void initialize() {
    const InitializationSettings initializationSettings = InitializationSettings(android: AndroidInitializationSettings("@mipmap/ic_launcher"));
    _flutterLocalNotificationsPlugin.initialize(initializationSettings);
  }

  static void display(RemoteMessage message) async {
    try {
      print("Display notification");
      // int id = DateTime.now().microsecondsSinceEpoch ~/1000000;
      Random random = Random();
      int id = random.nextInt(1000);
      const NotificationDetails notificationDetails = NotificationDetails(
          android: AndroidNotificationDetails(
        "mychanel",
        "my chanel",
        importance: Importance.max,
        priority: Priority.high,
      ));
      print("my id is ${id.toString()}");
      await _flutterLocalNotificationsPlugin.show(
        id,
        message.notification!.title,
        message.notification!.body,
        notificationDetails,
      );
    } on Exception catch (e) {
      print('Error>>>$e');
    }
  }

  Future<void> sendNotification({
    String? title,
    String? message,
    String? token,
    String? uniqueId,
    String? action,
    String? channelId,
    String? channelName,
    String? channelDesc,
  }) async {
    final data = {
      "click_action": "FLUTTER_NOTIFICATION_CLICK",
      "action": action,
      "uniqueId": uniqueId,
      "message": message,
      "channelId": channelId ?? 'my channel id',
      "channelName": channelName ?? 'my channel Name',
      "channelDesc": channelDesc ?? 'my channel description',
    };

    try {
      final response = await post(
        'https://fcm.googleapis.com/fcm/send',
        {
          'notification': {'title': title, 'body': message},
          'priority': 'high',
          'data': data,
          'to': '$token',
          'direct_boot_ok': true,
        },
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'key=$serverKey',
        },
      );
      print('response body : ${response.body}');
    } catch (e) {}
  }
}
</code>```

Then, I'm trying to validate the users in my flutter application whenever they receive FCM notification, here's the logic that I want to create:

If the user is not logged in, then the device could not receive the notification

If the user is logged in, but the specific user is not eligible to receive the message (in case there are some users with the same FCM token / device registered ) then the device could not receive the notification. I would want to solve this after the point number 1 is succeeded

Here's my main.dart file

```<code>void main() async {
  await GetStorage.init();

  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
  GlobalController globalC = Get.put(GlobalController());
  AuthController authC = Get.put(AuthController());
  ErrorController errorC = Get.put(ErrorController());
  ConnectivityResult connectivityResult = ConnectivityResult.none;
  final Connectivity connectivity = Connectivity();
  connectivityResult = await connectivity.checkConnectivity();

  if (connectivityResult == ConnectivityResult.wifi || connectivityResult == ConnectivityResult.mobile) {
    // Start FCM
    final fcmToken = await FirebaseMessaging.instance.getToken();
    globalC.fcmToken.value = fcmToken ?? ''; //set global fcm Token
    final FirebaseMessaging fcmInstance = FirebaseMessaging.instance;

    NotificationSettings settings = await fcmInstance.requestPermission(
      alert: true,
      announcement: true,
      badge: true,
      carPlay: false,
      criticalAlert: false,
      provisional: false,
      sound: true,
    );

    await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(
      alert: true,
      badge: true,
      sound: true,
    );

    /* Handle message when in foreground */
    FirebaseMessaging.onMessage.listen((event) {
      if (globalC.isAuthenticated.isTrue) {
        LocalNotificationService.display(event); //display notification
      }
    });

    /* Handle message when in background */
    if (globalC.isAuthenticated.isTrue) {
      FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
    }

    fcmInstance.onTokenRefresh.listen((fcmToken) {

      // Note: This callback is fired at each app startup and whenever a new
      // token is generated.
    }).onError((err) {
      // Error getting token.
    });
    // End FCM
  }

  FirebaseAnalytics analytics = FirebaseAnalytics.instance;

  runApp(MyApp());
}
</code>```

as you can see, I'm trying to filter the non logged in user when in the foreground using the FirebaseMessaging.onMessage.listen with the  globalC.isAuthenticated.isTrue validation. And it works (because the default of globalC.isAuthenticated is false whenever user is not logged in)

But for the FirebaseMessaging.onBackgroundMessage function does not seems to work with the validation. I've tried to search for the solution in the documentations, youtube but i couldn't find it till this question is made.

How can I make this kind of validation for background message?

Sorry for this newbie question, any help would be greatly appreciated.

Thank you .

Body:
I'm creating a chat app (kind of WhatsApp-like messaging) using Flutter.
First, the notifications mechanism is working as intended, whenever I send a message from 1 device to another device, the notification would pop up.

I created a local_notification_service.dart to handle the foreground notification & sending a not

import 'dart:math';
import 'package:get/get.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';

class LocalNotificationService extends GetConnect {
  String serverKey ='xxxxxxxxxxxxxxxxxxxx'
  static final FlutterLocalNotificationsPlugin _flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();

  static void initialize() {
    const InitializationSettings initializationSettings = InitializationSettings(android: AndroidInitializationSettings("@mipmap/ic_launcher"));
    _flutterLocalNotificationsPlugin.initialize(initializationSettings);
  }

  static void display(RemoteMessage message) async {
    try {
      print("Display notification");
      // int id = DateTime.now().microsecondsSinceEpoch ~/1000000;
      Random random = Random();
      int id = random.nextInt(1000);
      const NotificationDetails notificationDetails = NotificationDetails(
          android: AndroidNotificationDetails(
        "mychanel",
        "my chanel",
        importance: Importance.max,
        priority: Priority.high,
      ));
      print("my id is ${id.toString()}");
      await _flutterLocalNotificationsPlugin.show(
        id,
        message.notification!.title,
        message.notification!.body,
        notificationDetails,
      );
    } on Exception catch (e) {
      print('Error>>>$e');
    }
  }

  Future<void> sendNotification({
    String? title,
    String? message,
    String? token,
    String? uniqueId,
    String? action,
    String? channelId,
    String? channelName,
    String? channelDesc,
  }) async {
    final data = {
      "click_action": "FLUTTER_NOTIFICATION_CLICK",
      "action": action,
      "uniqueId": uniqueId,
      "message": message,
      "channelId": channelId ?? 'my channel id',
      "channelName": channelName ?? 'my channel Name',
      "channelDesc": channelDesc ?? 'my channel description',
    };

    try {
      final response = await post(
        'https://fcm.googleapis.com/fcm/send',
        {
          'notification': {'title': title, 'body': message},
          'priority': 'high',
          'data': data,
          'to': '$token',
          'direct_boot_ok': true,
        },
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'key=$serverKey',
        },
      );
      print('response body : ${response.body}');
    } catch (e) {}
  }
}

Then, I'm trying to validate the users in my flutter application whenever they receive FCM notification, here's the logic that I want to create:

If the user is not logged in, then the device could not receive the notification

If the user is logged in, but the specific user is not eligible to receive the message (in case there are some users with the same FCM token / device registered ) then the device could not receive the notification. I would want to solve this after the point number 1 is succeeded

Here's my main.dart file

void main() async {
  await GetStorage.init();

  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
  GlobalController globalC = Get.put(GlobalController());
  AuthController authC = Get.put(AuthController());
  ErrorController errorC = Get.put(ErrorController());
  ConnectivityResult connectivityResult = ConnectivityResult.none;
  final Connectivity connectivity = Connectivity();
  connectivityResult = await connectivity.checkConnectivity();

  if (connectivityResult == ConnectivityResult.wifi || connectivityResult == ConnectivityResult.mobile) {
    // Start FCM
    final fcmToken = await FirebaseMessaging.instance.getToken();
    globalC.fcmToken.value = fcmToken ?? ''; //set global fcm Token
    final FirebaseMessaging fcmInstance = FirebaseMessaging.instance;

    NotificationSettings settings = await fcmInstance.requestPermission(
      alert: true,
      announcement: true,
      badge: true,
      carPlay: false,
      criticalAlert: false,
      provisional: false,
      sound: true,
    );

    await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(
      alert: true,
      badge: true,
      sound: true,
    );

    /* Handle message when in foreground */
    FirebaseMessaging.onMessage.listen((event) {
      if (globalC.isAuthenticated.isTrue) {
        LocalNotificationService.display(event); //display notification
      }
    });

    /* Handle message when in background */
    if (globalC.isAuthenticated.isTrue) {
      FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
    }

    fcmInstance.onTokenRefresh.listen((fcmToken) {

      // Note: This callback is fired at each app startup and whenever a new
      // token is generated.
    }).onError((err) {
      // Error getting token.
    });
    // End FCM
  }

  FirebaseAnalytics analytics = FirebaseAnalytics.instance;

  runApp(MyApp());
}

as you can see, I'm trying to filter the non logged in user when in the foreground using the FirebaseMessaging.onMessage.listen with the  globalC.isAuthenticated.isTrue validation. And it works (because the default of globalC.isAuthenticated is false whenever user is not logged in)

But for the FirebaseMessaging.onBackgroundMessage function does not seems to work with the validation. I've tried to search for the solution in the documentations, youtube but i couldn't find it till this question is made.

How can I make this kind of validation for background message?

Sorry for this newbie question, any help would be greatly appreciated.

Thank you .


问:
Cypress V11 failing to start in Jenkins
```<code>[STARTED] Task without title.
[FAILED] Cypress failed to start.
[FAILED]
[FAILED] This may be due to a missing library or dependency. https://on.cypress.io/required-dependencies
[FAILED]
[FAILED] Please refer to the error below for more details.
[FAILED]
[FAILED] ----------
[FAILED]
[FAILED] Command was killed with SIGSEGV (Segmentation fault): /root/.cache/Cypress/11.2.0/Cypress/Cypress --no-sandbox --smoke-test --ping=265
[FAILED]
[FAILED] ----------
[FAILED]
[FAILED] Platform: linux-arm64 (Debian - 11.4)
[FAILED] Cypress Version: 11.2.0
Cypress failed to start.
</code>```

Versions: Cypress: 11.2.0
Node: 18.9.0
Debian: 11.4 (arm64)
React: 17.0.2

This is working locally in docker but fails in my Jenkins pipeline. Both are running identical commands.

Title: Cypress V11 failing to start in Jenkins

Body:
[STARTED] Task without title.
[FAILED] Cypress failed to start.
[FAILED]
[FAILED] This may be due to a missing library or dependency. https://on.cypress.io/required-dependencies
[FAILED]
[FAILED] Please refer to the error below for more details.
[FAILED]
[FAILED] ----------
[FAILED]
[FAILED] Command was killed with SIGSEGV (Segmentation fault): /root/.cache/Cypress/11.2.0/Cypress/Cypress --no-sandbox --smoke-test --ping=265
[FAILED]
[FAILED] ----------
[FAILED]
[FAILED] Platform: linux-arm64 (Debian - 11.4)
[FAILED] Cypress Version: 11.2.0
Cypress failed to start.

Versions: Cypress: 11.2.0
Node: 18.9.0
Debian: 11.4 (arm64)
React: 17.0.2

This is working locally in docker but fails in my Jenkins pipeline. Both are running identical commands.


问:
Is it possible to consume OAuth bearer token generated from UseOAuthAuthorizationServer in ASP.NET 6 natively?
I have a legacy ASP.NET Framework 4.7 application that is providing OAuth bearer tokens using OWIN and IAppBuilder.UseOAuthAuthorizationServer.  Elsewhere in our ecosystem we consume those tokens via .NET Framework apps, OWIN, and IAppBuilder.UseOAuthBearerAuthentication.  I believe the encryption keys are handled for this currently using web.config file <machineKey /> elements with keys set and synced on each host.

I am working on a new ASP.NET web application, in .NET 6.  Is it possible to consume these same bearer tokens out of the box in the new .NET?

From what I've read the original UseOAuthBearerAuthentication is not ported to .NET Core.  I've run across some posts implying that I might be able to use AuthenticationBuilder.AddJwtBearer in my Program.cs to still consume OAuth tokens, but am not finding a lot in the way of examples on how that works.  I sort of wonder if I have a way to set the machineKey values in .NET Core that are being used in the .NET Framework applications, that might help things work, too.  I've come across a handful of nuget packages that sound like they might provide what I'm looking for as well, but most don't seem to be currently maintained or involve setting up other 3rd party applications to support, too.

Is there any native support for what I'm trying to do?