问:
How to implement an (auto) Logout feature in MAUI?
I have another question, please.

I have a shell-based navigation:

```<code><Shell ...
    <Shell.Items>
        <ShellContent x:Name="Login" ContentTemplate="{DataTemplate Login:Login}" Route="Login" Shell.FlyoutBehavior="Disabled" Shell.NavBarIsVisible="False" ></ShellContent>
    </Shell.Items>

    <TabBar Route="Login">
        <ShellContent ContentTemplate="{DataTemplate Login:Login}" Shell.FlyoutBehavior="Disabled" Shell.NavBarIsVisible="False" ></ShellContent>
    </TabBar>

    <TabBar x:Name="MyTabBar" Shell.NavBarHasShadow="true" Route="Home">
        <Tab Title="Tab1" ... >
            <ShellContent Title="Page1"
            </ShellContent>
            <ShellContent Title="Page2"
            </ShellContent>
        </Tab>

        <Tab Title="Tab2" ... >
            <ShellContent Title="Page3"
            </ShellContent>
            <ShellContent Title="Page4"
            </ShellContent>
        </Tab>

        <Tab Title="Tab3"... >
            <ShellContent Title="Page5"
            </ShellContent>
        </Tab>
    </TabBar>
</Shell>
</code>```

I need to implement a Logout feature.

If I create a Flyout containing just this Logout button I am afraid that it won't be at all visible or intuitive or obvious for the users.

I would like to set it up in some linkButton residing to the right of my TabBar, thus showing, for instance,
Page1 Page2         Logout
and
Page3 Page4         Logout
and
Page5               Logout

but unfortunately I do not know how to insert a button there.

I could maybe set it up it on the last page, Page5, somwehere (that's what I've been told to do by my manager - I do not agree with that position - again, it's not at all obvious).

But no matter where I set this button, I don't know how to clear the nav history (to kill that back arrow).

I have tried to write this code on that button:

```<code>[RelayCommand]
        private static async void Logout()
        {
            try
            {
                Globals.loginStatus = Globals.LoginStatus.loginRefused;
                await Shell.Current.Navigation.PopToRootAsync();
                await Shell.Current.GoToAsync(nameof(Login), true);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Unable to logout: {ex.Message}");
                Utils.ErrorHandling.HandleError(ex);
            }
        }
</code>```

together with this (in Shell.cs):

```<code>protected override void OnNavigating(ShellNavigatingEventArgs args)
{
    base.OnNavigating(args);

    // Cancel any back navigation.
    if (args.Source == ShellNavigationSource.Pop)
    {
        args.Cancel();
    }
}
</code>```

This does not do me any good - I can still see the Back arrow one the Login tab. I can also see the three tabs on the bottom: Tab1, Tab2, and Tab3, enabled, and I shouldn't be able to see those !

By reversing the order of the calls

```<code>[RelayCommand]
        private static async void Logout()
        {
            try
            {
                Globals.loginStatus = Globals.LoginStatus.loginRefused;
                await Shell.Current.GoToAsync(nameof(Login), true);
                await Shell.Current.Navigation.PopToRootAsync();
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Unable to logout: {ex.Message}");
                Utils.ErrorHandling.HandleError(ex);
            }
        }
</code>```

the result is even funnier: the app flip-flops between Page5 and Login.

So, my questions are:

Where should I set this Logout button up ? In the case there is a way to put it in the TabBar (my first choice), how ?

What do you think about putting it into some FlyOut on the Login page ?

What should I do to really kill the back navigation ? How could I also hide the TabBar items by code from this method in Page5 ?

I could maybe just say Application.Current.Quit(); but this is not quite elegant, is it ? Besides, this might not work in iOS.

Since this app works with sensitive data, I would like to write an auto-logout feature, to be executed after, say, one minute of inactivity. It's very simple to do this in Windows (using Windows api) but how would one do it in MAUI ?

Thank you !
Alex

Body:
I have another question, please.

I have a shell-based navigation:

<Shell ...
    <Shell.Items>
        <ShellContent x:Name="Login" ContentTemplate="{DataTemplate Login:Login}" Route="Login" Shell.FlyoutBehavior="Disabled" Shell.NavBarIsVisible="False" ></ShellContent>
    </Shell.Items>

    <TabBar Route="Login">
        <ShellContent ContentTemplate="{DataTemplate Login:Login}" Shell.FlyoutBehavior="Disabled" Shell.NavBarIsVisible="False" ></ShellContent>
    </TabBar>

    <TabBar x:Name="MyTabBar" Shell.NavBarHasShadow="true" Route="Home">
        <Tab Title="Tab1" ... >
            <ShellContent Title="Page1"
            </ShellContent>
            <ShellContent Title="Page2"
            </ShellContent>
        </Tab>

        <Tab Title="Tab2" ... >
            <ShellContent Title="Page3"
            </ShellContent>
            <ShellContent Title="Page4"
            </ShellContent>
        </Tab>

        <Tab Title="Tab3"... >
            <ShellContent Title="Page5"
            </ShellContent>
        </Tab>
    </TabBar>
</Shell>

I need to implement a Logout feature.

If I create a Flyout containing just this Logout button I am afraid that it won't be at all visible or intuitive or obvious for the users.

I would like to set it up in some linkButton residing to the right of my TabBar, thus showing, for instance,
Page1 Page2         Logout
and
Page3 Page4         Logout
and
Page5               Logout

but unfortunately I do not know how to insert a button there.

I could maybe set it up it on the last page, Page5, somwehere (that's what I've been told to do by my manager - I do not agree with that position - again, it's not at all obvious).

But no matter where I set this button, I don't know how to clear the nav history (to kill that back arrow).

I have tried to write this code on that button:

[RelayCommand]
        private static async void Logout()
        {
            try
            {
                Globals.loginStatus = Globals.LoginStatus.loginRefused;
                await Shell.Current.Navigation.PopToRootAsync();
                await Shell.Current.GoToAsync(nameof(Login), true);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Unable to logout: {ex.Message}");
                Utils.ErrorHandling.HandleError(ex);
            }
        }

together with this (in Shell.cs):

protected override void OnNavigating(ShellNavigatingEventArgs args)
{
    base.OnNavigating(args);

    // Cancel any back navigation.
    if (args.Source == ShellNavigationSource.Pop)
    {
        args.Cancel();
    }
}

This does not do me any good - I can still see the Back arrow one the Login tab. I can also see the three tabs on the bottom: Tab1, Tab2, and Tab3, enabled, and I shouldn't be able to see those !

By reversing the order of the calls

[RelayCommand]
        private static async void Logout()
        {
            try
            {
                Globals.loginStatus = Globals.LoginStatus.loginRefused;
                await Shell.Current.GoToAsync(nameof(Login), true);
                await Shell.Current.Navigation.PopToRootAsync();
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Unable to logout: {ex.Message}");
                Utils.ErrorHandling.HandleError(ex);
            }
        }

the result is even funnier: the app flip-flops between Page5 and Login.

So, my questions are:

Where should I set this Logout button up ? In the case there is a way to put it in the TabBar (my first choice), how ?

What do you think about putting it into some FlyOut on the Login page ?

What should I do to really kill the back navigation ? How could I also hide the TabBar items by code from this method in Page5 ?

I could maybe just say Application.Current.Quit(); but this is not quite elegant, is it ? Besides, this might not work in iOS.

Since this app works with sensitive data, I would like to write an auto-logout feature, to be executed after, say, one minute of inactivity. It's very simple to do this in Windows (using Windows api) but how would one do it in MAUI ?

Thank you !
Alex


来源: stackexchange

问:
Tensorflow : How to retrieve parts of my multi input Dataset and their respective loss?
First of all i am quite new regarding how AI and Tensorflow work.

My problem is the following : I need to train my neural network on 2 paired images. One that is unchanged and the same one that is transformed. This implies at the end a joint loss calculation of the paired images in order to calculate the mutual information for an unsupervised image analysis problem.

Also, since my dataset are 256*256 RGB images * 4 000 i need to use a data generator.

Here is an example of what i already did about my data generator:

```<code>class dataset(object):
    def __init__(self, data_list, batch_size):

        self.dataset = None

        self.batch_size = BATCH_SIZE
        self.current_batch = 0

        self.data_list  = data_list

        self.normal_image      = None
        self.transformed_image = None
        self.label             = None

    def generator(self):

        index =  self.current_batch * self.batch_size

        self.current_batch = self.current_batch + 1

        for image, label in self.data_list[index:]:

            self.label = label

            image = image / 255.0

            self.normal_image      = image
            self.transformed_image = utils.get_random_crop(image, height = 200, width = 200)

            yield ({'normal_image'      : self.normal_image,
                    'transformed_image' : self.transformed_image},
                   {'label'             : self.label})

    def data_loader(self):
        self.dataset = tf.data.Dataset.from_generator(self.generator,
                                                      output_types=(
                                                          {'normal_image'      : tf.float32,
                                                           'transformed_image' : tf.float32},
                                                          {'label'             : tf.int32})).batch(self.batch_size)

        return self.dataset

train_dataset = dataset(train_list, BATCH_SIZE)
test_dataset  = dataset(test_list, BATCH_SIZE)
</code>```

Note that train_list & test_list are just raw numpy arrays that i have retrieved from my images collection.

Here are my 2 questions :

How can i retrieve specifically the loss from my normal & transformed images so that i can do a joint loss calculation at the end of each epoch ?

I got my data generator(seems to work fine) each next() retrieve the next batch of my collection. However as you can see i have a (kind of ?) tuple inside of my dataset {normal_image, transformed_image}.
I am having a hard time to find how to access specifically one of those data inside of this (kind of ?) tuple in order to feed my CNN with the normal_imageand the transformed_image one at the time ect...

dataset.transformed_image would have been too good Haha !

Also, in my dataset class i have a self.normal_image & self.transformed_image but i use them only for plotting. They are not tensors... like in my dataset :(

Thanks for your time !

ContentLicense: CC BY-SA 4.0

Body:
First of all i am quite new regarding how AI and Tensorflow work.

My problem is the following : I need to train my neural network on 2 paired images. One that is unchanged and the same one that is transformed. This implies at the end a joint loss calculation of the paired images in order to calculate the mutual information for an unsupervised image analysis problem.

Also, since my dataset are 256*256 RGB images * 4 000 i need to use a data generator.

Here is an example of what i already did about my data generator:

class dataset(object):
    def __init__(self, data_list, batch_size):

        self.dataset = None

        self.batch_size = BATCH_SIZE
        self.current_batch = 0

        self.data_list  = data_list

        self.normal_image      = None
        self.transformed_image = None
        self.label             = None

    def generator(self):

        index =  self.current_batch * self.batch_size

        self.current_batch = self.current_batch + 1

        for image, label in self.data_list[index:]:

            self.label = label

            image = image / 255.0

            self.normal_image      = image
            self.transformed_image = utils.get_random_crop(image, height = 200, width = 200)

            yield ({'normal_image'      : self.normal_image,
                    'transformed_image' : self.transformed_image},
                   {'label'             : self.label})

    def data_loader(self):
        self.dataset = tf.data.Dataset.from_generator(self.generator,
                                                      output_types=(
                                                          {'normal_image'      : tf.float32,
                                                           'transformed_image' : tf.float32},
                                                          {'label'             : tf.int32})).batch(self.batch_size)

        return self.dataset

train_dataset = dataset(train_list, BATCH_SIZE)
test_dataset  = dataset(test_list, BATCH_SIZE)

Note that train_list & test_list are just raw numpy arrays that i have retrieved from my images collection.

Here are my 2 questions :

How can i retrieve specifically the loss from my normal & transformed images so that i can do a joint loss calculation at the end of each epoch ?

I got my data generator(seems to work fine) each next() retrieve the next batch of my collection. However as you can see i have a (kind of ?) tuple inside of my dataset {normal_image, transformed_image}.
I am having a hard time to find how to access specifically one of those data inside of this (kind of ?) tuple in order to feed my CNN with the normal_imageand the transformed_image one at the time ect...

dataset.transformed_image would have been too good Haha !

Also, in my dataset class i have a self.normal_image & self.transformed_image but i use them only for plotting. They are not tensors... like in my dataset :(

Thanks for your time !


问:
aws fallback option while fargate is scaling
Given that fargate takes a little while to spinup a new healthy container that takes requests, what's the best way to handle sudden spikes in traffic that require additional processing power?

I was thinking of using lambda as a fallback, BUT I haven't seen this mentioned as a "design pattern" anywhere AND for this to work every request would have to additionally go through a Step Function or something (?) that will switch to lambda - which cost wise might be really heavy.


问:
Run Azure IoT Python SDK on OpenWrt Router
I am trying to use azure iot python sdk for my small router, which uses OpenWrt OS. My question is, is there anyway to run python sdk for OpenWrt? And the router has only 6MB storage. I have tried with

pyinstaller to create a binary -> Too big binary

installed only necessary python package -> Also too big and too many python package muss go with.

tried to use azure iot c sdk with cross compiler -> Until now, it doesn't work for me because of my missing knowledge about cross compiler

I really would like to hear your advices.
Thanks


问:
App crashing while creating Dao object for room database
My app is crashing and the only thing I know for sure is that the main problem is this line ->

```<code>val placesDao = (application as HotspotBucketApp).placesDb.placesDao()
</code>```

can any one tell please me why is this happening.

```<code>private fun getPlaceList() {
    val placesDao = (application as HotspotBucketApp).placesDb.placesDao()
    lifecycleScope.launch {
        placesDao.fetchAllPlaces().collect {
            placeList = ArrayList(it)
        }
        if (placeList.isNotEmpty()) {
            lastId = placeList[placeList.size - 1].id
        }
    }
}
</code>```
```<code>class HotspotBucketApp: Application() {

    val placesDb by lazy {
        PlacesDatabase.getInstance(this)
    }
}
</code>```
```<code>@Dao
interface PlacesDao {

    @Query("select * from `placesTable`")
    fun fetchAllPlaces(): Flow<List<PlaceEntity>>

    @Insert
    suspend fun insert(placeEntity: PlaceEntity)

    @Delete
    suspend fun delete(placeEntity: PlaceEntity)
}
</code>```
```<code>@Database(entities = [PlaceEntity::class], version = 1)
abstract class PlacesDatabase: RoomDatabase() {

    abstract fun placesDao(): PlacesDao

    companion object {
        @Volatile
        private var INSTANCE: PlacesDatabase? = null
        private const val PLACES_DB_NAME = "place_database"

        fun getInstance(context: Context): PlacesDatabase {
            synchronized(this) {
                var instance = INSTANCE
                if (instance == null) {
                    instance = Room.databaseBuilder(context.applicationContext, PlacesDatabase::class.java, PLACES_DB_NAME)
                        .fallbackToDestructiveMigration()
                        .build()
                    INSTANCE = instance
                }

                return instance
            }
        }
    }
}
</code>```
```<code>@Entity(tableName = "placesTable")
data class PlaceEntity(
    @PrimaryKey
    val id: Int,
    val title: String,
    val image: String,
    val description: String,
    val date: String,
    val location: String,
    val latitude: Double,
    val longitude: Double
)
</code>```
```<code>override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    binding = ActivityMainBinding.inflate(layoutInflater)
    setContentView(binding?.root)

    setSupportActionBar(binding?.addPlacesToolBar)
    if (Build.VERSION.SDK_INT >= 33) {
        onBackInvokedDispatcher.registerOnBackInvokedCallback(
            OnBackInvokedDispatcher.PRIORITY_DEFAULT
        ) {
            finish()
        }
    } else {
        onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                finish()
            }
        })
    }

    getPlaceList()

    binding?.fABAddPlaces?.setOnClickListener {
        val intent = Intent(this, AddPlaceActivity::class.java)
        intent.putExtra("lats_place_id", lastId)
        startActivity(intent)
    }

}
</code>```

Body:
My app is crashing and the only thing I know for sure is that the main problem is this line ->

val placesDao = (application as HotspotBucketApp).placesDb.placesDao()

can any one tell please me why is this happening.

private fun getPlaceList() {
    val placesDao = (application as HotspotBucketApp).placesDb.placesDao()
    lifecycleScope.launch {
        placesDao.fetchAllPlaces().collect {
            placeList = ArrayList(it)
        }
        if (placeList.isNotEmpty()) {
            lastId = placeList[placeList.size - 1].id
        }
    }
}

class HotspotBucketApp: Application() {

    val placesDb by lazy {
        PlacesDatabase.getInstance(this)
    }
}

@Dao
interface PlacesDao {

    @Query("select * from `placesTable`")
    fun fetchAllPlaces(): Flow<List<PlaceEntity>>

    @Insert
    suspend fun insert(placeEntity: PlaceEntity)

    @Delete
    suspend fun delete(placeEntity: PlaceEntity)
}

@Database(entities = [PlaceEntity::class], version = 1)
abstract class PlacesDatabase: RoomDatabase() {

    abstract fun placesDao(): PlacesDao

    companion object {
        @Volatile
        private var INSTANCE: PlacesDatabase? = null
        private const val PLACES_DB_NAME = "place_database"

        fun getInstance(context: Context): PlacesDatabase {
            synchronized(this) {
                var instance = INSTANCE
                if (instance == null) {
                    instance = Room.databaseBuilder(context.applicationContext, PlacesDatabase::class.java, PLACES_DB_NAME)
                        .fallbackToDestructiveMigration()
                        .build()
                    INSTANCE = instance
                }

                return instance
            }
        }
    }
}

@Entity(tableName = "placesTable")
data class PlaceEntity(
    @PrimaryKey
    val id: Int,
    val title: String,
    val image: String,
    val description: String,
    val date: String,
    val location: String,
    val latitude: Double,
    val longitude: Double
)

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    binding = ActivityMainBinding.inflate(layoutInflater)
    setContentView(binding?.root)

    setSupportActionBar(binding?.addPlacesToolBar)
    if (Build.VERSION.SDK_INT >= 33) {
        onBackInvokedDispatcher.registerOnBackInvokedCallback(
            OnBackInvokedDispatcher.PRIORITY_DEFAULT
        ) {
            finish()
        }
    } else {
        onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                finish()
            }
        })
    }

    getPlaceList()

    binding?.fABAddPlaces?.setOnClickListener {
        val intent = Intent(this, AddPlaceActivity::class.java)
        intent.putExtra("lats_place_id", lastId)
        startActivity(intent)
    }

}


问:
While running command nerdctl run after building an image getting error : Starting the development server... node:
I tried to add system variable path for powershell but it is same as it is. I think its error related to powershell but not sure about
Starting the development server...  node:
this.events:491

throw er; // Unhandled 'error' event       ^  Error: spawn /mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe ENOENT        at ChildProcess._handle.onexit (n

```<code>Starting the development server...

node:events:491
      throw er; // Unhandled 'error' event
      ^

Error: spawn /mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe ENOENT
    at ChildProcess._handle.onexit (node:internal/child_process:285:19)
    at onErrorNT (node:internal/child_process:483:16)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21)
</code>```

Body:
I tried to add system variable path for powershell but it is same as it is. I think its error related to powershell but not sure about
Starting the development server...  node:
this.events:491

throw er; // Unhandled 'error' event       ^  Error: spawn /mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe ENOENT        at ChildProcess._handle.onexit (n

Starting the development server...

node:events:491
      throw er; // Unhandled 'error' event
      ^

Error: spawn /mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe ENOENT
    at ChildProcess._handle.onexit (node:internal/child_process:285:19)
    at onErrorNT (node:internal/child_process:483:16)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21)


问:
poetry install fail build with private dependency
I have a module that depends on another module (module_a) stored in my private repository (nexus) that reuqest another module (module_b) at build time, even stored in the private repository.

I add repository source on poetry.toml in order to add my private repo.

```<code>[[tool.poetry.source]]
name = "nexus"
url = "https://my_nexus_url/private_repo/simple"
secondary = true
</code>```

Then I specify the dependency on th toml

```<code>[tool.poetry.dependencies]
python = ">=3.9.0,<3.11,"
module_a="1.0.0"
</code>```

When I run poetry install it download module_a and build it. During the build process I get this error:

```<code> ERROR: Could not find a version that satisfies the requirement module_b==1.0.1
 ERROR: No matching distribution found for module_b==1.0.1
</code>```

When I try to install the module using pip with --extra-index-url <my repo> everything works fine.

```<code>pip install module_a --extra-index-url https://my_nexus_url/private_repo/simple
</code>```

I guess that the problem is releted on the pip command, executed by poetry. It dose not specify the extra-index-url that point to my repo so it try to download dependency (module_b) from pypi repository instead from my repo.

There is a way to instruct poetry in order to use my private repo when source build is required?

I have already try with this:

```<code>[tool.poetry.dependencies]
python = ">=3.9.0,<3.11,"
module_b={version="1.0.1", source="nexus"}
module_a={version="1.0.0", source="nexus"}
</code>```

without any success.

Body:
I have a module that depends on another module (module_a) stored in my private repository (nexus) that reuqest another module (module_b) at build time, even stored in the private repository.

I add repository source on poetry.toml in order to add my private repo.

[[tool.poetry.source]]
name = "nexus"
url = "https://my_nexus_url/private_repo/simple"
secondary = true

Then I specify the dependency on th toml

[tool.poetry.dependencies]
python = ">=3.9.0,<3.11,"
module_a="1.0.0"

When I run poetry install it download module_a and build it. During the build process I get this error:

 ERROR: Could not find a version that satisfies the requirement module_b==1.0.1
 ERROR: No matching distribution found for module_b==1.0.1

When I try to install the module using pip with --extra-index-url <my repo> everything works fine.

pip install module_a --extra-index-url https://my_nexus_url/private_repo/simple

I guess that the problem is releted on the pip command, executed by poetry. It dose not specify the extra-index-url that point to my repo so it try to download dependency (module_b) from pypi repository instead from my repo.

There is a way to instruct poetry in order to use my private repo when source build is required?

I have already try with this:

[tool.poetry.dependencies]
python = ">=3.9.0,<3.11,"
module_b={version="1.0.1", source="nexus"}
module_a={version="1.0.0", source="nexus"}

without any success.


问:
(Android) How do you get App start up time without parsing logs?
My goal is to get the amount of time it takes for apps/services to start but I don't want to have to parse the logs for each app/service.</p>


问:
Why Blazor with Radzen doesn't have the same behavior in podman container?
I've been working with Blazor Server Side for a while without any problem, using Radzen Blazor nuget for the UI. The problem came when I realize that Blazor doesn't have the same behavior with some Radzen components when is deployed in a podman container.

The TreeView component doesn't work properly in the pdoman container, but locally it works fine, even in Release mode and using the same database.

In short, the problem is that the TreeView has a property that lets you to enable checkboxes in each item, but in the first component render all those checkboxes are checked, even when some of them aren't. (This only happens in the podman container).

Unlike as I mentioned above, locally it works fine, checked and unchecked checkboxes are marked as they should be. I'm not able to reproduce that bug locally, and my mind is about to explode.

I did some tests and I realize that the same image used with a docker container have the right beahvior.

My Machine (Windows) => App Image => Docker Container => Works fine!

My Machine (Windows) => Same Code => Debug Release => Works fine!

Development Environment (Linux) => App Image => Podman Container => Buggg!

Additionally, I have to say that the image is made using docker and later is passed to the development environment (it's a remote server with linux) to be run with podman.

I'm using .NET6 and all nuget packages are up to date.

This is the dockerfile:

```<code>#Build Stage
FROM mcr.microsoft.com/dotnet/sdk:6.0-focal as build
WORKDIR /source
COPY . .
RUN chmod -R 777 /source
RUN dotnet restore "./Website/Website.csproj"
RUN dotnet publish "./Website/Website.csproj" -c release -o /bpms --no-restore

#Server Stage
FROM mcr.microsoft.com/dotnet/aspnet:6.0-focal
WORKDIR /app
COPY --from=build /bpms ./
EXPOSE 4000/tcp
RUN sed -i -e '1s/^/openssl_conf = default_conf\n/' -e '$a[default_conf]\nssl_conf = ssl_sect\n\n[ssl_sect]\nsystem_default = ssl_default_sect\n\n[ssl_default_sect]\nMinProtocol = TLSv1.2\nCipherString = DEFAULT:@SECLEVEL=0' /etc/ssl/openssl.cnf
RUN apt-get update
RUN apt-get install -yq tzdata
RUN ln -fs /usr/share/zoneinfo/America/Argentina/Buenos_Aires /etc/localtime
RUN dpkg-reconfigure -f noninteractive tzdata
ENV TZ="America/Argentina/Buenos_Aires"
ENTRYPOINT ["dotnet", "Website.dll"]
</code>```

Body:
I've been working with Blazor Server Side for a while without any problem, using Radzen Blazor nuget for the UI. The problem came when I realize that Blazor doesn't have the same behavior with some Radzen components when is deployed in a podman container.

The TreeView component doesn't work properly in the pdoman container, but locally it works fine, even in Release mode and using the same database.

In short, the problem is that the TreeView has a property that lets you to enable checkboxes in each item, but in the first component render all those checkboxes are checked, even when some of them aren't. (This only happens in the podman container).

Unlike as I mentioned above, locally it works fine, checked and unchecked checkboxes are marked as they should be. I'm not able to reproduce that bug locally, and my mind is about to explode.

I did some tests and I realize that the same image used with a docker container have the right beahvior.

My Machine (Windows) => App Image => Docker Container => Works fine!

My Machine (Windows) => Same Code => Debug Release => Works fine!

Development Environment (Linux) => App Image => Podman Container => Buggg!

Additionally, I have to say that the image is made using docker and later is passed to the development environment (it's a remote server with linux) to be run with podman.

I'm using .NET6 and all nuget packages are up to date.

This is the dockerfile:

#Build Stage
FROM mcr.microsoft.com/dotnet/sdk:6.0-focal as build
WORKDIR /source
COPY . .
RUN chmod -R 777 /source
RUN dotnet restore "./Website/Website.csproj"
RUN dotnet publish "./Website/Website.csproj" -c release -o /bpms --no-restore

#Server Stage
FROM mcr.microsoft.com/dotnet/aspnet:6.0-focal
WORKDIR /app
COPY --from=build /bpms ./
EXPOSE 4000/tcp
RUN sed -i -e '1s/^/openssl_conf = default_conf\n/' -e '$a[default_conf]\nssl_conf = ssl_sect\n\n[ssl_sect]\nsystem_default = ssl_default_sect\n\n[ssl_default_sect]\nMinProtocol = TLSv1.2\nCipherString = DEFAULT:@SECLEVEL=0' /etc/ssl/openssl.cnf
RUN apt-get update
RUN apt-get install -yq tzdata
RUN ln -fs /usr/share/zoneinfo/America/Argentina/Buenos_Aires /etc/localtime
RUN dpkg-reconfigure -f noninteractive tzdata
ENV TZ="America/Argentina/Buenos_Aires"
ENTRYPOINT ["dotnet", "Website.dll"]


问:
Is adding fields in a nested protobuf message backwards compatible?
I have a protobuf message roughly like this:

```<code>syntax = "proto3";
package state;

message Version
{
  uint32 major = 1;
  uint32 minor = 2;
  uint32 fix = 3;
}

message Parameters
{
  optional int32 a = 1;
  optional int32 b = 2;
  optional bool c = 3;
  optional float d = 4;
}

/** A simple tree data structure to hold some state information */
message Tree
{
  /** All state value attributes for this node, as a name/value pair map */
  map<string, bytes> attributes = 1;

  /** All child state trees as a child id / Tree pair map */
  map<string, Tree> child_trees = 2;
}

message State
{
  string product_name = 1;
  Version product_version = 2;

  Parameters parameters = 3;

  Tree state_tree_a = 4;
  Tree state_tree_b = 5;
}
</code>```

This is already used in shipped software. Now we would like to add further optional fields to the Parameters message (all of them either bool, int or float). This has to be backwards compatible, e.g. a new version of the software should be able to parse a State message written with the older version, where there were less entries in the nested Parameters message. The messages are serialised in C++ via SerializeToArray and restored via ParseFromArray.

I did some tests and this seems to work without problems. Extending the Parameters message did not break the readability of the Tree messages after it and fields not defined in the first version just returned false when checked for existence.

But I won't rely on this limiting amount of try and error testing for shipping code, so I'd like to find some documentation on wether this should be safe by design or if it just worked by pure luck in my tests or only under certain circumstances. In this case, it would be completely okay for me if it worked in a C++ context only.

From my understanding, the Updating A Message Type section from the proto3 language guide does not give a clear answer wether it is safe or not to extend a message which sits nested in the middle of another message without risking to invalidate the data located behind it. But I might be overlooking something or getting something wrong from the documentation. Can anyone point me to a clearly documented answer to my question?

Body:
I have a protobuf message roughly like this:

syntax = "proto3";
package state;

message Version
{
  uint32 major = 1;
  uint32 minor = 2;
  uint32 fix = 3;
}

message Parameters
{
  optional int32 a = 1;
  optional int32 b = 2;
  optional bool c = 3;
  optional float d = 4;
}

/** A simple tree data structure to hold some state information */
message Tree
{
  /** All state value attributes for this node, as a name/value pair map */
  map<string, bytes> attributes = 1;

  /** All child state trees as a child id / Tree pair map */
  map<string, Tree> child_trees = 2;
}

message State
{
  string product_name = 1;
  Version product_version = 2;

  Parameters parameters = 3;

  Tree state_tree_a = 4;
  Tree state_tree_b = 5;
}

This is already used in shipped software. Now we would like to add further optional fields to the Parameters message (all of them either bool, int or float). This has to be backwards compatible, e.g. a new version of the software should be able to parse a State message written with the older version, where there were less entries in the nested Parameters message. The messages are serialised in C++ via SerializeToArray and restored via ParseFromArray.

I did some tests and this seems to work without problems. Extending the Parameters message did not break the readability of the Tree messages after it and fields not defined in the first version just returned false when checked for existence.

But I won't rely on this limiting amount of try and error testing for shipping code, so I'd like to find some documentation on wether this should be safe by design or if it just worked by pure luck in my tests or only under certain circumstances. In this case, it would be completely okay for me if it worked in a C++ context only.

From my understanding, the Updating A Message Type section from the proto3 language guide does not give a clear answer wether it is safe or not to extend a message which sits nested in the middle of another message without risking to invalidate the data located behind it. But I might be overlooking something or getting something wrong from the documentation. Can anyone point me to a clearly documented answer to my question?


问:
node-red reading modbus poll rate weird behavior - debug node gets updated at random
I have a temperature and humidity ModBus RTU sensor connected to data acquisition module which runs node-red, both devices are connected using ModBus RTU.

I'm currently trying to read the temperature and humidity data on the module using the modbus nodes.

I've set a polling rate of 1000 ms to fetch the sensor data each 1 second, and according to the device's TX and RX LEDs, the data is actually being fetched each 1 seconds, since the LEDs on the data acquisition module blinks with this same period. So this leads me to believe that my configuration is done correctly.

According to what I said above, since data is being fetched each 1 second, I'd expect to see both, the debug node and modbus response node, being updated with the sensor data at this same pace, that is, 1 second, however that is not the case, the said nodes, get their data updated almost at random intervals.

The following screenshot shows the entries for the debug node since the time when I began writing this post:

Notice that I deployed the flow at 10:06:08, then data was fetched again at intervals of 3 minutes, then, it went at random pace.

As far as I understand, the debug node should get updated at the same polling rate as the modbus read node, which is 1000 ms.

Am I wrong in my line of thoughts?

This is my flow:

I've configured the ModBus server as follows:

And the following is the configuration for the ModBus Read node for temperature measurement.

Notice from the second picture, that I've also added inject, function and ModBus Flex Getter nodes in order to manually trigger the measurement. So when I click on the Inject node, a reading should be issued. This actually happens since each time that I click on the inject node, the device's TX and RX LEDs blinks, So I'd expect to see some readings on the debug node and the ModBus response node, but that is not the case, even though I know the reading is being performed, the data is not shown.


问:
Log4net in .net core, best way to make it send an email on level Error or higher?
Log4net in .net core 3.1+ webapi,

What is the best way to make it send an email on level Error or higher?

Currently I have an exception filter that catches unhandled excptions and emails them, but I like the .net way better


问:
beeline msck repair table returns Nonzero exit value 127
My script is

```<code> beeline <<EOF
 !connect -u jdbc:hive://someurl; principal=hive/someprincipal;set hive.msck.repair.batch.size=10000; msck repair table default.test_table sync partitions;
          EOF
</code>```

Script returns Nonzero exit value 127.
The problem is located at last part: msck repair table default.test_table sync partitions.

May be msck requires some more syntax inside beeline scripts?

Body:
My script is

 beeline <<EOF
 !connect -u jdbc:hive://someurl; principal=hive/someprincipal;set hive.msck.repair.batch.size=10000; msck repair table default.test_table sync partitions;
          EOF

Script returns Nonzero exit value 127.
The problem is located at last part: msck repair table default.test_table sync partitions.

May be msck requires some more syntax inside beeline scripts?


问:
web services error code 401 not authorized
I'm trying to retrieve information from a web service through an angular app, if I try from the browser everything is ok see image 200 OK if I try from angular I get a 401 no authorized.
Could anyone help me?

COMPONENT.TS

```<code>import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { MissioniService } from '../services/servizi/missioni.service';

@Component({
  selector: 'app-servizi',
  templateUrl: './servizi.component.html',
  styleUrls: \['./servizi.component.css'\]
})
export class ServiziComponent implements OnInit {
  obs:Observable<any>;

  constructor(private service:MissioniService) { }

  ngOnInit(): void {

  const host='https://username:password@xmlhostname.com/11428442.xml';

  //this.obs = this.service.request(host,{par : 1},'GET');
  this.obs = this.service.request(host,{},'GET');
    this.obs.subscribe((data:any) => {
      if(!data.error){

      }else{
        alert(data.error);
      }
    });
  }
}
</code>```

SERVICE.TS:

```<code>export class MissioniService {

  constructor(private http:HttpClient) { }

  request = (url:string, parameters:any, method:string): Observable <any>=> {
    return this.http.request(method, url, {
        headers: {
            'Content-Type': 'application/json'
        },
        params: parameters
    }).pipe(
        /*
          map((data)=>{}
        */
        catchError(error => {
            return error;
        })
    );
  };
}
</code>```

Body:
I'm trying to retrieve information from a web service through an angular app, if I try from the browser everything is ok see image 200 OK if I try from angular I get a 401 no authorized.
Could anyone help me?

COMPONENT.TS

import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { MissioniService } from '../services/servizi/missioni.service';

@Component({
  selector: 'app-servizi',
  templateUrl: './servizi.component.html',
  styleUrls: \['./servizi.component.css'\]
})
export class ServiziComponent implements OnInit {
  obs:Observable<any>;

  constructor(private service:MissioniService) { }

  ngOnInit(): void {

  const host='https://username:password@xmlhostname.com/11428442.xml';

  //this.obs = this.service.request(host,{par : 1},'GET');
  this.obs = this.service.request(host,{},'GET');
    this.obs.subscribe((data:any) => {
      if(!data.error){

      }else{
        alert(data.error);
      }
    });
  }
}

SERVICE.TS:

export class MissioniService {

  constructor(private http:HttpClient) { }

  request = (url:string, parameters:any, method:string): Observable <any>=> {
    return this.http.request(method, url, {
        headers: {
            'Content-Type': 'application/json'
        },
        params: parameters
    }).pipe(
        /*
          map((data)=>{}
        */
        catchError(error => {
            return error;
        })
    );
  };
}


问:
Scaling the component axes of a rotation
I have an orientation sensor that outputs a rotation (either quaternion or rotation matrix).

I need to apply a calibration to the output which involves scaling the magnitude of the X,Y and Z axes.

My current approach is to deconstruct the rotations in each plane, calculate and scale the component of the two axes and then recalculte the respective angles. I then reconstruct the modified rotation.

Is there a simpler approach that i'm missing?


问:
Unable to resolve path to module 'react-dom/client' (import/no-unresolved)
I've upgraded my React Application to React 18. Everything works fine but I receive warning
Unable to resolve path to module 'react-dom/client'

Environment is:

Node v16.15.0,

react: 18.2.0,

react-dom: 18.2.0

@types/node: 16.11.8,

@types/react": "^18.0.26

index.tsx:

import React from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';
import reportWebVitals from './reportWebVitals';
import 'antd/dist/reset.css';
import './index.scss';

const container = document.getElementById('root');
const root = createRoot(container as HTMLElement);

root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

reportWebVitals();
```

Any suggestions please!

Body:
I've upgraded my React Application to React 18. Everything works fine but I receive warning
Unable to resolve path to module 'react-dom/client'

Environment is:

Node v16.15.0,

react: 18.2.0,

react-dom: 18.2.0

@types/node: 16.11.8,

@types/react": "^18.0.26

index.tsx:

import React from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';
import reportWebVitals from './reportWebVitals';
import 'antd/dist/reset.css';
import './index.scss';

const container = document.getElementById('root');
const root = createRoot(container as HTMLElement);

root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

reportWebVitals();

Any suggestions please!


问:
Powershell - removing subfolder recursively in a mapped drive getting error Illegal characters in path
I use a mapped drive to copy folder and files into a Sharpoint directory.
Here is my code

```<code>net use Q: "\\Sharepoint\Dir" /user:domain\user Password

copy-item "C:\Dir" -Destination Q:\

net use Q: /delete
</code>```

Now before copying new files everyday I need to remove 1 subfolder and all his files (data of the day before). Then I try

```<code>remove-item "Q:\Subfolder" -Recurse -Force
</code>```

but i'm getting this error

```<code>Illegal characters in path '{0}'. (Parameter 'Q:\Subfolder\.')
</code>```

It's working if i write the whole file path like so

```<code>remove-item "Q:\Subfolder\file.ext" -Recurse -Force
</code>```

But I need to remove all of the subfolder...

Some of my other unsuccessful tries

```<code>- remove-item "Q:\Subfolder\*" -Recurse -Force

- remove-item "Q:\\Subfolder" -Recurse -Force

- Get-ChildItem Q: -Directory -Force | ForEach-Object {

               $regex = "^te"

                       if ($_.BaseName -match $regex) {
                           remove-item $_.BaseName
                       }
</code>```

Hope someone can help, thanks !

Body:
I use a mapped drive to copy folder and files into a Sharpoint directory.
Here is my code

net use Q: "\\Sharepoint\Dir" /user:domain\user Password

copy-item "C:\Dir" -Destination Q:\

net use Q: /delete

Now before copying new files everyday I need to remove 1 subfolder and all his files (data of the day before). Then I try

remove-item "Q:\Subfolder" -Recurse -Force

but i'm getting this error

Illegal characters in path '{0}'. (Parameter 'Q:\Subfolder\.')

It's working if i write the whole file path like so

remove-item "Q:\Subfolder\file.ext" -Recurse -Force

But I need to remove all of the subfolder...

Some of my other unsuccessful tries

- remove-item "Q:\Subfolder\*" -Recurse -Force

- remove-item "Q:\\Subfolder" -Recurse -Force

- Get-ChildItem Q: -Directory -Force | ForEach-Object {

               $regex = "^te"

                       if ($_.BaseName -match $regex) {
                           remove-item $_.BaseName
                       }

Hope someone can help, thanks !


问:
How to list down all the 3rd party components used in a project by using blackduck?
We are having a project developed using .net and we want to list down all the 3rd party components we have used in our project

I tried searching it on blackduck but didn't find any feature


问:
I have a problem deploying the Django project
When deploying the Django project, I am facing this problem: There is no module with this name (main project folder).

I tried another project with a different name, but still no response.
The command prompt gives me this message: ModuleNotFoundError: No module named eg 'tamrin_project'


问:
Sum the rows of a pandas dataframe grouping by the dates with the same year
I have the following dataframe. lets call it df:

```<code>|Account  |Type   |Date        | Per   | Value|
-----------------------------------------------
|A        |FC     |31/03/2019  |3M     |a     |
|A        |FC     |30/06/2019  |3M     |b     |
|A        |FC     |30/09/2019  |3M     |c     |
|A        |FC     |31/12/2019  |3M     |d     |
|B        |P&G    |31/03/2019  |3M     |e     |
|B        |P&G    |30/06/2019  |3M     |f     |
|B        |P&G    |30/09/2019  |3M     |g     |
|B        |P&G    |31/12/2019  |3M     |h     |
</code>```

Where a,bc,d,e,f,g,h are numerical values.For each element of the account column I need to sum up the values of the value column that are in the same year, according to the date column, getting something like this:

```<code>|Account  |Type   |Date        | Per   | Value  |
-------------------------------------------------
|A        |FC     |31/12/2019  |3M     |a+b+c+d |
|B        |P&G    |30/12/2019  |3M     |e+f+g+h |
</code>```

Where the value of the date column of the resulting dataframe corresponds to the last period that was added.

I tried the next code:

```<code>test_df = pd.DataFrame(df.groupby('Date').sum().reset_index())
</code>```

And I get the next dataframe:

```<code>    Date    Value
0   2016    294590.0158
1   2017    235216.0481
2   2018    326280.1496
3   2019    152482.2480
</code>```

But clearly this is not what i was looking for.

Can you guys help me?

Body:
I have the following dataframe. lets call it df:

|Account  |Type   |Date        | Per   | Value|
-----------------------------------------------
|A        |FC     |31/03/2019  |3M     |a     |
|A        |FC     |30/06/2019  |3M     |b     |
|A        |FC     |30/09/2019  |3M     |c     |
|A        |FC     |31/12/2019  |3M     |d     |
|B        |P&G    |31/03/2019  |3M     |e     |
|B        |P&G    |30/06/2019  |3M     |f     |
|B        |P&G    |30/09/2019  |3M     |g     |
|B        |P&G    |31/12/2019  |3M     |h     |

Where a,bc,d,e,f,g,h are numerical values.For each element of the account column I need to sum up the values of the value column that are in the same year, according to the date column, getting something like this:

|Account  |Type   |Date        | Per   | Value  |
-------------------------------------------------
|A        |FC     |31/12/2019  |3M     |a+b+c+d |
|B        |P&G    |30/12/2019  |3M     |e+f+g+h |

Where the value of the date column of the resulting dataframe corresponds to the last period that was added.

I tried the next code:

test_df = pd.DataFrame(df.groupby('Date').sum().reset_index())

And I get the next dataframe:

    Date    Value
0   2016    294590.0158
1   2017    235216.0481
2   2018    326280.1496
3   2019    152482.2480

But clearly this is not what i was looking for.

Can you guys help me?


问:
Use .htaccess to allow subfolders both with and without trailing slash
I am about to move my html files from the root folder to a couple of subfolders.

The default setting my host is using is to show the trailing slash for the subfolders and no slash for the html files. If the browser requests a subfolder without trailing slash, a 301 redirect to the same folder with trailing slash is returned. The files are shown without html extension thanks to a .htaccess snippet.

I think I like the approach to distinguish the subfolders from the files. In my case the contents of the index files will be different than the ordinary files.

However, I am not as convinced as many others that duplicate content is a disaster. I cannot be sure how my websites will develop in the future and what I will think about trailing slashes and such, so an easy forward compatible strategy is therefore desirable. For that reason I am considering to abandon the 301 redirect and instead allow the browser to send urls to subfolders both with and without the trailing slash and with response 200 OK in both cases. Yes, that leads to duplicate content, but I will will keep the trailing slash on all subfolders on all internal and canonical links, so in practice, I do not think it is a disaster. And Google and Bing and others should be able to figure things out.

I have my sites on a shared server configured via directadmin and (probably) no access to other configuration files and do not know how the default setting has been accomplished. I guess I need to do something in .htaccess to change the default setting but I am not sure what.

Is there anybody who knows how to override the default setting so that I get rid of the 301 redirect in the mentioned case and instead send 200?

I found this interesting document https://httpd.apache.org/docs/2.4/mod/mod_dir.html#directoryindex , but I can not interpret it, and I do not dare to do any trial and error. Hope that somebody can give me a hint.


问:
Java WebSocket subscribe/unsubscribe manually from inside server
I have created a simple websocket server with this configuration and I'm trying to subscribe or unsubscribe a user to a certain topic automaticaly, without the user permission (without sending SUBSCRIPTION event from the client). Example: a user connect to the server and the server automatically subscribe the user to topic "news" and "football". I'm trying to replicate what done when a client send this event "SUBSCRIBE\ndestination:/news/e88e2682-c467-4f48-b445-0af9c7983a5d\nid:/news/e88e2682-c467-4f48-b445-0af9c7983a5d\n\n\u0000" but without the client sending it actualy, is it possible?

```<code>package com.websocket.socket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketTransportRegistration;
import org.springframework.web.socket.handler.WebSocketHandlerDecorator;
import org.springframework.web.socket.handler.WebSocketHandlerDecoratorFactory;

import java.util.Arrays;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfiguration implements WebSocketMessageBrokerConfigurer {

    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketConfiguration.class);
    public static final String APP = "/app";

    private static final String[] topics = new String[]{
            NEWS.BROKER_NAME,
            FOOTBALL.BROKER_NAME
    };

    @Autowired
    private TopicChannelInterceptor topicChannelInterceptor;
    @Autowired
    private UserSessions userSessions;

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {

        config.enableSimpleBroker(topics);
        config.setApplicationDestinationPrefixes(APP);

        LOGGER.info("Prefix: {}", APP);
        LOGGER.info("Topics: {}", Arrays.toString(topics));
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {

        registry.addEndpoint("/socket")
                .setAllowedOriginPatterns("*")
                .withSockJS();
    }

    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {

        registration.interceptors(topicChannelInterceptor);
        WebSocketMessageBrokerConfigurer.super.configureClientInboundChannel(registration);
    }

    @Override
    public void configureWebSocketTransport(WebSocketTransportRegistration registration) {
        registration.addDecoratorFactory(new WebSocketHandlerDecoratorFactory() {
            @Override
            public WebSocketHandler decorate(final WebSocketHandler handler) {
                return new WebSocketHandlerDecorator(handler) {

                    @Override
                    public void afterConnectionEstablished(final WebSocketSession session) throws Exception {

                        // We will store current user's session into WebsocketSessionHolder after connection is established
                        userSessions.addUserSession(session.getId(), session);

                        LOGGER.info("Session stored");
                        super.afterConnectionEstablished(session);
                    }
                };
            }
        });
    }
}
</code>```

Body:
I have created a simple websocket server with this configuration and I'm trying to subscribe or unsubscribe a user to a certain topic automaticaly, without the user permission (without sending SUBSCRIPTION event from the client). Example: a user connect to the server and the server automatically subscribe the user to topic "news" and "football". I'm trying to replicate what done when a client send this event "SUBSCRIBE\ndestination:/news/e88e2682-c467-4f48-b445-0af9c7983a5d\nid:/news/e88e2682-c467-4f48-b445-0af9c7983a5d\n\n\u0000" but without the client sending it actualy, is it possible?

package com.websocket.socket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketTransportRegistration;
import org.springframework.web.socket.handler.WebSocketHandlerDecorator;
import org.springframework.web.socket.handler.WebSocketHandlerDecoratorFactory;

import java.util.Arrays;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfiguration implements WebSocketMessageBrokerConfigurer {

    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketConfiguration.class);
    public static final String APP = "/app";

    private static final String[] topics = new String[]{
            NEWS.BROKER_NAME,
            FOOTBALL.BROKER_NAME
    };

    @Autowired
    private TopicChannelInterceptor topicChannelInterceptor;
    @Autowired
    private UserSessions userSessions;

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {

        config.enableSimpleBroker(topics);
        config.setApplicationDestinationPrefixes(APP);

        LOGGER.info("Prefix: {}", APP);
        LOGGER.info("Topics: {}", Arrays.toString(topics));
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {

        registry.addEndpoint("/socket")
                .setAllowedOriginPatterns("*")
                .withSockJS();
    }

    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {

        registration.interceptors(topicChannelInterceptor);
        WebSocketMessageBrokerConfigurer.super.configureClientInboundChannel(registration);
    }

    @Override
    public void configureWebSocketTransport(WebSocketTransportRegistration registration) {
        registration.addDecoratorFactory(new WebSocketHandlerDecoratorFactory() {
            @Override
            public WebSocketHandler decorate(final WebSocketHandler handler) {
                return new WebSocketHandlerDecorator(handler) {

                    @Override
                    public void afterConnectionEstablished(final WebSocketSession session) throws Exception {

                        // We will store current user's session into WebsocketSessionHolder after connection is established
                        userSessions.addUserSession(session.getId(), session);

                        LOGGER.info("Session stored");
                        super.afterConnectionEstablished(session);
                    }
                };
            }
        });
    }
}


问:
Schedule Shift Resource in ARENA Simulation
How I consider resource schedule (with break time) in all the resources. This is the table of resource break time.
enter image description here

I want to know the resource schedule (break time) of four resources


问:
Issues Deploying PERN app to AWS Elastic Beanstalk/Codepipelink
Im trying to deploy a PERN app to AWS ElasticBeanstalk/Code Pipeline but having issues. Im pretty lost in what the problem is as the causes are broad. Im not sure if my package.json is not configured correctly or what I need to do to move forward.
Any help would be great!

Error Log

Error Log


问:
What is problem in save files indexedDB in my code
Im just started learning indexedDB and have a task.So i need save 3 pictures in indexedDB and after show this pictures after click on button(1,2 or 3).In this code i save only one pictures but after click button 1 nothing  is going.
`

```<code>  <div class="flexi" >
        <img src="" alt=''>

        <button id="one">1</button>
    <button class="two">2</button>
    <button class="three">3</button>
</div>
    <script src='./IDB.js'></script>
    <script>
        let db=idb.open("Gallery",1,(upgradeDB)=>{
            let photo=upgradeDB.createObjectStore("Nature"/* ,{keypath:description} */)
        })
        .then((photos)=>{
            let transaction=photos.transaction(["Nature"],"readwrite")
            let store=transaction.objectStore("Nature")
            let img=new Image();
            img.src="img nat/christopher-czermak-AeiXAB8n8Mc-unsplash.jpg"
            let BlobUpload = new Blob([img], {type: 'image/jpg'});
            store.add(BlobUpload,1)
        })
        document.querySelector("#one").addEventListener("click",function(){
        let bs=idb.open("Gallery",1)
        .then((res)=>{

            let transaction=res.transaction(["Nature"],"readwrite");
            let store=transaction.objectStore("Nature");
            return store.get(1)

    })
    .then((pic)=>{
        let imgUrl=URL.createObjectURL(pic);
       document.querySelector("img").setAttribute("src",imgUrl)

    })
})
</code>```

`

I think problem in blob file because i use

```<code>console.log(imgUrl)
</code>```

and in console i see

```<code>blob:null/e8e0cf8f-0f36-4f3c-b688-029b33b256bf
</code>```

Body:
Im just started learning indexedDB and have a task.So i need save 3 pictures in indexedDB and after show this pictures after click on button(1,2 or 3).In this code i save only one pictures but after click button 1 nothing  is going.
`

        <button id="one">1</button>
    <button class="two">2</button>
    <button class="three">3</button>


问:
count children in Firebase Database
I need to count all the children (Enonce) from each sources that are in my Firebase database.

This is the Firebase structure:

How can I count the childs "Enonce" from each sources ( Source 1 ; Source 2 ; .... ; ....)

Title: count children in Firebase Database


问:
Print headers one time when redirecting an output to a txt fie in python
Need to print header only once when the scripts redirects the output  to a log file.

Below is what I have in place and it's working fine but I want the header to be printed once and not every time. I an redirecting the output to a text file.

Current output:

Script :

```<code>#!/usr/bin/env python3.7
import subprocess
import os
import sys
from datetime import datetime

job_dict = { 'test.evn.prd.' : 'Server1','test.env1.prd.' : 'Server2'}
out = sys.stdout
def backup_jobs(jobs, path):
    backup_server = job_dict[jobs]
    cmd="%s -j *%s* -v -t c -n .inf. -s RU -q"  %(path, jobs)
    cmd1="%s -j *%s* -v -t c -n .inf. -s AC -q"  %(path, jobs)
    cmd2="%s -j *%s* -v -t c -n .inf. -s QU -q"  %(path, jobs)
    cmd3="%s -j *%s* -v -t c -n .inf. -s SU -q"  %(path, jobs)
    output=subprocess.Popen((cmd),shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE).communicate()[0]
    output1=subprocess.Popen((cmd1),shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE).communicate()[0]
    output2=subprocess.Popen((cmd2),shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE).communicate()[0]
    output3=subprocess.Popen((cmd3),shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE).communicate()[0]`count = output.count(b'RU')
    count1 = output1.count(b'AC')
    count2 = output2.count(b'QU')
    count3 = output3.count(b'SU')
    gap= ' '*3
    gaps=' '*5
    gape=' '*7
    heading = f"{'Backup Server Name':17s} {gap} {'RU' :<2s} {gap} {'AC' :<2s} {gaps} {'QU' :<2s} {gaps} {'SU' :<2s} "
     print("="*140)
     print(heading)
     print("-"*140)
     result= f"{backup_server:15s} {gap} {count:>4d} {gap} {count1:>4d} {gap} {count2:>4d} {gap} {count3:>4,.0f}  "
        print(result)
        print("-"*140)
        print("\n")
with open("/home/tmp/out1.log", "w") as output:

        sys.stdout = output
        for jobs in sorted (job_dict.keys()):
                backup_jobs(jobs, '/tmpmnt1/script_lp2_v9.pl')

sys.stdout = out
</code>```

Body:
Need to print header only once when the scripts redirects the output  to a log file.

Below is what I have in place and it's working fine but I want the header to be printed once and not every time. I an redirecting the output to a text file.

Current output:

Script :

#!/usr/bin/env python3.7
import subprocess
import os
import sys
from datetime import datetime

job_dict = { 'test.evn.prd.' : 'Server1','test.env1.prd.' : 'Server2'}
out = sys.stdout
def backup_jobs(jobs, path):
    backup_server = job_dict[jobs]
    cmd="%s -j *%s* -v -t c -n .inf. -s RU -q"  %(path, jobs)
    cmd1="%s -j *%s* -v -t c -n .inf. -s AC -q"  %(path, jobs)
    cmd2="%s -j *%s* -v -t c -n .inf. -s QU -q"  %(path, jobs)
    cmd3="%s -j *%s* -v -t c -n .inf. -s SU -q"  %(path, jobs)
    output=subprocess.Popen((cmd),shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE).communicate()[0]
    output1=subprocess.Popen((cmd1),shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE).communicate()[0]
    output2=subprocess.Popen((cmd2),shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE).communicate()[0]
    output3=subprocess.Popen((cmd3),shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE).communicate()[0]`count = output.count(b'RU')
    count1 = output1.count(b'AC')
    count2 = output2.count(b'QU')
    count3 = output3.count(b'SU')
    gap= ' '*3
    gaps=' '*5
    gape=' '*7
    heading = f"{'Backup Server Name':17s} {gap} {'RU' :<2s} {gap} {'AC' :<2s} {gaps} {'QU' :<2s} {gaps} {'SU' :<2s} "
     print("="*140)
     print(heading)
     print("-"*140)
     result= f"{backup_server:15s} {gap} {count:>4d} {gap} {count1:>4d} {gap} {count2:>4d} {gap} {count3:>4,.0f}  "
        print(result)
        print("-"*140)
        print("\n")
with open("/home/tmp/out1.log", "w") as output:

        sys.stdout = output
        for jobs in sorted (job_dict.keys()):
                backup_jobs(jobs, '/tmpmnt1/script_lp2_v9.pl')

sys.stdout = out


问:
getting a generalized binary incrementer bit by bit
A binary incrementer bit by bit is a sequence in which each succesive nuber is reached by changing only one bit from predecessor, in a way it travels from 0 to 2^n reaching all values without repetition.

An example is the 4-bit incrementer:

#python
incrementer4=(3,2,3,1,3,2,3,0,1,3,2,3,1,3,2)
pins=[0]*4
def change(p,i):
    p[i]=0 if p[i] else 1

print(pins)
for i in incrementer4:
    change(pins,i)
    print(pins)
```

Is there a way to generalise the incrementer4 for any n?
I mean I need a function getIncrementer(int n) where n is power of 2

This is for an electronic projet so I can send the conmuter one pin change each time and optimize the reading time.

Body:
A binary incrementer bit by bit is a sequence in which each succesive nuber is reached by changing only one bit from predecessor, in a way it travels from 0 to 2^n reaching all values without repetition.

An example is the 4-bit incrementer:

#python
incrementer4=(3,2,3,1,3,2,3,0,1,3,2,3,1,3,2)
pins=[0]*4
def change(p,i):
    p[i]=0 if p[i] else 1

print(pins)
for i in incrementer4:
    change(pins,i)
    print(pins)

Is there a way to generalise the incrementer4 for any n?
I mean I need a function getIncrementer(int n) where n is power of 2

This is for an electronic projet so I can send the conmuter one pin change each time and optimize the reading time.


问:
Can't open PDF viewer using QWebEngineView in PySide6
I have a code:

```<code># Import PySide6
from PySide6.QtWidgets import QApplication, QMainWindow, QTextEdit, QFileDialog, QMessageBox, QWidget
from PySide6.QtGui import QIcon, QFont, QAction
from PySide6.QtPrintSupport import QPrinter, QPrintPreviewDialog
from PySide6.QtCore import QFileInfo, QUrl
from PySide6.QtWebEngineWidgets import QWebEngineView
import sys, os

pathFile = ""

# Create new window for PDF file viewer with size 600x400 and title "PDF Viewer"
class PDFViewer(QWidget):
    def __init__(self):
        super().__init__()

        global pathFile
        self.setWindowTitle("PDF Viewer")
        self.setGeometry(300,200,600,400)

        # Create web engine view for PDF file viewer
        self.web_engine_view = QWebEngineView(self)
        self.web_engine_view.load(QUrl.fromLocalFile(pathFile))

        # Show the window
        self.show()

# Create Second Window with Size 400x400 and Title "Config". The size of window cannot be changed.
class ConfigWindow(QWidget):
    def __init__(self):
        super ().__init__()

        self.setWindowTitle("Config")
        self.setGeometry(300,200,400,400)
        self.setFixedSize(400,400)

# Create Main Window with Size 1100x580 and Title "Display". The size of window cannot be changed.
class Window(QMainWindow):
    def __init__(self):
        global config_window
        super().__init__()

        self.setWindowTitle("Display")
        self.setGeometry(300,200,1100,580)
        self.setFixedSize(1100,580)

        # Create Menu Bar with 2 options. The first one is "File" and the second one is "Edit"
        mainMenu = self.menuBar()
        fileMenu = mainMenu.addMenu('File')
        editMenu = mainMenu.addMenu('Edit')

        # Create 3 sub options for "File" menu. The first one is "Choose File" and the second one is "Print" and the third one is "Print Preview"
        # The first one is used to choose a file, the second one is used to print the file, and the third one is used to print preview the file.
        chooseFileAction = QAction(QIcon('open.png'), "Choose File", self)
        chooseFileAction.setShortcut('Ctrl+O')

        printAction = QAction(QIcon('print.png'), "Print", self)
        printAction.setShortcut('Ctrl+P')

        printPreviewAction = QAction(QIcon('printpreview.png'), "Print Preview", self)
        printPreviewAction.setShortcut('Ctrl+Shift+P')

        # Create sub option for "Edit" menu. The sub option is "Config". This sub option is create multi window.
        configAction = QAction(QIcon('config.png'), "Config", self)
        configAction.setShortcut('Ctrl+E')

        # Add sub option of "Choose File", "Print", and "Print Preview" to "File" menu.
        fileMenu.addAction(chooseFileAction)
        fileMenu.addAction(printAction)
        fileMenu.addAction(printPreviewAction)

        # Add sub option of "Config" to "Edit" menu.
        editMenu.addAction(configAction)

        # Add command to "Choose File" sub option. The command is used to choose a file.
        chooseFileAction.triggered.connect(self.choose_file)

        # Add command to "Print" sub option. The command is used to print the file.
        printAction.triggered.connect(self.print_file)

        # Add command to "Print Preview" sub option. The command is used to print preview the file.
        printPreviewAction.triggered.connect(self.print_preview_file)

        # Add command to "Config" sub option. The command is used to create multi window.
        configAction.triggered.connect(self.config_window)

        # Create text edit with size 1000x480
        self.textEdit = QTextEdit(self)
        self.textEdit.setGeometry(50,50,1000,480)

    # Create function for config window
    def config_window(self):
        # Create variable for config window
        config_window = ConfigWindow()

        # Show config window
        config_window.show()

        # Make config not disappear
        config_window.exec_()

    # Create function for choose file
    def choose_file(self):
        global pathFile
        pathFile = ""
        # Create variable for file name
        file_name = QFileDialog.getOpenFileName(self, 'Open File', '/home', 'Text Files (*.txt);;PDF Files (*.pdf)')

        # Create variable for file path
        file_path = file_name[0]

        # Create variable for file type
        file_type = file_name[1]

        # Check the file type from choosen file is "Text Files (*.txt)"
        if file_type == "Text Files (*.txt)":
            # Create variable for file
            file = open(file_path, 'r')

            # Create variable for file content
            file_content = file.read()

            # Add file content to text edit
            self.textEdit.setText(file_content)

        # Check the file type from choosen file is "PDF Files (*.pdf)", then create new window for PDF file viewer
        elif file_type == "PDF Files (*.pdf)":
            pathFile = file_path
            print(pathFile)
            PDFViewer()

    # Create function for print file
    def print_file(self):
        # Create variable for printer
        printer = QPrinter(QPrinter.HighResolution)

        # Create variable for print preview dialog
        preview_dialog = QPrintPreviewDialog(printer, self)

        # Create variable for text edit
        text_edit = self.textEdit

        # Add command to print preview dialog
        preview_dialog.paintRequested.connect(lambda: text_edit.print_(printer))

        # Show print preview dialog
        preview_dialog.exec_()

    # Create function for print preview file
    def print_preview_file(self):
        # Create variable for printer
        printer = QPrinter(QPrinter.HighResolution)

        # Create variable for print preview dialog
        preview_dialog = QPrintPreviewDialog(printer, self)

        # Create variable for text edit
        text_edit = self.textEdit

        # Add command to print preview dialog
        preview_dialog.paintRequested.connect(lambda: text_edit.print_(printer))

        # Show print preview dialog
        preview_dialog.exec_()

app = QApplication(sys.argv)
window = Window()
window.show()

sys.exit(app.exec_())
</code>```

I want to display the PDF File viewer using PySide6 when the file type from chosen file is PDF. But the problem is, PDF File viewer can't showing. I don't know where my program went wrong.

I tried use new widget to preview the file, but it does not work. My expect is when I open a PDF type file, a new widget will open to preview the file using QWebEngineView.

Body:
I have a code:

# Import PySide6
from PySide6.QtWidgets import QApplication, QMainWindow, QTextEdit, QFileDialog, QMessageBox, QWidget
from PySide6.QtGui import QIcon, QFont, QAction
from PySide6.QtPrintSupport import QPrinter, QPrintPreviewDialog
from PySide6.QtCore import QFileInfo, QUrl
from PySide6.QtWebEngineWidgets import QWebEngineView
import sys, os

pathFile = ""

# Create new window for PDF file viewer with size 600x400 and title "PDF Viewer"
class PDFViewer(QWidget):
    def __init__(self):
        super().__init__()

        global pathFile
        self.setWindowTitle("PDF Viewer")
        self.setGeometry(300,200,600,400)

        # Create web engine view for PDF file viewer
        self.web_engine_view = QWebEngineView(self)
        self.web_engine_view.load(QUrl.fromLocalFile(pathFile))

        # Show the window
        self.show()

# Create Second Window with Size 400x400 and Title "Config". The size of window cannot be changed.
class ConfigWindow(QWidget):
    def __init__(self):
        super ().__init__()

        self.setWindowTitle("Config")
        self.setGeometry(300,200,400,400)
        self.setFixedSize(400,400)

# Create Main Window with Size 1100x580 and Title "Display". The size of window cannot be changed.
class Window(QMainWindow):
    def __init__(self):
        global config_window
        super().__init__()

        self.setWindowTitle("Display")
        self.setGeometry(300,200,1100,580)
        self.setFixedSize(1100,580)

        # Create Menu Bar with 2 options. The first one is "File" and the second one is "Edit"
        mainMenu = self.menuBar()
        fileMenu = mainMenu.addMenu('File')
        editMenu = mainMenu.addMenu('Edit')

        # Create 3 sub options for "File" menu. The first one is "Choose File" and the second one is "Print" and the third one is "Print Preview"
        # The first one is used to choose a file, the second one is used to print the file, and the third one is used to print preview the file.
        chooseFileAction = QAction(QIcon('open.png'), "Choose File", self)
        chooseFileAction.setShortcut('Ctrl+O')

        printAction = QAction(QIcon('print.png'), "Print", self)
        printAction.setShortcut('Ctrl+P')

        printPreviewAction = QAction(QIcon('printpreview.png'), "Print Preview", self)
        printPreviewAction.setShortcut('Ctrl+Shift+P')

        # Create sub option for "Edit" menu. The sub option is "Config". This sub option is create multi window.
        configAction = QAction(QIcon('config.png'), "Config", self)
        configAction.setShortcut('Ctrl+E')

        # Add sub option of "Choose File", "Print", and "Print Preview" to "File" menu.
        fileMenu.addAction(chooseFileAction)
        fileMenu.addAction(printAction)
        fileMenu.addAction(printPreviewAction)

        # Add sub option of "Config" to "Edit" menu.
        editMenu.addAction(configAction)

        # Add command to "Choose File" sub option. The command is used to choose a file.
        chooseFileAction.triggered.connect(self.choose_file)

        # Add command to "Print" sub option. The command is used to print the file.
        printAction.triggered.connect(self.print_file)

        # Add command to "Print Preview" sub option. The command is used to print preview the file.
        printPreviewAction.triggered.connect(self.print_preview_file)

        # Add command to "Config" sub option. The command is used to create multi window.
        configAction.triggered.connect(self.config_window)

        # Create text edit with size 1000x480
        self.textEdit = QTextEdit(self)
        self.textEdit.setGeometry(50,50,1000,480)

    # Create function for config window
    def config_window(self):
        # Create variable for config window
        config_window = ConfigWindow()

        # Show config window
        config_window.show()

        # Make config not disappear
        config_window.exec_()

    # Create function for choose file
    def choose_file(self):
        global pathFile
        pathFile = ""
        # Create variable for file name
        file_name = QFileDialog.getOpenFileName(self, 'Open File', '/home', 'Text Files (*.txt);;PDF Files (*.pdf)')

        # Create variable for file path
        file_path = file_name[0]

        # Create variable for file type
        file_type = file_name[1]

        # Check the file type from choosen file is "Text Files (*.txt)"
        if file_type == "Text Files (*.txt)":
            # Create variable for file
            file = open(file_path, 'r')

            # Create variable for file content
            file_content = file.read()

            # Add file content to text edit
            self.textEdit.setText(file_content)

        # Check the file type from choosen file is "PDF Files (*.pdf)", then create new window for PDF file viewer
        elif file_type == "PDF Files (*.pdf)":
            pathFile = file_path
            print(pathFile)
            PDFViewer()

    # Create function for print file
    def print_file(self):
        # Create variable for printer
        printer = QPrinter(QPrinter.HighResolution)

        # Create variable for print preview dialog
        preview_dialog = QPrintPreviewDialog(printer, self)

        # Create variable for text edit
        text_edit = self.textEdit

        # Add command to print preview dialog
        preview_dialog.paintRequested.connect(lambda: text_edit.print_(printer))

        # Show print preview dialog
        preview_dialog.exec_()

    # Create function for print preview file
    def print_preview_file(self):
        # Create variable for printer
        printer = QPrinter(QPrinter.HighResolution)

        # Create variable for print preview dialog
        preview_dialog = QPrintPreviewDialog(printer, self)

        # Create variable for text edit
        text_edit = self.textEdit

        # Add command to print preview dialog
        preview_dialog.paintRequested.connect(lambda: text_edit.print_(printer))

        # Show print preview dialog
        preview_dialog.exec_()

app = QApplication(sys.argv)
window = Window()
window.show()

sys.exit(app.exec_())

I want to display the PDF File viewer using PySide6 when the file type from chosen file is PDF. But the problem is, PDF File viewer can't showing. I don't know where my program went wrong.

I tried use new widget to preview the file, but it does not work. My expect is when I open a PDF type file, a new widget will open to preview the file using QWebEngineView.


问:
Duplicate Module Name Conflict
I have created a fork of the module gym which is also called gym. For clarity, I will refer to original gym as gym_original and the gym fork as gym_fork.

gym_original is already installed on the system (I'm working on Google Colab) and I cannot remove it. Whenever I use gym, I want it to point to gym_fork, not gym_original. I am able to do this on the current file that I'm working on by using import fork_location.gym as gym. But there are other files within gym_fork which also use import gym. In this case, import gym points to gym_original.

What can I do to make any code which uses import gym to point to gym_fork?

I unfortunately cannot uninstall gym_original since it is on google colab. I also cannot rename my fork because there are hundreds of calls to import gym within it.

Title: Duplicate Module Name Conflict


问:
Android App Icon for the release APK not showing
Right-click on App folder > new > Image Asset > Set up your icon.
View Image</p>


问:
How to download the generated CSV file in Rails?
I am trying to download the CSV file processed by the ReportExport service, in the logs the sent data is a "Sent data Business analyst-report-2022-12-12.csv". But the file is not downloaded remotely.
reports_controller.rb

```<code>class ReportsController < ApplicationController
  def export
    status = HoursUploader.new(params[:hours_file]).call
    return redirect_to reports_path, alert: status if status != TasksUploader::OK

    total_hours = Hour.last
    status = HoursDistributor.new(total_hours).call
    return redirect_to reports_path, alert: status if status != HoursDistributor::OK

    send_data ReportExport.new(total_hours).to_csv, filename: "#{total_hours.position_english}-report-#{Time.zone.today}.csv", content_type: 'text/csv'
  end
end

</code>```

_form.html.erb

```<code><%= form_with url: export_reports_path, method: :post do |f| %>
  <form action="#" class="space-y-7">
    <div class="mt-3">
      <%= f.label :hours_file, class: "block my-2 text-sm font-medium text-gray-900 dark:text-gray-300"%>
      <%= f.file_field :hours_file, direct_upload: 'false', class: "block w-full p-1.5 text-sm text-gray-900 bg-gray-50 rounded-lg border border-gray-300 cursor-pointer dark:text-gray-400 focus:outline-none dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400" %>
    </div>
    <button type="submit" class="mt-10 flex w-full items-center justify-center rounded-md border border-transparent bg-indigo-600 py-3 px-8 text-base font-medium text-white hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2">
      <%= f.submit "Create" %>
    </button>
  </form>
<% end %>
</code>```

ReportExport generates the required CSV file

I added data: {turbolinks: false}, disposition: attachment,  did submit with a link and a button but it didn't help. Also it worked before I added styles.

```<code><%= form_with url: export_reports_path, method: :post do |form| %>
  <%= form.label :hours_file, "Hours" %>
  <%= form.file_field :hours_file %>
  <%= form.button "Create" %>
<% end %>

</code>```

How do I fix the error? Thank you in advance!

Body:
I am trying to download the CSV file processed by the ReportExport service, in the logs the sent data is a "Sent data Business analyst-report-2022-12-12.csv". But the file is not downloaded remotely.
reports_controller.rb

class ReportsController < ApplicationController
  def export
    status = HoursUploader.new(params[:hours_file]).call
    return redirect_to reports_path, alert: status if status != TasksUploader::OK

    total_hours = Hour.last
    status = HoursDistributor.new(total_hours).call
    return redirect_to reports_path, alert: status if status != HoursDistributor::OK

    send_data ReportExport.new(total_hours).to_csv, filename: "#{total_hours.position_english}-report-#{Time.zone.today}.csv", content_type: 'text/csv'
  end
end

_form.html.erb

<%= form_with url: export_reports_path, method: :post do |f| %>
  <form action="#" class="space-y-7">

      <%= f.label :hours_file, class: "block my-2 text-sm font-medium text-gray-900 dark:text-gray-300"%>
      <%= f.file_field :hours_file, direct_upload: 'false', class: "block w-full p-1.5 text-sm text-gray-900 bg-gray-50 rounded-lg border border-gray-300 cursor-pointer dark:text-gray-400 focus:outline-none dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400" %>

    <button type="submit" class="mt-10 flex w-full items-center justify-center rounded-md border border-transparent bg-indigo-600 py-3 px-8 text-base font-medium text-white hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2">
      <%= f.submit "Create" %>
    </button>
  </form>
<% end %>

ReportExport generates the required CSV file

I added data: {turbolinks: false}, disposition: attachment,  did submit with a link and a button but it didn't help. Also it worked before I added styles.

<%= form_with url: export_reports_path, method: :post do |form| %>
  <%= form.label :hours_file, "Hours" %>
  <%= form.file_field :hours_file %>
  <%= form.button "Create" %>
<% end %>

How do I fix the error? Thank you in advance!


问:
How to find Target of ASP.NET MVC RedirectToAction?
I am a contractor working on code that has been created/changed by 5 contractors prior to me over the last 5 to 8 years. It is an ASP.NET MVC 5.2 project built on .Net Framework 4.5.2.

Microsoft doesn't seem to give me a good way to locate the target. Take this snippet of code for example in the EmployeeController.cs file:

[HttpPost, ActionName("LoginConfirmations")]
[ValidateAntiForgeryToken]
public ActionResult LoginConfirmations(Login employee)
{
    TempData["email"] = employee.Email;
    TempData["password"] = employee.Password;

    return RedirectToAction("ViewEmployeeConfirmation");
}
```

I can't seem to find anything called ViewEmployeeConfirmation, EmployeeConfirmation, or ViewEmployee using a text search.

Neither the Model nor the View folders seem to have this exact route (I have been placing break points at likely spots in the code, but they are not being hit).

How do I determine where ViewEmployeeConfirmation is routing to?

Body:
I am a contractor working on code that has been created/changed by 5 contractors prior to me over the last 5 to 8 years. It is an ASP.NET MVC 5.2 project built on .Net Framework 4.5.2.

Microsoft doesn't seem to give me a good way to locate the target. Take this snippet of code for example in the EmployeeController.cs file:

[HttpPost, ActionName("LoginConfirmations")]
[ValidateAntiForgeryToken]
public ActionResult LoginConfirmations(Login employee)
{
    TempData["email"] = employee.Email;
    TempData["password"] = employee.Password;

    return RedirectToAction("ViewEmployeeConfirmation");
}

I can't seem to find anything called ViewEmployeeConfirmation, EmployeeConfirmation, or ViewEmployee using a text search.

Neither the Model nor the View folders seem to have this exact route (I have been placing break points at likely spots in the code, but they are not being hit).

How do I determine where ViewEmployeeConfirmation is routing to?


问:
How to Decode Apple App Attestation Statement?
I'm trying to perform the Firebase App Check validation using REST APIs since it's the only way when developing App Clips as they dont' support sockets. I'm trying to follow Firebase docs. All I'm having trouble with is the decoding of the App Attestation Statement.

So far I've been able to extract the device keyId, make Firebase send me a challenge to be sent to Apple so they can provide me an App Attest Statement using DCAppAttestService.shared.attestKey method.

Swift:

```<code>private let dcAppAttestService = DCAppAttestService.shared
    private var deviceKeyId = ""

    private func generateAppAttestKey() {
        // The generateKey method returns an ID associated with the key.  The key itself is stored in the Secure Enclave
        dcAppAttestService.generateKey(completionHandler: { [self] keyId, error in

            guard let keyId = keyId else {
                print("key generate failed: \(String(describing: error))")
                return
            }

            deviceKeyId = keyId
            print("Key ID: \(deviceKeyId.toBase64())")
        })
    }

    func requestAppAttestChallenge() {
        guard let url = URL(string: "\(PROJECT_PREFIX_BETA):generateAppAttestChallenge?key=\(FIREBASE_API_KEY)") else {
            return
        }

        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        let task = URLSession.shared.dataTask(with: request) { [self] data, response, error in
            guard let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) else {
                return
            }

            guard let data = data, error == nil else {
                return
            }

            let response = try? JSONDecoder().decode(AppAttestChallenge.self, from: data)

            if let response = response {

                let challenge = response.challenge

                print("Response app check challenge: \(challenge)")
                print("Response app check keyID: \(deviceKeyId)")
                let hash = Data(SHA256.hash(data: Data(base64Encoded: challenge)!))
                dcAppAttestService.attestKey(deviceKeyId, clientDataHash: hash, completionHandler: {attestationObj, errorAttest in
                    let string = String(decoding: attestationObj!, as: UTF8.self)
                    print("Attestation Object: \(string)")

                })

            }

        }

        task.resume()
    }
</code>```

I tried to send the attestation object to Firebase after converting it in a String, although I wasn't able to properly format the String. I see from Apple docs here the format of the attestation, but it isn't really a JSON so I don't know how to handle it. I was trying to send it to Firebase like this:

```<code>func exchangeAppAttestAttestation(appAttestation : String, challenge : String) {
        guard let url = URL(string: "\(PROJECT_PREFIX_BETA):exchangeAppAttestAttestation?key=\(FIREBASE_API_KEY)") else {
            return
        }

        let requestBody = ExchangeAttestChallenge(attestationStatement: appAttestation.toBase64(), challenge: challenge, keyID: deviceKeyId)
        let jsonData = try! JSONEncoder().encode(requestBody)

        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.httpBody = jsonData

        let task = URLSession.shared.dataTask(with: request) {data, response, error in
            guard let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) else {
                print("Exchange App Attestation \(String(describing: response))")
                return
            }

            guard let data = data, error == nil else {
                return
            }

            print("Exchange App Attestation: \(data)")

        }

        task.resume()
    }
</code>```

Body:
I'm trying to perform the Firebase App Check validation using REST APIs since it's the only way when developing App Clips as they dont' support sockets. I'm trying to follow Firebase docs. All I'm having trouble with is the decoding of the App Attestation Statement.

So far I've been able to extract the device keyId, make Firebase send me a challenge to be sent to Apple so they can provide me an App Attest Statement using DCAppAttestService.shared.attestKey method.

Swift:

private let dcAppAttestService = DCAppAttestService.shared
    private var deviceKeyId = ""

    private func generateAppAttestKey() {
        // The generateKey method returns an ID associated with the key.  The key itself is stored in the Secure Enclave
        dcAppAttestService.generateKey(completionHandler: { [self] keyId, error in

            guard let keyId = keyId else {
                print("key generate failed: \(String(describing: error))")
                return
            }

            deviceKeyId = keyId
            print("Key ID: \(deviceKeyId.toBase64())")
        })
    }

    func requestAppAttestChallenge() {
        guard let url = URL(string: "\(PROJECT_PREFIX_BETA):generateAppAttestChallenge?key=\(FIREBASE_API_KEY)") else {
            return
        }

        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        let task = URLSession.shared.dataTask(with: request) { [self] data, response, error in
            guard let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) else {
                return
            }

            guard let data = data, error == nil else {
                return
            }

            let response = try? JSONDecoder().decode(AppAttestChallenge.self, from: data)

            if let response = response {

                let challenge = response.challenge

                print("Response app check challenge: \(challenge)")
                print("Response app check keyID: \(deviceKeyId)")
                let hash = Data(SHA256.hash(data: Data(base64Encoded: challenge)!))
                dcAppAttestService.attestKey(deviceKeyId, clientDataHash: hash, completionHandler: {attestationObj, errorAttest in
                    let string = String(decoding: attestationObj!, as: UTF8.self)
                    print("Attestation Object: \(string)")

                })

            }

        }

        task.resume()
    }

I tried to send the attestation object to Firebase after converting it in a String, although I wasn't able to properly format the String. I see from Apple docs here the format of the attestation, but it isn't really a JSON so I don't know how to handle it. I was trying to send it to Firebase like this:

func exchangeAppAttestAttestation(appAttestation : String, challenge : String) {
        guard let url = URL(string: "\(PROJECT_PREFIX_BETA):exchangeAppAttestAttestation?key=\(FIREBASE_API_KEY)") else {
            return
        }

        let requestBody = ExchangeAttestChallenge(attestationStatement: appAttestation.toBase64(), challenge: challenge, keyID: deviceKeyId)
        let jsonData = try! JSONEncoder().encode(requestBody)

        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.httpBody = jsonData

        let task = URLSession.shared.dataTask(with: request) {data, response, error in
            guard let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) else {
                print("Exchange App Attestation \(String(describing: response))")
                return
            }

            guard let data = data, error == nil else {
                return
            }

            print("Exchange App Attestation: \(data)")

        }

        task.resume()
    }


问:
Rust nested lazy iteration and the interaction with mutable closures
Nested iteration combined with side-effects don't seem to work very well with Rust iterators.  Here is an example:

fn main(){
  let v1=vec![1];
  let v2=vec![3];
  let mut v3=vec![];
  v1.iter().map(|x|{
    v2.iter().map(|y|{
      v3.push(*y);
    })
  });
}
```
<p>This results in the following error:</p>
```error: captured variable cannot escape `FnMut` closure body
 --> src/main.rs:6:5
  |
4 |     let mut v3=vec![];
  |         ------ variable defined here
5 |     v1.iter().map(|x|{
  |                     - inferred to be a `FnMut` closure
6 | /     v2.iter().map(|y|{
7 | |       v3.push(*y);
  | |       -- variable captured here
8 | |     })
  | |______^ returns a reference to a captured variable which escapes the closure body
```

I assume the problem has something to do with the laziness of iterators and a conflict between the two closures.  What is causing the error?  And how do I fix it?

Body:
Nested iteration combined with side-effects don't seem to work very well with Rust iterators.  Here is an example:

fn main(){
  let v1=vec![1];
  let v2=vec![3];
  let mut v3=vec![];
  v1.iter().map(|x|{
    v2.iter().map(|y|{
      v3.push(*y);
    })
  });
}

This results in the following error:

error: captured variable cannot escape `FnMut` closure body
 --> src/main.rs:6:5
  |
4 |     let mut v3=vec![];
  |         ------ variable defined here
5 |     v1.iter().map(|x|{
  |                     - inferred to be a `FnMut` closure
6 | /     v2.iter().map(|y|{
7 | |       v3.push(*y);
  | |       -- variable captured here
8 | |     })
  | |______^ returns a reference to a captured variable which escapes the closure body

I assume the problem has something to do with the laziness of iterators and a conflict between the two closures.  What is causing the error?  And how do I fix it?


问:
Visual Studio 2022 Default C# (CSharp) Snippets Not Showing With Intellisense
Within the last week or so, standard C# snippets like: (ctor, propfull, for, etc.) stopped showing in IntelliSense. However, if I type ctor, then press ESC to close IntelliSense, then press TAB, it will execute the snippet. Or edit/IntelliSense/insert snippet/Visual C# will insert any of the desired commands.
(https://i.stack.imgur.com/v5UBv.jpg) (https://i.stack.imgur.com/Jpeff.jpg) (https://i.stack.imgur.com/uRE1v.jpg)

Below are some of the things I have tried:

tools/options/texteditor/advanced/default IntelliSense completion mode = automatic

tools/options/texteditor/C#/IntelliSense/snippets behavior = always include snippets

snippets manager/CSharp/Visual C# shows all correct snippets & in the correct location
C:\Program Files\Microsoft Visual Studio\2022\Community\VC#\Snippets\1033\Visual C#

Uninstalled & reinstalled VS2022.

No installation of Jetbrains or Resharper on computer.