问:
Apache beam - prevent accumulator to fire an empty pane at the end of the allowed lateness
I am currently running a pipeline that is quite close to the Beam example of using a CombineFn, with the difference that it is a streaming job, and thus uses a windowing method before the combiner.

import apache_beam as beam
from apache_beam.transforms import window
from apache_beam.transforms.trigger import (
    AccumulationMode,
    AfterAll,
    AfterCount,
    AfterWatermark,
    AfterProcessingTime,
)

class AverageFn(beam.CombineFn):
  def create_accumulator(self):
    sum = 0.0
    count = 0
    accumulator = sum, count
    return accumulator

  def add_input(self, accumulator, input):
    sum, count = accumulator
    return sum + input, count + 1

  def merge_accumulators(self, accumulators):
    sums, counts = zip(*accumulators)
    return sum(sums), sum(counts)

  def extract_output(self, accumulator):
    sum, count = accumulator
    if count == 0:
      return float('NaN')
    return sum / count

with beam.Pipeline() as pipeline:
    pipeline | beam.Create([('', 3),
          ('', 2),
          ('', 1),
          ('', 4),
          ('', 5),
          ('', 3),]) | beam.WindowInto(
                             window.FixedWindow(60),
                             accumulation_mode=AccumulationMode.DISCARDING,
                             allowed_lateness = 10*60,
                             trigger=AfterWatermark(
                                         late=AfterAll(AfterProcessingTime(120), AfterCount(1))
                                         )
                    ) | 'Average' >> beam.CombinePerKey(AverageFn())
                      | beam.Map(print))
```
<p>If I were to not allow lateness, the pipeline would be doing great, but I cannot simply discard late data.</p>
<p>I have set up the trigger <code>AfterAll(AfterProcessingTime(120), AfterCount(1))</code> to fire one pane every 120 second only if there at least one element in this pane.</p>
<p>However, I still receive an error
<code>ValueError: not enough values to unpack (expected 3, got 0)</code>.</p>
<p>After some investigation, I found out that it happened that the method <code>AverageFn.merge_accumulators</code> was called with an empty list as <code>accumulators</code>. This was not supposed to happen from the definition of the trigger, but it seems that when the window reaches the end of it's <code>allowed_lateness</code> period, a pane is fired even if it contains 0 elements.</p>
<p>The first fix I thought about was relatively straightforward, simply return <code>0</code> if the accumulator is an empty list</p>
```def merge_accumulators(self, accumulators):
    if len(accumulators) == 0:
        return 0, 0
    sums, counts = zip(*accumulators)
    return sum(sums), sum(counts)
```

However, I find this solution a bit inelegant: filtering out elements rather than simply not creating them seems like a waste of CPU time.

Is there a way to not fire the last pane if it does not contain any element ?

Body:
I am currently running a pipeline that is quite close to the Beam example of using a CombineFn, with the difference that it is a streaming job, and thus uses a windowing method before the combiner.

import apache_beam as beam
from apache_beam.transforms import window
from apache_beam.transforms.trigger import (
    AccumulationMode,
    AfterAll,
    AfterCount,
    AfterWatermark,
    AfterProcessingTime,
)

class AverageFn(beam.CombineFn):
  def create_accumulator(self):
    sum = 0.0
    count = 0
    accumulator = sum, count
    return accumulator

  def add_input(self, accumulator, input):
    sum, count = accumulator
    return sum + input, count + 1

  def merge_accumulators(self, accumulators):
    sums, counts = zip(*accumulators)
    return sum(sums), sum(counts)

  def extract_output(self, accumulator):
    sum, count = accumulator
    if count == 0:
      return float('NaN')
    return sum / count

with beam.Pipeline() as pipeline:
    pipeline | beam.Create([('', 3),
          ('', 2),
          ('', 1),
          ('', 4),
          ('', 5),
          ('', 3),]) | beam.WindowInto(
                             window.FixedWindow(60),
                             accumulation_mode=AccumulationMode.DISCARDING,
                             allowed_lateness = 10*60,
                             trigger=AfterWatermark(
                                         late=AfterAll(AfterProcessingTime(120), AfterCount(1))
                                         )
                    ) | 'Average' >> beam.CombinePerKey(AverageFn())
                      | beam.Map(print))

If I were to not allow lateness, the pipeline would be doing great, but I cannot simply discard late data.

I have set up the trigger AfterAll(AfterProcessingTime(120), AfterCount(1)) to fire one pane every 120 second only if there at least one element in this pane.

However, I still receive an error
ValueError: not enough values to unpack (expected 3, got 0).

After some investigation, I found out that it happened that the method AverageFn.merge_accumulators was called with an empty list as accumulators. This was not supposed to happen from the definition of the trigger, but it seems that when the window reaches the end of it's allowed_lateness period, a pane is fired even if it contains 0 elements.

The first fix I thought about was relatively straightforward, simply return 0 if the accumulator is an empty list

def merge_accumulators(self, accumulators):
    if len(accumulators) == 0:
        return 0, 0
    sums, counts = zip(*accumulators)
    return sum(sums), sum(counts)

However, I find this solution a bit inelegant: filtering out elements rather than simply not creating them seems like a waste of CPU time.

Is there a way to not fire the last pane if it does not contain any element ?


来源: stackexchange

问:
Deploying Django Postgres to Digital Ocean Droplets
I have to deploy a Django API to Digital Ocean, a service that should scale a bit over the next year. I also need a database to save all the data from the users, and I will use Postgres. Recently I saw a lot of video tutorials, official guides from the digital ocean and so on that tell us to use the Postgres that you install on the Droplets "locally" as the database, so install Postgres locally  and put all the data there.

It actually can make sense since the droplet I will pay for is about 25 GB that I will never really reach. So, my question was if this approach makes sense at all, or is it better to set up right now a different possibility, like a database on the digital ocean itself?

If I keep these settings, will I be able to easily migrate in the future? Or will it be painful if not impossible? Is there a very good cost-efficient way to do this, or this solution is good enough even for a platform that needs to scale (let's say 100,000 users and a really high amount of requests for each one of them at his prime, maybe in a couple of years)?

Any suggestion is useful.

Then, should I go with venv or Docker? Thank you a lot

ContentLicense: CC BY-SA 4.0


问:
CentOS/Rocky 8 installation of obsolete CentOS 4 package
The obsolete packages repository https://vault.centos.org/4.0/os/x86_64/CentOS/RPMS/ contains one I would like to install on CentOS/Rocky 8.

I am having problems with basic libraries such as libcrypto.so.4 and libssl.so.4 that conflict with the new system.

openssl-1.X doesn't allow openssl-0.X while the reverse is possible

I tried to install openssl-0.X which contains the missing dependencies but this leads to a broken system when I uninstall current openssl-1.X

I also tried to create symbolic links for the missing libraries to the existing ones


问:
Excel =(Formula to add +1 every day)
i am trying to make excel cell count the number of dates passed since the last time i have edited that cell.

eg: A1 = Info1 A2 = 10

Cell A1 Edited 10 Days ago.

how can i create this in excel and LibreOffice please

i tried some formulas but don't have the exact results and complicated to understand.

Title: Excel =(Formula to add +1 every day)


问:
How to go back to react native activity from android native modules
I implemented android native bridge module in which I call native like below, and I don't know how to navigate back to react native
@ReactMethod public void createMerchantEvent(){ Intent intent = new Intent(getReactApplicationContext(),LoadingActivity.class); getCurrentActivity().startActivity(intent); }


问:
Execution failed for task ':unsw-gsbme_react-native-keep-awake:compileDebugKotlin'
I'm working on a react native bare project that I run and return this error, has anyone seen something similar and a possible solution?

```<code>FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':unsw-gsbme_react-native-keep-awake:compileDebugKotlin'.
> Compilation error. See log for more details

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 2m 22s
</code>```

Do you have any ideas? Did someone met this problem also?

I have tried to run the app, remove this lib with npm but to no avail

Body:
I'm working on a react native bare project that I run and return this error, has anyone seen something similar and a possible solution?

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':unsw-gsbme_react-native-keep-awake:compileDebugKotlin'.
> Compilation error. See log for more details

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 2m 22s

Do you have any ideas? Did someone met this problem also?

I have tried to run the app, remove this lib with npm but to no avail


问:
Managing ElasticSearch resources in Tomcat
I have a web app running in Tomcat that needs to connect to ES using the High Level Java API. I am usure about the best practices for managing the ES resources (client, transport) in that context.

In the past, I would create a brand new client for every request and close it (as well as its transport) when I was done with the request.

But now I read that it's best to use a single client in my app and across all threads (the client is apparently thread-safe).

I can see two issues with that approach.

Issue 1: client timing out

If the single client hasn't been used in a while, it may have timed out. So before I use the client, I need a way to check if the client is still alive. But I can't find clear doc on how to do that (at least not without pinging the server everytime).

Issue 2: can't tell when Tomcat is done with the client

When I run my app as a comnmand line main() app, I can close the client's trasport at the end of that main. But in a Tomcat context, my code has no way of knowing when Tomcat is done with the client and its transport.

I tried all sorts of tricks using finalize() but none of them work consistently. And from what I read, it's unwise to rely on finalize() to close resources as the JVM offers no garantee as to when an object will be GCed (if ever!).

Thx for your guidance.


问:
In Python, why attribute is not found even if it's listed in dir(object)?
i am using regionprops() from skimage.measure (version 0.19.3). It returns a list of RegionProperties objects. I can access all the various attributes from these RegionProperties (like area, major_axis_length, eccentricity...). But when i try to access the attributes related to intensity (intensity_mean, intensity_min, intensity_max) it returns this error:

```<code>AttributeError: '<class 'skimage.measure._regionprops.RegionProperties'>' object has no attribute 'intensity_mean'
</code>```

When i print dir(region_property), where region_property is an instance of the class, it shows that intensity_mean/min/max are, in fact, between the object's attributes:

```<code>['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattr__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_cache', '_cache_active', '_extra_properties', '_image_intensity_double', '_intensity_image', '_label_image', '_multichannel', '_ndim', '_slice', '_spatial_axes', 'area', 'area_bbox', 'area_convex', 'area_filled', 'axis_major_length', 'axis_minor_length', 'bbox', 'centroid', 'centroid_local', 'centroid_weighted', 'centroid_weighted_local', 'coords', 'eccentricity', 'equivalent_diameter_area', 'euler_number', 'extent', 'feret_diameter_max', 'image', 'image_convex', 'image_filled', 'image_intensity', 'inertia_tensor', 'inertia_tensor_eigvals', 'intensity_max', 'intensity_mean', 'intensity_min', 'label', 'moments', 'moments_central', 'moments_hu', 'moments_normalized', 'moments_weighted', 'moments_weighted_central', 'moments_weighted_hu', 'moments_weighted_normalized', 'orientation', 'perimeter', 'perimeter_crofton', 'slice', 'solidity']
</code>```

How is this possible?

Here a minimal reproducible example of my code:

```<code>from tqdm import tqdm
import string
import cv2
import numpy as np
from skimage.measure import label, regionprops, regionprops_table

test_mask_img = cv2.imread(test_mask, 0)
label_img = label(test_mask)
if len(np.unique(label_img)) > 1:
    regions = regionprops(label_img)
    print(dir(regions[0]))
    print(regions[0].intensity_mean) # this returns the error
</code>```

complete stacktrace:

```<code>-------------------------------------------------------------------
AttributeError                            Traceback (most recent
call last)
Cell In [44], line 13
 11 regions = regionprops(label_img)
 12 print(dir(regions[0]))
 ---> 13 print(regions[0].intensity_mean)
 14 # update area stats
 15 update_stats(stats_dict=area_stats,
 16             regions=regions,
 17             c=c,
 18             feature="area")

 File ~/ambiente/lib/python3.8/site-
 packages/skimage/measure/_regionprops.py:352, in
 RegionProperties.__getattr__(self, attr)
 350     return getattr(self, PROPS[attr])
 351 else:
 --> 352     raise AttributeError(
 353         f"'{type(self)}' object has no attribute '{attr}'"
 354     )

 AttributeError: '<class
 'skimage.measure._regionprops.RegionProperties'>' object has no
 attribute 'intensity_mean'
</code>```

Body:
i am using regionprops() from skimage.measure (version 0.19.3). It returns a list of RegionProperties objects. I can access all the various attributes from these RegionProperties (like area, major_axis_length, eccentricity...). But when i try to access the attributes related to intensity (intensity_mean, intensity_min, intensity_max) it returns this error:

AttributeError: '<class 'skimage.measure._regionprops.RegionProperties'>' object has no attribute 'intensity_mean'

When i print dir(region_property), where region_property is an instance of the class, it shows that intensity_mean/min/max are, in fact, between the object's attributes:

['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattr__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_cache', '_cache_active', '_extra_properties', '_image_intensity_double', '_intensity_image', '_label_image', '_multichannel', '_ndim', '_slice', '_spatial_axes', 'area', 'area_bbox', 'area_convex', 'area_filled', 'axis_major_length', 'axis_minor_length', 'bbox', 'centroid', 'centroid_local', 'centroid_weighted', 'centroid_weighted_local', 'coords', 'eccentricity', 'equivalent_diameter_area', 'euler_number', 'extent', 'feret_diameter_max', 'image', 'image_convex', 'image_filled', 'image_intensity', 'inertia_tensor', 'inertia_tensor_eigvals', 'intensity_max', 'intensity_mean', 'intensity_min', 'label', 'moments', 'moments_central', 'moments_hu', 'moments_normalized', 'moments_weighted', 'moments_weighted_central', 'moments_weighted_hu', 'moments_weighted_normalized', 'orientation', 'perimeter', 'perimeter_crofton', 'slice', 'solidity']

How is this possible?

Here a minimal reproducible example of my code:

from tqdm import tqdm
import string
import cv2
import numpy as np
from skimage.measure import label, regionprops, regionprops_table

test_mask_img = cv2.imread(test_mask, 0)
label_img = label(test_mask)
if len(np.unique(label_img)) > 1:
    regions = regionprops(label_img)
    print(dir(regions[0]))
    print(regions[0].intensity_mean) # this returns the error

complete stacktrace:

-------------------------------------------------------------------
AttributeError                            Traceback (most recent
call last)
Cell In [44], line 13
 11 regions = regionprops(label_img)
 12 print(dir(regions[0]))
 ---> 13 print(regions[0].intensity_mean)
 14 # update area stats
 15 update_stats(stats_dict=area_stats,
 16             regions=regions,
 17             c=c,
 18             feature="area")

 File ~/ambiente/lib/python3.8/site-
 packages/skimage/measure/_regionprops.py:352, in
 RegionProperties.__getattr__(self, attr)
 350     return getattr(self, PROPS[attr])
 351 else:
 --> 352     raise AttributeError(
 353         f"'{type(self)}' object has no attribute '{attr}'"
 354     )

 AttributeError: '<class
 'skimage.measure._regionprops.RegionProperties'>' object has no
 attribute 'intensity_mean'


问:
Duplicate class com.google.firebase.iid.FirebaseInstanceIdReceiver found in modules
Duplicate class com.google.firebase.iid.FirebaseInstanceIdReceiver found in modules jetified-firebase-iid-20.1.5-runtime (com.google.firebase:firebase-iid:20.1.5) and jetified-firebase-messaging-23.1.1-runtime (com.google.firebase:firebase-messaging:23.1.1)

I'm trying to integrate the Carrot Quest library and I'm facing a dependency conflict problem.

I tried to do exclude group, but without success

`

```<code>implementation ('io.carrotquest:android-sdk:1.0.60-commonRelease') {
    exclude group: 'com.google.firebase'
}
</code>```

`

Body:
Duplicate class com.google.firebase.iid.FirebaseInstanceIdReceiver found in modules jetified-firebase-iid-20.1.5-runtime (com.google.firebase:firebase-iid:20.1.5) and jetified-firebase-messaging-23.1.1-runtime (com.google.firebase:firebase-messaging:23.1.1)

I'm trying to integrate the Carrot Quest library and I'm facing a dependency conflict problem.

I tried to do exclude group, but without success

`

implementation ('io.carrotquest:android-sdk:1.0.60-commonRelease') {
    exclude group: 'com.google.firebase'
}

`


问:
Is there a way to configure python to hide python version when running quick web test using http.server
Is there a way to configure python to hide python version when running quick web test using http.server which can be wither updated in configuration file or setup in environment variables. There are code but not practical if you want to setup this in lot of machines.</p>
```<code> curl -kvl http://0.0.0.0 2>&1| grep -i python
< Server: SimpleHTTP/0.6 Python/3.10.5

</code>```

Body:
Is there a way to configure python to hide python version when running quick web test using http.server which can be wither updated in configuration file or setup in environment variables. There are code but not practical if you want to setup this in lot of machines.

 curl -kvl http://0.0.0.0 2>&1| grep -i python
< Server: SimpleHTTP/0.6 Python/3.10.5


问:
Can An iPhone App Motintor Multiple Apple Watches?
Is WatchOS flexible enough to allow a single app to read data from multiple Apple Watches?

The application I am looking at is similar to the one described in this post, but with a twist. I want to use Apple Watches on multiple subjects to monitor vital signs, but I am quite willing to write a dedicated app to access the watches, including polling them or switching the active watch on the iPhone if needed, and assuming that is even possible. Is that possible?

I'd prefer not to have a separate iPhone for each subject.


问:
Blazor Server: Attempting to take files from InputFile into an Email attachment
I am currently trying to get the files received from InputFile and attach it as an email attachment. I followed this website to get my InputFile with the progress bar: https://www.meziantou.net/file-upload-with-progress-bar-in-blazor.htm.

I have tried various options such as converting the file to byte array, using memory stream, and using a file stream but I do not have a path to copy the file too. Here's my code currently on what I am trying to accomplish. The Email is sent through SMTP client and that works perfectly without the attachments.

```<code>private async ValueTask LoadFiles(InputFileChangeEventArgs e)
{
    var files = e.GetMultipleFiles(maximumFileCount: 100);
    filesList = e.GetMultipleFiles(maximumFileCount: 100);

    var startIndex = uploadedFiles.Count;

    // Add all files to the UI
    foreach (var file in files)
    {
        var progress = new FileUploadProgress(file.Name, file.Size);
        uploadedFiles.Add(progress);
    }

    await using var timer = new Timer(_ => InvokeAsync(() => StateHasChanged()));
    timer.Change(TimeSpan.FromMilliseconds(500), TimeSpan.FromMilliseconds(500));

    // Upload files
    byte[] buffer = System.Buffers.ArrayPool<byte>.Shared.Rent(4096);
    try
    {
        foreach (var file in files)
        {

            MemoryStream ms = new MemoryStream();

            using var stream = file.OpenReadStream(maxAllowedSize: 10 * 1024 * 1024);
            while (await stream.ReadAsync(buffer) is int read && read > 0)
            {
                uploadedFiles[startIndex].UploadedBytes += read;

                file.OpenReadStream().CopyTo(ms);
                var fileBytes = ms.ToArray();

                Attachment fileAttch = new Attachment(new MemoryStream(fileBytes), file.ContentType);
                message.Attachments.Add(fileAttch);

                var readData = buffer.AsMemory().Slice(0, read);
            }

            startIndex++;
        }
    }
    finally
    {
        System.Buffers.ArrayPool<byte>.Shared.Return(buffer);

        // Update the UI with the final progress
        StateHasChanged();
    }
}
</code>```

When using the debugger, I noticed that the try block breaks whenever I try to copy the file into MemoryStream. I am not sure why. Any help or solutions would be greatly appreciated.

Thank you

I have tried copying the file/buffer into the memory stream but the try block breaks. I have tried to use file stream without success. I am either missing something I am unaware of or I am not implementing the code correctly.

Body:
I am currently trying to get the files received from InputFile and attach it as an email attachment. I followed this website to get my InputFile with the progress bar: https://www.meziantou.net/file-upload-with-progress-bar-in-blazor.htm.

I have tried various options such as converting the file to byte array, using memory stream, and using a file stream but I do not have a path to copy the file too. Here's my code currently on what I am trying to accomplish. The Email is sent through SMTP client and that works perfectly without the attachments.

private async ValueTask LoadFiles(InputFileChangeEventArgs e)
{
    var files = e.GetMultipleFiles(maximumFileCount: 100);
    filesList = e.GetMultipleFiles(maximumFileCount: 100);

    var startIndex = uploadedFiles.Count;

    // Add all files to the UI
    foreach (var file in files)
    {
        var progress = new FileUploadProgress(file.Name, file.Size);
        uploadedFiles.Add(progress);
    }

    await using var timer = new Timer(_ => InvokeAsync(() => StateHasChanged()));
    timer.Change(TimeSpan.FromMilliseconds(500), TimeSpan.FromMilliseconds(500));

    // Upload files
    byte[] buffer = System.Buffers.ArrayPool<byte>.Shared.Rent(4096);
    try
    {
        foreach (var file in files)
        {

            MemoryStream ms = new MemoryStream();

            using var stream = file.OpenReadStream(maxAllowedSize: 10 * 1024 * 1024);
            while (await stream.ReadAsync(buffer) is int read && read > 0)
            {
                uploadedFiles[startIndex].UploadedBytes += read;

                file.OpenReadStream().CopyTo(ms);
                var fileBytes = ms.ToArray();

                Attachment fileAttch = new Attachment(new MemoryStream(fileBytes), file.ContentType);
                message.Attachments.Add(fileAttch);

                var readData = buffer.AsMemory().Slice(0, read);
            }

            startIndex++;
        }
    }
    finally
    {
        System.Buffers.ArrayPool<byte>.Shared.Return(buffer);

        // Update the UI with the final progress
        StateHasChanged();
    }
}

When using the debugger, I noticed that the try block breaks whenever I try to copy the file into MemoryStream. I am not sure why. Any help or solutions would be greatly appreciated.

Thank you

I have tried copying the file/buffer into the memory stream but the try block breaks. I have tried to use file stream without success. I am either missing something I am unaware of or I am not implementing the code correctly.


问:
Export Excel (for Mac) Sheet to CSV works only on my system
This is my first time on StackOverflow and first post so please bare with me. I have created an Excel (for Mac) Macro-enabled workbook which takes data into one sheet, manipulates it slightly and updated a 2nd sheet. One the first sheet is a button with some basic code behind it to export the 2nd sheet to a CSV file. The workbook and macro within work perfectly for me on my Mac however I need to share with my peers at work so they can do the same but it will not work on their Macs. I don't know why it doesn't work on their systems.

When I sent the Excel file to my peer to generate the same CSV file for his team's data it didn't work. He is receiving a "Run-time error 1004: Cannot access read-only document".

Macro Line where error occurs

Error Dialog Box


问:
How to send payload from c# in pushkit notification?
In firebase Or in any third party it's easy to send paylod for notification alert in Android and ios, but how can i send Or whats the role of backend in pushkit notification.

I try to implement in asp dot net mvc but there is no any reference, so can you please find a solution to implement it in my code in asp.net mvc..


问:
read full review from the dataset with the specific word that shown in wordcloud
Hy! I am finding for the reviews from dataset related to those specific words that are shown in wordCloud
here is my code for visualizing  and counting for words

visualize wordcloud with removing stopwords

```<code>stopwords=set(STOPWORDS)
stopwords.update(["car","vehicle","time","buy","new","infiniti",])
wordcloud_spam=WordCloud(stopwords=stopwords,background_color="white").generate(negitive_reviews_str)
plt.figure(figsize=(10,10))
plt.imshow(wordcloud_spam, interpolation = 'bilinear')
plt.axis("off")
plt.show()
</code>```

count first 10 words from cloud

```<code>filtered_word_spam=[word for word in negitive_reviews_str.split()if word not in stopwords]
counted_word_spam=collections.Counter(filtered_word_spam)
word_count_spam={}
for letter, count in counted_word_spam.most_common(10):
    word_count_spam[letter]=count
for i,j in word_count_spam.items():
    print('Word: {0}, count: {1}'.format(i,j))
</code>```

Body:
Hy! I am finding for the reviews from dataset related to those specific words that are shown in wordCloud
here is my code for visualizing  and counting for words

visualize wordcloud with removing stopwords

stopwords=set(STOPWORDS)
stopwords.update(["car","vehicle","time","buy","new","infiniti",])
wordcloud_spam=WordCloud(stopwords=stopwords,background_color="white").generate(negitive_reviews_str)
plt.figure(figsize=(10,10))
plt.imshow(wordcloud_spam, interpolation = 'bilinear')
plt.axis("off")
plt.show()

count first 10 words from cloud

filtered_word_spam=[word for word in negitive_reviews_str.split()if word not in stopwords]
counted_word_spam=collections.Counter(filtered_word_spam)
word_count_spam={}
for letter, count in counted_word_spam.most_common(10):
    word_count_spam[letter]=count
for i,j in word_count_spam.items():
    print('Word: {0}, count: {1}'.format(i,j))


问:
Removing parts of a field in SSRS reports
I have a question that I need help with :

I also need to extract the last two digits of the year and put in a text box using an expression. for eg, since we are in 2022, I need to extract the last two digits (22).
grateful if someone can please help as I have not done this before and my syntax might be off

I have tried :

=DatePart(Year())-2

thank you


问:
Representing an array as a feature in ML training
I have a set of features x1,x2,x3,x4 where x1,x2,x3 are floats and x4 is an array of floats.

To give an example, say that I am trying to predict the price of a house. I could use the size of the house as an array  (e.g. length, width, and height) along with other features like number of bedrooms, age of house, no of bathrooms etc.

This is simple, but I am sort of struggling how to represent this.

Here is a similar sample based on heart attack prediction https://colab.research.google.com/drive/1CQX2d0vkjlZKjX6wbG4ga6tRcI-zOMNA

I tried to add a column to add an array feature, with np.c_ to the end

```<code>##################################-Check-########################
print("Before",X_s[:1])
X_s =np.c_[ X_s,np.random.rand(303,2)] # add a numpy array here as a feature
print("After",X_s[:1])
print("shape of X_s",X_s.shape)
print(X_s[:1])
dataset = tf.data.Dataset.from_tensor_slices((X_s, y_s))
</code>```

But the problems is that the array is added as two extra columns in the end

```<code>shape of X_s (303, 13)
shape of X_s (303, 15)
</code>```

So if I have a feature array of say 330*300 with the above approach it will add 300 columns to the end. Not something I want

I am aware of CNN network, and one option is to model the whole problem as a CNN; that is pad the other features also as arrays and created an n dimension tensor and use a CNN

Is there something simpler and better than these approaches

Body:
I have a set of features x1,x2,x3,x4 where x1,x2,x3 are floats and x4 is an array of floats.

To give an example, say that I am trying to predict the price of a house. I could use the size of the house as an array  (e.g. length, width, and height) along with other features like number of bedrooms, age of house, no of bathrooms etc.

This is simple, but I am sort of struggling how to represent this.

Here is a similar sample based on heart attack prediction https://colab.research.google.com/drive/1CQX2d0vkjlZKjX6wbG4ga6tRcI-zOMNA

I tried to add a column to add an array feature, with np.c_ to the end

##################################-Check-########################
print("Before",X_s[:1])
X_s =np.c_[ X_s,np.random.rand(303,2)] # add a numpy array here as a feature
print("After",X_s[:1])
print("shape of X_s",X_s.shape)
print(X_s[:1])
dataset = tf.data.Dataset.from_tensor_slices((X_s, y_s))

But the problems is that the array is added as two extra columns in the end

shape of X_s (303, 13)
shape of X_s (303, 15)

So if I have a feature array of say 330*300 with the above approach it will add 300 columns to the end. Not something I want

I am aware of CNN network, and one option is to model the whole problem as a CNN; that is pad the other features also as arrays and created an n dimension tensor and use a CNN

Is there something simpler and better than these approaches


问:
Behavior changes for Scope annotation in Spring?
I'm trying to upgrade from Spring 2.1.18.RELEASE to 2.7.6. In the code, a custom scope has been defined:

```<code>@Scope("myScope")
public @interface MyScope {}
</code>```

To make it work, a class implementing Scope was also defined and registered as scope in Spring context bean factory.

```<code>public class MyScopeImpl implements Scope {
  @Override
  public synchronized Object get(String name, ObjectFactory<?> objectFactory {
    // code omitted
  }

  // The following methods added too:
  // remove, registerDestructionCallback, resolveContextualObject getConversationId
}
</code>```

A component is also defined:

```<code>@Component
@MyScope
public class MyScopedComponent {
  // Code omitted
}
</code>```

With Spring 2.1.18.RELEASE, everything was working well. A new MyScopedComponent was created according to the context specified in MyScopeImpl.get() method.

With Spring 2.7.6, this behavior somehow changed. It seems that a MyScopedComponent was added as singleton, ignoring its scope. When debugging, I noticed that Spring DefaultSingletonBeanRegistry.singletonObjects contains an instance of MyScopedComponent. It was not the case when using Spring 2.1.18.RELEASE.

Anyone knows how to fix this?

Regards

Francois

UPDATE 2022-12-13 I forgot to mention that Java was upgraded from 11 to 17 in the same update.

Body:
I'm trying to upgrade from Spring 2.1.18.RELEASE to 2.7.6. In the code, a custom scope has been defined:

@Scope("myScope")
public @interface MyScope {}

To make it work, a class implementing Scope was also defined and registered as scope in Spring context bean factory.

public class MyScopeImpl implements Scope {
  @Override
  public synchronized Object get(String name, ObjectFactory<?> objectFactory {
    // code omitted
  }

  // The following methods added too:
  // remove, registerDestructionCallback, resolveContextualObject getConversationId
}

A component is also defined:

@Component
@MyScope
public class MyScopedComponent {
  // Code omitted
}

With Spring 2.1.18.RELEASE, everything was working well. A new MyScopedComponent was created according to the context specified in MyScopeImpl.get() method.

With Spring 2.7.6, this behavior somehow changed. It seems that a MyScopedComponent was added as singleton, ignoring its scope. When debugging, I noticed that Spring DefaultSingletonBeanRegistry.singletonObjects contains an instance of MyScopedComponent. It was not the case when using Spring 2.1.18.RELEASE.

Anyone knows how to fix this?

Regards

Francois

UPDATE 2022-12-13 I forgot to mention that Java was upgraded from 11 to 17 in the same update.


问:
Jupyterlab / Mac / German keyboard: how to comment multiple lines or entire cell?
I'd like to simply select and comment/uncomment multiple python lines in jupyter, which means putting # sign at the beginning of each line. What is the keyboard shortcut for that in German layout (QAY-WSX)? Thanks.

For info: non of these solutions worked

jupyter - how to comment out cells?


问:
How to load the browser when using inertia stack in laravel jetstream application?
I am using Laravel Jetstream and using stack: inertia to build a portal. After login in, I am going to the user profile page where I can update the user information. But the problem is when I am clicking on the navigation menu "Dashboard", the browser is not loading, only the content is changing since I am using inertia. But I want to load the browser when I am clicking on the navigation menu. How to do that?

resources/js/Layouts/AppLayout.vue

```<code><Link :href="route('dashboard')">
</Link>
</code>```

app/config/jetstream.php

```<code><?php
use Laravel\Jetstream\Features;
return [
'stack" => 'inertia',
</code>```

Body:
I am using Laravel Jetstream and using stack: inertia to build a portal. After login in, I am going to the user profile page where I can update the user information. But the problem is when I am clicking on the navigation menu "Dashboard", the browser is not loading, only the content is changing since I am using inertia. But I want to load the browser when I am clicking on the navigation menu. How to do that?

resources/js/Layouts/AppLayout.vue

<Link :href="route('dashboard')">
</Link>

app/config/jetstream.php

<?php
use Laravel\Jetstream\Features;
return [
'stack" => 'inertia',


问:
Keycloak mysql user storage
I need to find or to create mysql user federation SPI for keycloak. A database already exists in my application, and I want to keycloak get user-info from the db.

I found an example
but when I try to add the federation, I have an exception
"Error! Communications link failure The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server."

enter image description here

What I can to do, to fix it? Or maybe there is an explain/documents how to do it use different way.

Title: Keycloak mysql user storage


问:
Public key credential verification using android biometric for StrongKeyFido2 API
I am creating an app that works like an authenticator for the website logins, I have setup a server of https://www.strongkey.com/ and here is the samples I am following https://github.com/StrongKey/fido2/tree/master/sampleapps/java/sacl/mobile/android.
But I am not aware how to achieve this facility, What my application is doing is

Hitting the pre register api and getting the challenge to register
sample response

{"Response":{"rp":{"name":"FIDOServer","id":"fidoidqa.com"},"user":{"name":"devendra","id":"s5wXaholuoVwk86KQ0d_hmIxOkQPNS-bBBes8X4Cex8","displayName":"devendraLiapC"},"challenge":"COJ03Ch_6KDjlvnZ1jg_Qw","pubKeyCredParams":[{"type":"public-key","alg":-7},{"type":"public-key","alg":-35},{"type":"public-key","alg":-36},{"type":"public-key","alg":-8},{"type":"public-key","alg":-47},{"type":"public-key","alg":-257},{"type":"public-key","alg":-258},{"type":"public-key","alg":-259},{"type":"public-key","alg":-37},{"type":"public-key","alg":-38},{"type":"public-key","alg":-38}],"excludeCredentials":[{"type":"public-key","id":"NEVDOUQzNkMzMDBEM0U3MS1FNDczNTQ3QUVDRDQ1ODDRELTk1MEJFOTM2NTI5MEIxNjctMTIxNkNFQjY1ODIzQTI5OQ","alg":-7},{"type":"public-key","id":"MUUzMDY0RkNGQUZEOTM5Ni1FMzlFOUM2MkUwOTQE4NzcwLTA0NzUyMEFBREM0ODUwM0UtMEU4ODdFOEFCRjFCMDE3QQ","alg":-7},{"type":"public-key","id":"hhkXnYmUiu_bzLy5HPHJvZs6TQA-302jRdeLHBgpL40","alg":-257}],"attestation":"direct"}}

Then with this response, I am creating the preregisterchallenge,

```<code>var preregisterChallenge = PreregisterChallenge() val authenticatorSelectionCriteria = AuthenticatorSelectionCriteria() authenticatorSelectionCriteria.authenticatorAttachment = "Android" authenticatorSelectionCriteria.isRequireResidentKey = true authenticatorSelectionCriteria.userVerification = "required" val authSelectionJson = Gson().toJson(authenticatorSelectionCriteria) val myCustomArray: JsonArray = Gson().toJsonTree(userData.Response?.pubKeyCredParams).asJsonArray preregisterChallenge.apply { id = 100 uid = 1001 did = 1003 rpid = userData.Response?.rp?.id userid = "1001" username = "devendra" displayName = "devendra" challenge = userData.Response?.challenge authenticatorSelectionJSONObject = JSONObject(authSelectionJson) authenticatorSelection = authSelectionJson publicKeyCredentialParams = myCustomArray.toString() credParamsJSONArray = JSONArray(myCustomArray.toString()) }
</code>```

And then doing like this

```<code>val publicKeyCredential = AuthenticatorMakeCredential.execute( ContextWrapper(context), preregisterChallenge, "fidoidqa.com" ) as PublicKeyCredential
</code>```

I am getting the publickKeyCredential without any error

Now I want to attest this key with biometric humen presence with this public key, for example now user will touch the biometric to verify this public key and then I will call the register api.
How can I attest the public key credential with the biometric fingerprint and want a signed public key credential for future verification.
Hope this is well explained, Please help me in understanding the flow or process.
Thanks in advance

Body:
I am creating an app that works like an authenticator for the website logins, I have setup a server of https://www.strongkey.com/ and here is the samples I am following https://github.com/StrongKey/fido2/tree/master/sampleapps/java/sacl/mobile/android.
But I am not aware how to achieve this facility, What my application is doing is

Hitting the pre register api and getting the challenge to register
sample response

{"Response":{"rp":{"name":"FIDOServer","id":"fidoidqa.com"},"user":{"name":"devendra","id":"s5wXaholuoVwk86KQ0d_hmIxOkQPNS-bBBes8X4Cex8","displayName":"devendraLiapC"},"challenge":"COJ03Ch_6KDjlvnZ1jg_Qw","pubKeyCredParams":[{"type":"public-key","alg":-7},{"type":"public-key","alg":-35},{"type":"public-key","alg":-36},{"type":"public-key","alg":-8},{"type":"public-key","alg":-47},{"type":"public-key","alg":-257},{"type":"public-key","alg":-258},{"type":"public-key","alg":-259},{"type":"public-key","alg":-37},{"type":"public-key","alg":-38},{"type":"public-key","alg":-38}],"excludeCredentials":[{"type":"public-key","id":"NEVDOUQzNkMzMDBEM0U3MS1FNDczNTQ3QUVDRDQ1ODDRELTk1MEJFOTM2NTI5MEIxNjctMTIxNkNFQjY1ODIzQTI5OQ","alg":-7},{"type":"public-key","id":"MUUzMDY0RkNGQUZEOTM5Ni1FMzlFOUM2MkUwOTQE4NzcwLTA0NzUyMEFBREM0ODUwM0UtMEU4ODdFOEFCRjFCMDE3QQ","alg":-7},{"type":"public-key","id":"hhkXnYmUiu_bzLy5HPHJvZs6TQA-302jRdeLHBgpL40","alg":-257}],"attestation":"direct"}}

Then with this response, I am creating the preregisterchallenge,

var preregisterChallenge = PreregisterChallenge() val authenticatorSelectionCriteria = AuthenticatorSelectionCriteria() authenticatorSelectionCriteria.authenticatorAttachment = "Android" authenticatorSelectionCriteria.isRequireResidentKey = true authenticatorSelectionCriteria.userVerification = "required" val authSelectionJson = Gson().toJson(authenticatorSelectionCriteria) val myCustomArray: JsonArray = Gson().toJsonTree(userData.Response?.pubKeyCredParams).asJsonArray preregisterChallenge.apply { id = 100 uid = 1001 did = 1003 rpid = userData.Response?.rp?.id userid = "1001" username = "devendra" displayName = "devendra" challenge = userData.Response?.challenge authenticatorSelectionJSONObject = JSONObject(authSelectionJson) authenticatorSelection = authSelectionJson publicKeyCredentialParams = myCustomArray.toString() credParamsJSONArray = JSONArray(myCustomArray.toString()) }

And then doing like this

val publicKeyCredential = AuthenticatorMakeCredential.execute( ContextWrapper(context), preregisterChallenge, "fidoidqa.com" ) as PublicKeyCredential

I am getting the publickKeyCredential without any error

Now I want to attest this key with biometric humen presence with this public key, for example now user will touch the biometric to verify this public key and then I will call the register api.
How can I attest the public key credential with the biometric fingerprint and want a signed public key credential for future verification.
Hope this is well explained, Please help me in understanding the flow or process.
Thanks in advance


问:
GitHub actions has not been run
I've faced with interesting problem.
We have a github action with:
on: pull_request: ['closed']
It's successfully run for all our closed/merged PRs, but there is one closed PR without that actions was being run for some mysterious reason.
Has anyone faced with such interesting problem or maybe know what is the reason of it?

Tried to reproduce that, but I have no result. That actions was run for every closed/merged PR except that one.

Title: GitHub actions has not been run


问:
Make a number in a text act as a price in Woocommerce

I have an issue with my multicurrency website.

I fully configured WooCommerce Payments Multi-Currency, and everything functions as intended on my category and product pages.

The problem is that plain numbers and text that were utilized as price indicators on the website outside the woocommerce "scope" inadvertently do not convert on currency switch.
Say, "This thing costs 55 euros."
such as in some of my homepage's titles or in arbitrary text in blog posts.

I tried to add this HTML:

<bdi>55 €</bdi>

It shows the price in € but unfortunately, it does not get converted on currency switch.

Would you know how to "inform" WooCommerce that these numbers are in fact prices that also need to be converted when changing currencie.

Do not hesitate to tell me if it is not clear, English is not my first language!

Thanks!


Title: Changing DrawingImage brush binded to DynamicResource

Body:
I have a DrawingImage object as a resource which uses brush color from DynamicResource like this:

<DrawingImage x:Key="img_building">
    <DrawingImage.Drawing>
        <DrawingGroup ClipGeometry="M0,0 V512 H512 V0 H0 Z">
            <DrawingGroup Opacity="1">
                <GeometryDrawing Geometry="F1 M512,512z M0,0z M256.5,17.2L512,119.4 512,153.8 477.6,153.8C477.6,158.4 475.7,162.2 472,165.9 468.3,169.6 463.6,170.5 459,170.5L53,170.5C48.4,170.5 43.7,168.6 40,165.9 36.3,163.1 34.4,158.5 34.4,153.8L0,153.8 0,119.4 256.5,17.2z M68.8,188.2L136.6,188.2 136.6,392.6 171,392.6 171,188.2 238.8,188.2 238.8,392.6 273.2,392.6 273.2,188.2 341,188.2 341,392.6 375.4,392.6 375.4,188.2 443.2,188.2 443.2,392.6 459,392.6C463.6,392.6 468.3,394.5 472,397.2 475.7,400 477.6,404.6 477.6,409.3L477.6,426 35.3,426 35.3,409.3C35.3,404.7 37.2,400.9 40.9,397.2 44.6,393.5 49.3,392.6 53.9,392.6L69.7,392.6 69.7,188.2 68.8,188.2z M493.4,443.7C498,443.7 502.7,445.6 506.4,448.3 510.1,452 512,455.7 512,460.4L512,494.8 0.9,494.8 0.9,460.4C0.9,455.8 2.8,452 6.5,448.3 10.2,444.6 14.9,443.7 19.5,443.7L493.4,443.7z" >
                    <GeometryDrawing.Brush>
                        <SolidColorBrush Color="{DynamicResource Image.FillColor}" />
                    </GeometryDrawing.Brush>
                </GeometryDrawing>
            </DrawingGroup>
        </DrawingGroup>
    </DrawingImage.Drawing>
</DrawingImage>

And then I'm using this resource in a template like this:

    <DataTemplate x:Key="buildingImage">
        <WrapPanel>
            <WrapPanel.Resources>

            </WrapPanel.Resources>
            <Image Source="{DynamicResource img_building}" />
        </WrapPanel>
    </DataTemplate>

It's running fine but when I change the theme of my app, image remains same although the Image.FillColor changes.
I guess it's rendering the image for once and then uses the same rendered resource over and over again.

How to fix this? Is there a way to force a hard reload on DrawingImage in code behind?


问:
override/redefine a C-Function which has a section attribute
I have the case where I need to overwrite some C-Functions of an SDK we use. The SDK is compiled as a lib and the functions we need to override are marked with
__attribute__((weak))
This works as it should when linking.
We override those functions then later in our files with the wanted definition.

Background:
The reason is that the SDK is not working in a standalone way but always needs a special tool which generates some global objects which are needed in the init-functions of the SDK. And we wanted to get rid of the tool and thus need new init-functions which do not rely on the global objects but on passing the configuration via pointer. Those functions are added additionally and no SDK-functions are removed.

Also the SDK shall not be altered in a way you can't use it anymore with the tool. So it must support both features, with the smallest changes possible which will not break the API and add support for the new API by us without the tool.

So following up, if we now have a function which has already an attribute defined, which references to a section like
void __attribute__((section(".text.random"))) Random_init(){}
it is not possible to override Random_init.
I do not get errors like it was redefined or anything but undefined symbols while linking which refer to those global objects, which of course are not generated anymore and are only used by the function which shall be overriden. And this works for all other 20 init-functions only for this one it does not and the only difference is the attribute already there.

I tried adding it together:
void __attribute__((weak, section(".text.random"))) Random_init()

which also does not work.

I also tried to add the attribute to the redefinition, but this also does not help.
We cannot just erase the section-attribute since it needs to be there for all the entities using the tool.

The compiler we use is a clang based TI LTS1.3.1-compiler.

I would like to provide a minimal example but since this combination only works with the sdk-code beeing compiled to a lib first, I just cannot.

I just try to show it:
SDK-function which is compiled inside the lib, c-file "Random.c":

```<code>extern RandConfig gRandConfig[];
extern int32_t gRandConfigNum;

void __attribute__((weak, section(".text.random"))) Random_init()
{
    uint32_t i;
    for (i = 0; i < gRandConfigNum; i++)
    {
        Random_setSpecial(i,
                (void*)gRandConfig[i].baseAddr,
                gRandConfig[i].size,
                &gRandConfig[i].attrs
        );
    }
}
</code>```

related Header-file, Random.h:

```<code>void Random_init();
</code>```

The gRandConfig and gRandSpecialConfig are produced in code by the tool, which are then linked against the library and we don't want to use them anymore.

All the context where this shall happen is in C but the libs are used from C++-context.
So for example this is how the override would look like in our .cpp-files:

```<code>#include "Random.h"

extern "C"
{

void Random_init()
{

}
}

</code>```

The result when linking:

```<code> undefined            first referenced
  symbol                  in file
 ---------            ----------------
 gRandConfig          ../../../../sdk-build/sdk.lib<Random.obj>
 gRandConfigNum       ../../../../sdk-build/sdk.lib<Random.obj>
</code>```

The included header by the sdk also has guards for __cplusplus. So it shouldn't be a language issue.

Also we issued the compiler to compile with -ffunction-sections which shall at least help to sort unneeded functions out later on. But anyway it does not. Even when the function gets never called by anyone.

A dirty solution would be to just add dummy-variables for this one, so it's satisfied and does not complain but as you can imagine, that would be a workaround which produces a lot of problems later on and also takes space where we need every Byte of space.

Could it be that an section-function-attribute prevents the function from being overriden? I did not find anything at the gnu-documantation which says that one cannot override a function with an attribute.

Body:
I have the case where I need to overwrite some C-Functions of an SDK we use. The SDK is compiled as a lib and the functions we need to override are marked with
__attribute__((weak))
This works as it should when linking.
We override those functions then later in our files with the wanted definition.

Background:
The reason is that the SDK is not working in a standalone way but always needs a special tool which generates some global objects which are needed in the init-functions of the SDK. And we wanted to get rid of the tool and thus need new init-functions which do not rely on the global objects but on passing the configuration via pointer. Those functions are added additionally and no SDK-functions are removed.

Also the SDK shall not be altered in a way you can't use it anymore with the tool. So it must support both features, with the smallest changes possible which will not break the API and add support for the new API by us without the tool.

So following up, if we now have a function which has already an attribute defined, which references to a section like
void __attribute__((section(".text.random"))) Random_init(){}
it is not possible to override Random_init.
I do not get errors like it was redefined or anything but undefined symbols while linking which refer to those global objects, which of course are not generated anymore and are only used by the function which shall be overriden. And this works for all other 20 init-functions only for this one it does not and the only difference is the attribute already there.

I tried adding it together:
void __attribute__((weak, section(".text.random"))) Random_init()

which also does not work.

I also tried to add the attribute to the redefinition, but this also does not help.
We cannot just erase the section-attribute since it needs to be there for all the entities using the tool.

The compiler we use is a clang based TI LTS1.3.1-compiler.

I would like to provide a minimal example but since this combination only works with the sdk-code beeing compiled to a lib first, I just cannot.

I just try to show it:
SDK-function which is compiled inside the lib, c-file "Random.c":

extern RandConfig gRandConfig[];
extern int32_t gRandConfigNum;

void __attribute__((weak, section(".text.random"))) Random_init()
{
    uint32_t i;
    for (i = 0; i < gRandConfigNum; i++)
    {
        Random_setSpecial(i,
                (void*)gRandConfig[i].baseAddr,
                gRandConfig[i].size,
                &gRandConfig[i].attrs
        );
    }
}

related Header-file, Random.h:

void Random_init();

The gRandConfig and gRandSpecialConfig are produced in code by the tool, which are then linked against the library and we don't want to use them anymore.

All the context where this shall happen is in C but the libs are used from C++-context.
So for example this is how the override would look like in our .cpp-files:

#include "Random.h"

extern "C"
{

void Random_init()
{

}
}

The result when linking:

 undefined            first referenced
  symbol                  in file
 ---------            ----------------
 gRandConfig          ../../../../sdk-build/sdk.lib<Random.obj>
 gRandConfigNum       ../../../../sdk-build/sdk.lib<Random.obj>

The included header by the sdk also has guards for __cplusplus. So it shouldn't be a language issue.

Also we issued the compiler to compile with -ffunction-sections which shall at least help to sort unneeded functions out later on. But anyway it does not. Even when the function gets never called by anyone.

A dirty solution would be to just add dummy-variables for this one, so it's satisfied and does not complain but as you can imagine, that would be a workaround which produces a lot of problems later on and also takes space where we need every Byte of space.

Could it be that an section-function-attribute prevents the function from being overriden? I did not find anything at the gnu-documantation which says that one cannot override a function with an attribute.


问:
Why interactive prompt writing in system stdout, except popen stdout
I am trying to write interface to interract with console application.

I want to send some console commands in one terminal session, like user works with terminal. These commands can be used with some console optionse, also without them, using interactive input(like ssh command asks password to connect).

So I tried to use Popen to implement this, but I found problem with commands, that waiting user input. The problem is that interactive prompt prints in system stdout, except p.stdout as I wanted to.

Here you can see example how I did it.

```<code>def setNonBlocking(fd):
    flags = fcntl.fcntl(fd, fcntl.F_GETFL)
    flags = flags | os.O_NONBLOCK
    fcntl.fcntl(fd, fcntl.F_SETFL, flags)

p = Popen('/bin/bash', shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, text=True, bufsize=0)

setNonBlocking(p.stdin)
setNonBlocking(p.stdout)

p.stdin.write('ssh administrator@1.1.1.1 -T\n')

b = p.stdout.read()
</code>```

So what I did wrong and is there any good way to implement this?

Body:
I am trying to write interface to interract with console application.

I want to send some console commands in one terminal session, like user works with terminal. These commands can be used with some console optionse, also without them, using interactive input(like ssh command asks password to connect).

So I tried to use Popen to implement this, but I found problem with commands, that waiting user input. The problem is that interactive prompt prints in system stdout, except p.stdout as I wanted to.

Here you can see example how I did it.

def setNonBlocking(fd):
    flags = fcntl.fcntl(fd, fcntl.F_GETFL)
    flags = flags | os.O_NONBLOCK
    fcntl.fcntl(fd, fcntl.F_SETFL, flags)

p = Popen('/bin/bash', shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, text=True, bufsize=0)

setNonBlocking(p.stdin)
setNonBlocking(p.stdout)

p.stdin.write('ssh administrator@1.1.1.1 -T\n')

b = p.stdout.read()

So what I did wrong and is there any good way to implement this?


问:
Android emulator API 31-33 system brightness slider not updating
on the emulator with API versions 31-33, when running this code, and looking at the notifications shade to check the brightness slider, it seems unchanged.

```<code>if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M || Settings.System.canWrite(context))
{
    Settings.System.putInt(context.contentResolver,Settings.System.SCREEN_BRIGHTNESS_MODE,Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL)
    Settings.System.putInt(context.contentResolver,Settings.System.SCREEN_BRIGHTNESS,somethingBetween0And255())
}
</code>```

after the above code runs, calling Settings.System.getInt does show that the value has been updated, though, but not the brightness slider.

I also checked on my physical phone, which is API 32, and confirmed that the above code works as expected, and the brightness does change, but not sure if it will work on all physical phones of this API.

Body:
on the emulator with API versions 31-33, when running this code, and looking at the notifications shade to check the brightness slider, it seems unchanged.

if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M || Settings.System.canWrite(context))
{
    Settings.System.putInt(context.contentResolver,Settings.System.SCREEN_BRIGHTNESS_MODE,Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL)
    Settings.System.putInt(context.contentResolver,Settings.System.SCREEN_BRIGHTNESS,somethingBetween0And255())
}

after the above code runs, calling Settings.System.getInt does show that the value has been updated, though, but not the brightness slider.

I also checked on my physical phone, which is API 32, and confirmed that the above code works as expected, and the brightness does change, but not sure if it will work on all physical phones of this API.


问:
suppress the 'labelled' from class()
This is with regard to the dataframe 'have' as created below, in this i derived a variable name with a label. so i get the have dataframe with variable name and a label. when i check the class of the variable in the have dataframe i also see the 'labelled' which i dont want to see i only want see the 'character', so please let me know is there a way i apply the label as well but when i use the class then i see only see 'character'

# creating a data frame have
have <- data.frame(name=c('person1','person2','person3','person4'))
# applying a label to the data frame
label(have$name) <- 'Name of person'
# checking the class of the variable within the dataframe
class(have$name)
```

Title: suppress the 'labelled' from class()


问:
Plotting grouped multi-index data with a For loop
I am trying to produce multiple plots from a for loop.

My dataframe is multi-indexed as below:

```<code>          temperature  depth
ID Month
33 2              150     95
   3              148     79
   4              148     54
   5              155     77
55 2              168     37
   3              172     33
   4              107     32
   5              155     77
61 2              168     37
   3              172     33
   4              107     32
   5              155     77
</code>```

I want to loop through each ID and plot:

Temperature as a line against Month (x-axis)

Depth as a bar against Month (x-axis)

I want these to be on the same plot.

This is what I have so far:

```<code># group the dataframe
grp = df.groupby([df.index.get_level_values(0), df.index.get_level_values(1)])

# create empty plots
fig, ax = plt.subplots()

# create an empty plot for combining with ax
ax2 = ax.twinx()

# for loop
for ID, group in grp:
    ax.bar(df.index.get_level_values(1), group["temperature"], color='blue', label='Release')
    ax2.plot(df.index.get_level_values(1), group["depth"], color='green', label='Hold')
    ax.set_xticklabels(df.index.get_level_values(1))
    plt.savefig("value{y}.png".format(y=ID))
    next
</code>```

dataframe reprex:

```<code>import pandas as pd

index = pd.MultiIndex.from_product([[33, 55, 61],['2','3','4', '5']], names=['ID','Month'])

df = pd.DataFrame([[150,   95],
                [148,  79],
                [148,  54],
                [155, 77],
                [168,  37],
                [172,  33],
                [107,  32],
                [155, 77],
                [168,  37],
                [172,  33],
                [107,  32],
                [155, 77]],
                columns=['temperature', 'depth'], index=index)
</code>```

Body:
I am trying to produce multiple plots from a for loop.

My dataframe is multi-indexed as below:

          temperature  depth
ID Month
33 2              150     95
   3              148     79
   4              148     54
   5              155     77
55 2              168     37
   3              172     33
   4              107     32
   5              155     77
61 2              168     37
   3              172     33
   4              107     32
   5              155     77

I want to loop through each ID and plot:

Temperature as a line against Month (x-axis)

Depth as a bar against Month (x-axis)

I want these to be on the same plot.

This is what I have so far:

# group the dataframe
grp = df.groupby([df.index.get_level_values(0), df.index.get_level_values(1)])

# create empty plots
fig, ax = plt.subplots()

# create an empty plot for combining with ax
ax2 = ax.twinx()

# for loop
for ID, group in grp:
    ax.bar(df.index.get_level_values(1), group["temperature"], color='blue', label='Release')
    ax2.plot(df.index.get_level_values(1), group["depth"], color='green', label='Hold')
    ax.set_xticklabels(df.index.get_level_values(1))
    plt.savefig("value{y}.png".format(y=ID))
    next

dataframe reprex:

import pandas as pd

index = pd.MultiIndex.from_product([[33, 55, 61],['2','3','4', '5']], names=['ID','Month'])

df = pd.DataFrame([[150,   95],
                [148,  79],
                [148,  54],
                [155, 77],
                [168,  37],
                [172,  33],
                [107,  32],
                [155, 77],
                [168,  37],
                [172,  33],
                [107,  32],
                [155, 77]],
                columns=['temperature', 'depth'], index=index)


问:
Add timezone offset retroactivly to SQL Server datetime entries
We have our time saved without a timezone offset inside our SQL Server database. The time is actually Central Europe Standard Time but due to no timezone offset in the time string it is treated as UTC. This now creates a bunch of problems regarding daylight saving times.

My question would be: is there a way to retroactively convert the Time with offset to the correct CEST Time.

For example my time string in my database is '2022-10-30 02:00' and should be converted to '2022-10-30 00:00+2' as well as '2022-10-30 03:00' to '2022-10-30 01:00+1'.

There is an option to convert a datetime object to another timezone with "AT TIME ZONE" but this didn't help much due to the date objects being treated as UTC in the database, but we need to convert them to the UTC+[offset] format. Also due to the daylight saving time changing timezone offsets during the year, we can't subtract the timezone offsets with a set value.


问:
How to change the size of UserCreationForm?
I want to modify the weight of the fields in UserCreationForm. How is that possible?

class SignUpForm(UserCreationForm):
    username = forms.CharField( widget=forms.TextInput(attrs={
        "class": "input",
        "type": "text",
        "placeholder": "Username",
    }) )

    email = forms.CharField(widget=forms.TextInput(attrs={
        "class": "input",
        "type": "email",
        "placeholder": "Email"
    }))

    password1 = forms.CharField(widget=forms.TextInput(attrs={
        "class": "input",
        "type": "password",
        "placeholder": "Password"
    }))

    password2 = forms.CharField(widget=forms.TextInput(attrs={
        "class": "input",
        "type": "password",
        "placeholder": "Password"
    }))

    class Meta:
        model= User
        fields = [
            "username", "email", "password1", "password2"
        ]
```

I want to modify the size of the fields: Username, Email, Password 1, and Password 2

More precisely, I want the fields longer. I would appreciate any help.

Body:
I want to modify the weight of the fields in UserCreationForm. How is that possible?

class SignUpForm(UserCreationForm):
    username = forms.CharField( widget=forms.TextInput(attrs={
        "class": "input",
        "type": "text",
        "placeholder": "Username",
    }) )

    email = forms.CharField(widget=forms.TextInput(attrs={
        "class": "input",
        "type": "email",
        "placeholder": "Email"
    }))

    password1 = forms.CharField(widget=forms.TextInput(attrs={
        "class": "input",
        "type": "password",
        "placeholder": "Password"
    }))

    password2 = forms.CharField(widget=forms.TextInput(attrs={
        "class": "input",
        "type": "password",
        "placeholder": "Password"
    }))

    class Meta:
        model= User
        fields = [
            "username", "email", "password1", "password2"
        ]

I want to modify the size of the fields: Username, Email, Password 1, and Password 2

More precisely, I want the fields longer. I would appreciate any help.


问:
How can I select a value from a JObject using another key-value pair from the same object?
Given the JObject balance, how can I select balance where asset = 'XBT'?

```<code>{
    'balance':
    [
        {
            'account_id': '123456789',
            'asset': 'XBT',
            **'balance': '0.00'**,
            'reserved': '0.00',
            'unconfirmed': '0'
        },
        {
            'account_id': '9123456789',
            'asset': 'USD',
            'balance': '0.00',
            'reserved': '0.00',
            'unconfirmed': '0'
        }
    ]
}
</code>```

I was considering using items() but have not had any luck doing so.

Body:
Given the JObject balance, how can I select balance where asset = 'XBT'?

{
    'balance':
    [
        {
            'account_id': '123456789',
            'asset': 'XBT',
            **'balance': '0.00'**,
            'reserved': '0.00',
            'unconfirmed': '0'
        },
        {
            'account_id': '9123456789',
            'asset': 'USD',
            'balance': '0.00',
            'reserved': '0.00',
            'unconfirmed': '0'
        }
    ]
}

I was considering using items() but have not had any luck doing so.


问:
UserManager Owin cannot fetch login credentials on local machine
I basically have two machines 1 for production (on the cloud) and 1 for dev (local) machine.
I also point both of the machines' web.config to the same SQL Server on the cloud.

The problem is whenever I try to fetch user credentials using

```<code>var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
ApplicationUser user = manager.FindByEmail(Email.Text);
</code>```

variable user returns a value on the production, while it returns null / empty on the local.

Both projects are cloned from a GitLab server, so it means I have exact replica of files for both servers, only the web.config differs.

I can verify that both connects to the database, because when I do basic query on both machines, both of them returns a value.

Am I missing a step here? Why does it return null on my local, but it returns a value on the production?

I tried to copy the bin folder of production to my local machine, but it did nothing.

Body:
I basically have two machines 1 for production (on the cloud) and 1 for dev (local) machine.
I also point both of the machines' web.config to the same SQL Server on the cloud.

The problem is whenever I try to fetch user credentials using

var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
ApplicationUser user = manager.FindByEmail(Email.Text);

variable user returns a value on the production, while it returns null / empty on the local.

Both projects are cloned from a GitLab server, so it means I have exact replica of files for both servers, only the web.config differs.

I can verify that both connects to the database, because when I do basic query on both machines, both of them returns a value.

Am I missing a step here? Why does it return null on my local, but it returns a value on the production?

I tried to copy the bin folder of production to my local machine, but it did nothing.


问:
React test crashes: "TypeError: Cannot read property 'getCurrentPosition' of undefined"
I use react-testing library to test the simple App component. Here's it:

```<code>import { useEffect, useState } from 'react';
import './App.css';
import { IWeatherDataObj, MyFormSubmitEvent } from './types/types';
import axios from 'axios';

const App = () => {

  const [weatherData, setWeatherData] = useState({} as IWeatherDataObj);

  const getWeather = async (myCity: string) => {

  const cityUrl = `https://api.openweathermap.org/data/2.5/weather?q=${myCity}&lang=en&appid=${API_WEATHER_KEY}&units=metric`;

  await axios
    .get(cityUrl)
    .then((response) => setWeatherData({
      name: response.data.name,
      country: response.data.sys.country,
      wind: response.data.wind.speed,
      clouds: response.data.weather[0].description,
      temp: Math.round(response.data.main.temp),
      feels_like: Math.round(response.data.main.feels_like),
      pressure: response.data.main.pressure,
      humidity: response.data.main.humidity,
      icon: response.data.weather[0].icon,
      error: undefined
    }))
    .catch(e => console.log(e));
};

  // on the first render, user will see his location and weather
  useEffect(() => {

    let localLatitude: number;
    let localLongitude: number;

    navigator.geolocation.getCurrentPosition(async (position) =>
    {
      localLatitude = position.coords.latitude;
      localLongitude = position.coords.longitude;

      await axios
      .get(`https://api.openweathermap.org/geo/1.0/reverse?lat=${localLatitude}&lon=${localLongitude}&appid=${API_WEATHER_KEY}`)
      .then((response) => {getWeather(response.data[0].name)})
      .catch(e => console.log(e));
    });

    // getWeather('Prague');

  }, []);

  return (
    <div className="App">
          <p>City/Region: <b>{weatherData.name}</b></p>
          <p>Local temperature: <b>{weatherData.temp}°C</b></p>
          <p>Wind: <b>{weatherData.wind} m/s</b></p>
          <p>Sky: <b>{weatherData.clouds}</b></p>
    </div>
  );
}

export default App;
</code>```

In simple terms, getWeather function takes JSON from the site and writes the values I need to the local state weatherData.

I try to test it, here's the App.test.tsx:

```<code>import App from "./App";
import { Provider } from 'react-redux';
import { store } from './store/store';
import { render, screen } from '@testing-library/react';

it('useEffect', async () => {
  render(<Provider store={store}><App /></Provider>);
  expect(await screen.findByText(/Local temperature/i)).toBeInTheDocument();
})
</code>```

When I call getWeather('Prague') or some another city inside useEffect, test is passing ok.

But when I try to use geolocation, I see the error in test:  "TypeError: Cannot read property 'getCurrentPosition' of undefined".

How can I render the component in tests so that it correctly determines the location and loads the data?

Body:
I use react-testing library to test the simple App component. Here's it:

import { useEffect, useState } from 'react';
import './App.css';
import { IWeatherDataObj, MyFormSubmitEvent } from './types/types';
import axios from 'axios';

const App = () => {

  const [weatherData, setWeatherData] = useState({} as IWeatherDataObj);

  const getWeather = async (myCity: string) => {

  const cityUrl = `https://api.openweathermap.org/data/2.5/weather?q=${myCity}&lang=en&appid=${API_WEATHER_KEY}&units=metric`;

  await axios
    .get(cityUrl)
    .then((response) => setWeatherData({
      name: response.data.name,
      country: response.data.sys.country,
      wind: response.data.wind.speed,
      clouds: response.data.weather[0].description,
      temp: Math.round(response.data.main.temp),
      feels_like: Math.round(response.data.main.feels_like),
      pressure: response.data.main.pressure,
      humidity: response.data.main.humidity,
      icon: response.data.weather[0].icon,
      error: undefined
    }))
    .catch(e => console.log(e));
};

  // on the first render, user will see his location and weather
  useEffect(() => {

    let localLatitude: number;
    let localLongitude: number;

    navigator.geolocation.getCurrentPosition(async (position) =>
    {
      localLatitude = position.coords.latitude;
      localLongitude = position.coords.longitude;

      await axios
      .get(`https://api.openweathermap.org/geo/1.0/reverse?lat=${localLatitude}&lon=${localLongitude}&appid=${API_WEATHER_KEY}`)
      .then((response) => {getWeather(response.data[0].name)})
      .catch(e => console.log(e));
    });

    // getWeather('Prague');

  }, []);

  return (

City/Region: {weatherData.name}

Local temperature: {weatherData.temp}°C

Wind: {weatherData.wind} m/s

Sky: {weatherData.clouds}

  );
}

export default App;

In simple terms, getWeather function takes JSON from the site and writes the values I need to the local state weatherData.

I try to test it, here's the App.test.tsx:

import App from "./App";
import { Provider } from 'react-redux';
import { store } from './store/store';
import { render, screen } from '@testing-library/react';

it('useEffect', async () => {
  render(<Provider store={store}><App /></Provider>);
  expect(await screen.findByText(/Local temperature/i)).toBeInTheDocument();
})

When I call getWeather('Prague') or some another city inside useEffect, test is passing ok.

But when I try to use geolocation, I see the error in test:  "TypeError: Cannot read property 'getCurrentPosition' of undefined".

How can I render the component in tests so that it correctly determines the location and loads the data?


问:
Get a span using the span ID in Open Telemetry
Is there any way in Open telemetry to get a span when you have the span ID? I am using Java and
I want to set the parent  , but I receive only the spanID of the parent in my method , so I wonder if there is a way to get the parent span.

```<code>   Span span = tracer.spanBuilder(name)
                .setParent(Context.current().with(parentspan))
                .startSpan();
</code>```

I didn't find any method that allows you to get the span based on the span ID.

Body:
Is there any way in Open telemetry to get a span when you have the span ID? I am using Java and
I want to set the parent  , but I receive only the spanID of the parent in my method , so I wonder if there is a way to get the parent span.

   Span span = tracer.spanBuilder(name)
                .setParent(Context.current().with(parentspan))
                .startSpan();

I didn't find any method that allows you to get the span based on the span ID.


问:
how to select a row in ag-grid react when clicking an icon rendred by ag-groupCellRender
I'M using the ag-grid react  rowSelection={"single"} it works fine but when try the select a row from the fist field of the column that has an icon rendered by ag-group-cellRender it doesnt't select the row

enter image description here

`

```<code>  <AgGridReact detailCellRenderer={'detailCellRenderer'} masterDetail={true} isRowMaster={isRowMaster} rowSelection={"single"} detailRowHeight={270} editType={'fullRow'} tooltipShowDelay={500}
                            onGridReady={onGridReady} rowData={rowData} suppressClickEdit={true} rowClassRules={rowClassRules} pagination={true}>
</code>```

``

```<code>   <AgGridColumn headerName='Line Item' headerTooltip="Line Item's name" headerClass="greyHeader"
                            field='Name' tooltipField='Name' cellEditor='lineItemEditor' cellRenderer="agGroupCellRenderer"
                            cellClass={cellClass} resizable={true} minWidth={150} flex={1}
                                editable={editable == "addLineItem" ? true : editable == "editLineItem" ? true : editable == "addChangeOrder" ? true : editable == "editChangeOrder" ? true : false} />
</code>```

t`

Body:
I'M using the ag-grid react  rowSelection={"single"} it works fine but when try the select a row from the fist field of the column that has an icon rendered by ag-group-cellRender it doesnt't select the row

enter image description here

`

  <AgGridReact detailCellRenderer={'detailCellRenderer'} masterDetail={true} isRowMaster={isRowMaster} rowSelection={"single"} detailRowHeight={270} editType={'fullRow'} tooltipShowDelay={500}
                            onGridReady={onGridReady} rowData={rowData} suppressClickEdit={true} rowClassRules={rowClassRules} pagination={true}>

``

   <AgGridColumn headerName='Line Item' headerTooltip="Line Item's name" headerClass="greyHeader"
                            field='Name' tooltipField='Name' cellEditor='lineItemEditor' cellRenderer="agGroupCellRenderer"
                            cellClass={cellClass} resizable={true} minWidth={150} flex={1}
                                editable={editable == "addLineItem" ? true : editable == "editLineItem" ? true : editable == "addChangeOrder" ? true : editable == "editChangeOrder" ? true : false} />

t`


问:
Change plotly bar chart x axis from weeks to days
I have a table that I'm currently trying to display on a bar chart. It is annual data, with various data from the 1st/jan of one year until the 31st/dec of the same year

```<code>    DATE        COUNT
0   2019-01-01      42
1   2019-02-01      3
2   2019-03-01      31
3   2019-04-01      13
4   2019-05-01      1
...
</code>```

When I plot this with 'date' as the x-axis, plotly is automatically converting the x axis to weeks, so that i have 52 bars instead of 365.

```<code>fig = px.histogram(df, x="DATE", y="COUNT", title="title")
fig.update_layout(bargap=0.30)
fig
</code>```

I've tried updating the ticks with various formats, but this just changes the x axis labels, not the number of bars

I'm not sure how to change it from weekly to daily on the x-axis

Body:
I have a table that I'm currently trying to display on a bar chart. It is annual data, with various data from the 1st/jan of one year until the 31st/dec of the same year

    DATE        COUNT
0   2019-01-01      42
1   2019-02-01      3
2   2019-03-01      31
3   2019-04-01      13
4   2019-05-01      1
...

When I plot this with 'date' as the x-axis, plotly is automatically converting the x axis to weeks, so that i have 52 bars instead of 365.

fig = px.histogram(df, x="DATE", y="COUNT", title="title")
fig.update_layout(bargap=0.30)
fig

I've tried updating the ticks with various formats, but this just changes the x axis labels, not the number of bars

I'm not sure how to change it from weekly to daily on the x-axis


问:
How to get the size of the output after ConvTranspose2d?
I am trying to build a convolutional VAE. The inputs are images (tensors) of dimensions 320x800 and I should get an output size equal to the input size.

The problem is that I can't understand how the output size after ConvTranspose2d is calculated and so the final output size I obtain is different from the input one.

This is my code: by giving as inputs random tensors of size [3, 320, 800] I obtain tensors of size [3, 3, 64, 160]. Note that there are 3 channels because I am using rgb images. I hope you can help me.

```<code>import torch
import torch.nn as nn
import torch.nn.functional as F

init_channels = 64 # initial number of filters
image_channels = 3 # color channels
latent_dim = 100 # number of features to consider

# Define the model

# Initial immage size = 320 x 800

class ConvVAE(nn.Module):
    def __init__(self):
        super(ConvVAE,self).__init__()

        # Encoder

        # output size after this layer: 160 x 400
        self.enc1 = nn.Conv2d(
            in_channels=image_channels, out_channels=init_channels,
            kernel_size=4, stride=2, padding=1
        )

        # output size after this layer: 80 x 200
        self.enc2 = nn.Conv2d(
            in_channels=init_channels, out_channels=init_channels*2,
            kernel_size=4, stride=2, padding=1
        )

        # output size after this layer: 40 x 100
        self.enc3 = nn.Conv2d(
            in_channels=init_channels*2, out_channels=init_channels*4,
            kernel_size=4, stride=2, padding=1
        )

        # output size after this layer: 20 x 50
        self.enc4 = nn.Conv2d(
            in_channels=init_channels*4, out_channels=init_channels*8,
            kernel_size=4, stride=2, padding=1
        )

        # output size after this layer: 10 x 25
        self.enc5 = nn.Conv2d(
            in_channels=init_channels*8, out_channels=init_channels*16,
            kernel_size=4, stride=2, padding=1
        )

         # output size after this layer: 4 x 10
        self.enc6 = nn.Conv2d(
            in_channels=init_channels*16, out_channels=1024,
            kernel_size=(2,5), stride=2, padding=0
        )

        self.fc1 = nn.Linear(1024, 2048)
        self.fc_mu = nn.Linear(2048, latent_dim)
        self.fc_log_var = nn.Linear(2048, latent_dim)
        self.fc2 = nn.Linear(latent_dim, 1024)

        # Decoder

        self.dec1 = nn.ConvTranspose2d(
            in_channels=1024, out_channels=init_channels*16,
            kernel_size=(2,5), stride=2, padding = 0
        )

        self.dec2 = nn.ConvTranspose2d(
            in_channels=init_channels*16, out_channels=init_channels*8,
            kernel_size=4, stride=2, padding = 1
        )

        self.dec3 = nn.ConvTranspose2d(
            in_channels=init_channels*8, out_channels=init_channels*4,
            kernel_size=4, stride=2, padding = 1
        )

        self.dec4 = nn.ConvTranspose2d(
            in_channels=init_channels*4, out_channels=init_channels*2,
            kernel_size=4, stride=2, padding = 1
        )

        self.dec5 = nn.ConvTranspose2d(
            in_channels=init_channels*2, out_channels=init_channels,
            kernel_size=4, stride=2, padding = 1
        )

        self.dec6 = nn.ConvTranspose2d(
            in_channels=init_channels, out_channels=image_channels,
            kernel_size=4, stride=2, padding = 1
        )

    def reparameterize(self, mu, log_var):
        """
        :param mu: mean from the encoder's latent space
        :param log_var: log variance from the encoder's latent space
        """
        std = torch.exp(0.5*log_var) # standard deviation
        eps = torch.randn_like(std) # `randn_like` as we need the same size
        sample = mu + (eps * std) # sampling
        return sample

    def forward(self, x):
        # encoding
        x = F.relu(self.enc1(x))
        x = F.relu(self.enc2(x))
        x = F.relu(self.enc3(x))
        x = F.relu(self.enc4(x))
        x = F.relu(self.enc5(x))
        x = F.relu(self.enc6(x))

        batch, _, _, _ = x.shape
        x = F.adaptive_avg_pool2d(x, 1).reshape(batch, -1)
        hidden = self.fc1(x)

        # get `mu` and `log_var`
        mu = self.fc_mu(hidden)
        log_var = self.fc_log_var(hidden)

        # get the latent vector through reparameterization
        z = self.reparameterize(mu, log_var)
        z = self.fc2(z)

        z = z.view(-1, 1024, 1, 1)

        # decoding
        x = F.relu(self.dec1(z))
        x = F.relu(self.dec2(x))
        x = F.relu(self.dec3(x))
        x = F.relu(self.dec4(x))
        x = F.relu(self.dec5(x))
        reconstruction = torch.sigmoid(self.dec6(x))
        return reconstruction, mu, log_var
</code>```

Body:
I am trying to build a convolutional VAE. The inputs are images (tensors) of dimensions 320x800 and I should get an output size equal to the input size.

The problem is that I can't understand how the output size after ConvTranspose2d is calculated and so the final output size I obtain is different from the input one.

This is my code: by giving as inputs random tensors of size [3, 320, 800] I obtain tensors of size [3, 3, 64, 160]. Note that there are 3 channels because I am using rgb images. I hope you can help me.

import torch
import torch.nn as nn
import torch.nn.functional as F

init_channels = 64 # initial number of filters
image_channels = 3 # color channels
latent_dim = 100 # number of features to consider

# Define the model

# Initial immage size = 320 x 800

class ConvVAE(nn.Module):
    def __init__(self):
        super(ConvVAE,self).__init__()

        # Encoder

        # output size after this layer: 160 x 400
        self.enc1 = nn.Conv2d(
            in_channels=image_channels, out_channels=init_channels,
            kernel_size=4, stride=2, padding=1
        )

        # output size after this layer: 80 x 200
        self.enc2 = nn.Conv2d(
            in_channels=init_channels, out_channels=init_channels*2,
            kernel_size=4, stride=2, padding=1
        )

        # output size after this layer: 40 x 100
        self.enc3 = nn.Conv2d(
            in_channels=init_channels*2, out_channels=init_channels*4,
            kernel_size=4, stride=2, padding=1
        )

        # output size after this layer: 20 x 50
        self.enc4 = nn.Conv2d(
            in_channels=init_channels*4, out_channels=init_channels*8,
            kernel_size=4, stride=2, padding=1
        )

        # output size after this layer: 10 x 25
        self.enc5 = nn.Conv2d(
            in_channels=init_channels*8, out_channels=init_channels*16,
            kernel_size=4, stride=2, padding=1
        )

         # output size after this layer: 4 x 10
        self.enc6 = nn.Conv2d(
            in_channels=init_channels*16, out_channels=1024,
            kernel_size=(2,5), stride=2, padding=0
        )

        self.fc1 = nn.Linear(1024, 2048)
        self.fc_mu = nn.Linear(2048, latent_dim)
        self.fc_log_var = nn.Linear(2048, latent_dim)
        self.fc2 = nn.Linear(latent_dim, 1024)

        # Decoder

        self.dec1 = nn.ConvTranspose2d(
            in_channels=1024, out_channels=init_channels*16,
            kernel_size=(2,5), stride=2, padding = 0
        )

        self.dec2 = nn.ConvTranspose2d(
            in_channels=init_channels*16, out_channels=init_channels*8,
            kernel_size=4, stride=2, padding = 1
        )

        self.dec3 = nn.ConvTranspose2d(
            in_channels=init_channels*8, out_channels=init_channels*4,
            kernel_size=4, stride=2, padding = 1
        )

        self.dec4 = nn.ConvTranspose2d(
            in_channels=init_channels*4, out_channels=init_channels*2,
            kernel_size=4, stride=2, padding = 1
        )

        self.dec5 = nn.ConvTranspose2d(
            in_channels=init_channels*2, out_channels=init_channels,
            kernel_size=4, stride=2, padding = 1
        )

        self.dec6 = nn.ConvTranspose2d(
            in_channels=init_channels, out_channels=image_channels,
            kernel_size=4, stride=2, padding = 1
        )

    def reparameterize(self, mu, log_var):
        """
        :param mu: mean from the encoder's latent space
        :param log_var: log variance from the encoder's latent space
        """
        std = torch.exp(0.5*log_var) # standard deviation
        eps = torch.randn_like(std) # `randn_like` as we need the same size
        sample = mu + (eps * std) # sampling
        return sample

    def forward(self, x):
        # encoding
        x = F.relu(self.enc1(x))
        x = F.relu(self.enc2(x))
        x = F.relu(self.enc3(x))
        x = F.relu(self.enc4(x))
        x = F.relu(self.enc5(x))
        x = F.relu(self.enc6(x))

        batch, _, _, _ = x.shape
        x = F.adaptive_avg_pool2d(x, 1).reshape(batch, -1)
        hidden = self.fc1(x)

        # get `mu` and `log_var`
        mu = self.fc_mu(hidden)
        log_var = self.fc_log_var(hidden)

        # get the latent vector through reparameterization
        z = self.reparameterize(mu, log_var)
        z = self.fc2(z)

        z = z.view(-1, 1024, 1, 1)

        # decoding
        x = F.relu(self.dec1(z))
        x = F.relu(self.dec2(x))
        x = F.relu(self.dec3(x))
        x = F.relu(self.dec4(x))
        x = F.relu(self.dec5(x))
        reconstruction = torch.sigmoid(self.dec6(x))
        return reconstruction, mu, log_var


问:
Azure Event Hub process events indefinitely
I need to create software that can read events from Azure Event Hub in an infinite way and save them on the db following some logic. The first question I wanted to ask is if such thing is feasible using:

EventProcessorClient (or rather EventProcessor<TPartition> as I would always like to use the SqlServer for checkpoints instead of an Azure Blob Storage) in a BackgroundService as Windows Service and then run it in infinitely and every so many events to checkpoint?
I tried this code reading from a single partition but the application crashes after an exception and the loop ends without continuing to process the events.

```<code>public class LogConsumerBackgroundService : BackgroundService
{
    private const string EventHubConnectionString =
        "ConnString";
    private const string ConsumerGroup = "ConsGroup";

    private static readonly JsonSerializerOptions SerializerOptions = new()
    {
        PropertyNameCaseInsensitive = true
    };

    private readonly ILogger<LogConsumerBackgroundService> _logger;
    private readonly IServiceProvider _serviceProvider;
    private int _count;

    public LogConsumerBackgroundService(ILogger<LogConsumerBackgroundService> logger, IServiceProvider serviceProvider)
    {
        Guard.Against.Null(logger);
        Guard.Against.Null(serviceProvider);

        _logger = logger;
        _serviceProvider = serviceProvider;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        try
        {
            var eventHubConsumerClientOptions = new EventHubConsumerClientOptions
            {
                ConnectionOptions =
                {
                    TransportType = EventHubsTransportType.AmqpWebSockets
                }
            };

            await using var consumer = new EventHubConsumerClient(ConsumerGroup, EventHubConnectionString, eventHubConsumerClientOptions);

            var startingPosition = EventPosition.Earliest;

            var partitionIds = await consumer.GetPartitionIdsAsync(CancellationToken.None);

            var partitionId = partitionIds.First();

            var scope = _serviceProvider.CreateScope();

            var repository = scope.ServiceProvider.GetRequiredService<IRepository>();

            while (!stoppingToken.IsCancellationRequested)
            {
                await foreach (var receivedEvent in consumer.ReadEventsFromPartitionAsync(partitionId, startingPosition,
                                   CancellationToken.None))
                {
                    try
                    {
                        // Some logic to save data on bd

                        _logger.LogInformation("Processed row: {Count}", countInfo += _count);

                        await repository.SaveChangesAsync();

                    }
                    catch (Exception e)
                    {
                        _logger.LogError(e.Demystify(), "{EventBody}", receivedEvent.Data?.EventBody);
                    }
                }
            }
        }
        catch (TaskCanceledException e)
        {
            _logger.LogError(e.Demystify(), "Task was canceled");
        }
        catch (Exception e)
        {
            _logger.LogError(e.Demystify(), "An unhandled exception has occurred");
        }
    }
}
</code>```

Body:
I need to create software that can read events from Azure Event Hub in an infinite way and save them on the db following some logic. The first question I wanted to ask is if such thing is feasible using:

EventProcessorClient (or rather EventProcessor<TPartition> as I would always like to use the SqlServer for checkpoints instead of an Azure Blob Storage) in a BackgroundService as Windows Service and then run it in infinitely and every so many events to checkpoint?
I tried this code reading from a single partition but the application crashes after an exception and the loop ends without continuing to process the events.

public class LogConsumerBackgroundService : BackgroundService
{
    private const string EventHubConnectionString =
        "ConnString";
    private const string ConsumerGroup = "ConsGroup";

    private static readonly JsonSerializerOptions SerializerOptions = new()
    {
        PropertyNameCaseInsensitive = true
    };

    private readonly ILogger<LogConsumerBackgroundService> _logger;
    private readonly IServiceProvider _serviceProvider;
    private int _count;

    public LogConsumerBackgroundService(ILogger<LogConsumerBackgroundService> logger, IServiceProvider serviceProvider)
    {
        Guard.Against.Null(logger);
        Guard.Against.Null(serviceProvider);

        _logger = logger;
        _serviceProvider = serviceProvider;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        try
        {
            var eventHubConsumerClientOptions = new EventHubConsumerClientOptions
            {
                ConnectionOptions =
                {
                    TransportType = EventHubsTransportType.AmqpWebSockets
                }
            };

            await using var consumer = new EventHubConsumerClient(ConsumerGroup, EventHubConnectionString, eventHubConsumerClientOptions);

            var startingPosition = EventPosition.Earliest;

            var partitionIds = await consumer.GetPartitionIdsAsync(CancellationToken.None);

            var partitionId = partitionIds.First();

            var scope = _serviceProvider.CreateScope();

            var repository = scope.ServiceProvider.GetRequiredService<IRepository>();

            while (!stoppingToken.IsCancellationRequested)
            {
                await foreach (var receivedEvent in consumer.ReadEventsFromPartitionAsync(partitionId, startingPosition,
                                   CancellationToken.None))
                {
                    try
                    {
                        // Some logic to save data on bd

                        _logger.LogInformation("Processed row: {Count}", countInfo += _count);

                        await repository.SaveChangesAsync();

                    }
                    catch (Exception e)
                    {
                        _logger.LogError(e.Demystify(), "{EventBody}", receivedEvent.Data?.EventBody);
                    }
                }
            }
        }
        catch (TaskCanceledException e)
        {
            _logger.LogError(e.Demystify(), "Task was canceled");
        }
        catch (Exception e)
        {
            _logger.LogError(e.Demystify(), "An unhandled exception has occurred");
        }
    }
}


问:
preventDefault() was working properly, now only works intermittently
In my app I have been using preventDefault() for a few years to use my custom pop up to appear on a right click.

In my init function:

```<code>element.contextmenu(getRightClickOrd.bind(this));
</code>```

and

```<code>function getRightClickOrd(mouseEvent) {
"use strict";
   var widgetId = mouseEvent.target.parentNode.id;

   //prevent default contextmenu appearing
   mouseEvent.preventDefault();
   mouseEvent.stopPropagation();

   customPopup(widgetId, "command");
}
</code>```

Now it only works intermittently, with both the default menu and my custom pop up both appearing sometimes.

Body:
In my app I have been using preventDefault() for a few years to use my custom pop up to appear on a right click.

In my init function:

element.contextmenu(getRightClickOrd.bind(this));

and

function getRightClickOrd(mouseEvent) {
"use strict";
   var widgetId = mouseEvent.target.parentNode.id;

   //prevent default contextmenu appearing
   mouseEvent.preventDefault();
   mouseEvent.stopPropagation();

   customPopup(widgetId, "command");
}

Now it only works intermittently, with both the default menu and my custom pop up both appearing sometimes.