问:
python module autopep8 problem in Linux terminal
I run ubuntu by wsl 2. I use python 3.10 version. Now when I run autopep8 the problem of your below picture comes. How can it be fixed?
when I type autopep8 --in-place -a filename.py ,this problem appears

```<code>Traceback (most recent call last):
  File "/home/asib/.local/bin/autopep8", line 8, in <module>
    sys.exit(main())
  File "/home/asib/.local/lib/python3.10/site-packages/autopep8.py", line 4518, in main
    results = fix_multiple_files(args.files, args, sys.stdout)
  File "/home/asib/.local/lib/python3.10/site-packages/autopep8.py", line 4413, in fix_multiple_files
    ret = _fix_file((name, options, output))
  File "/home/asib/.local/lib/python3.10/site-packages/autopep8.py", line 4383, in _fix_file
    return fix_file(*parameters)
  File "/home/asib/.local/lib/python3.10/site-packages/autopep8.py", line 3569, in fix_file
    original_source = readlines_from_file(filename)
  File "/home/asib/.local/lib/python3.10/site-packages/autopep8.py", line 195, in readlines_from_file
    with open_with_encoding(filename) as input_file:
  File "/home/asib/.local/lib/python3.10/site-packages/autopep8.py", line 172, in open_with_encoding
    encoding = detect_encoding(filename, limit_byte_check=limit_byte_check)
  File "/home/asib/.local/lib/python3.10/site-packages/autopep8.py", line 182, in detect_encoding
    from lib2to3.pgen2 import tokenize as lib2to3_tokenize
ModuleNotFoundError: No module named 'lib2to3'
</code>```

I want when I give autopep8 command, it will work.
For example: autopep8 --in-place -a filename.py

Body:
I run ubuntu by wsl 2. I use python 3.10 version. Now when I run autopep8 the problem of your below picture comes. How can it be fixed?
when I type autopep8 --in-place -a filename.py ,this problem appears

Traceback (most recent call last):
  File "/home/asib/.local/bin/autopep8", line 8, in <module>
    sys.exit(main())
  File "/home/asib/.local/lib/python3.10/site-packages/autopep8.py", line 4518, in main
    results = fix_multiple_files(args.files, args, sys.stdout)
  File "/home/asib/.local/lib/python3.10/site-packages/autopep8.py", line 4413, in fix_multiple_files
    ret = _fix_file((name, options, output))
  File "/home/asib/.local/lib/python3.10/site-packages/autopep8.py", line 4383, in _fix_file
    return fix_file(*parameters)
  File "/home/asib/.local/lib/python3.10/site-packages/autopep8.py", line 3569, in fix_file
    original_source = readlines_from_file(filename)
  File "/home/asib/.local/lib/python3.10/site-packages/autopep8.py", line 195, in readlines_from_file
    with open_with_encoding(filename) as input_file:
  File "/home/asib/.local/lib/python3.10/site-packages/autopep8.py", line 172, in open_with_encoding
    encoding = detect_encoding(filename, limit_byte_check=limit_byte_check)
  File "/home/asib/.local/lib/python3.10/site-packages/autopep8.py", line 182, in detect_encoding
    from lib2to3.pgen2 import tokenize as lib2to3_tokenize
ModuleNotFoundError: No module named 'lib2to3'

I want when I give autopep8 command, it will work.
For example: autopep8 --in-place -a filename.py


来源: stackexchange

问:
Create Pip package dependent on Shared Library
I have a C++ project that I have successfully created a Python binding for using Swig. I am able to create a Pip installation for the Python binding of my overall project but it is failing to copy the shared object needed for the binding to work.

When creating a Python binding for a C++ project with Swig there is a shared library created as well as a .py file that acts as the callable definitions for the Python API (think of it as a ).

Here is an example of what my setup.py file looks like:

import setuptools

setuptools.setup(
    name='example',
    version='0.0.1',
    author='me',
    description='brief description',
    keywords='example, pypi, package',
    long_description=long_description,
    long_description_content_type='text/markdown',
    url='repo.com',
    project_urls={
        'Documentation': 'docs.com',
        'Bug Reports':'repo/issues.com',
        'Source Code': 'repo.com',
    },
    # location of Python API related files
    package_dir={'': 'Python'},
    packages=setuptools.find_packages(where='Python'),
    package_data={'': ['path/to/_example.so']},
    classifiers=[
        # see https://pypi.org/classifiers/
        'Development Status :: 5 - Production/Stable',

        'Intended Audience :: Developers',
        'Topic :: Software Development :: Build Tools',

        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
        'Programming Language :: Python :: 3.8',
        'Programming Language :: Python :: 3.9',
        'Programming Language :: Python :: 3.10',
        'Programming Language :: Python :: 3 :: Only',
        'Operating System :: OS Independent',
    ],
    python_requires='>=3.6',
)

```

How can I modify my setup.py file to include the Swig binding creation process that creates a Pip package out of my project.

ContentLicense: CC BY-SA 4.0

Body:
I have a C++ project that I have successfully created a Python binding for using Swig. I am able to create a Pip installation for the Python binding of my overall project but it is failing to copy the shared object needed for the binding to work.

When creating a Python binding for a C++ project with Swig there is a shared library created as well as a .py file that acts as the callable definitions for the Python API (think of it as a ).

Here is an example of what my setup.py file looks like:

import setuptools

setuptools.setup(
    name='example',
    version='0.0.1',
    author='me',
    description='brief description',
    keywords='example, pypi, package',
    long_description=long_description,
    long_description_content_type='text/markdown',
    url='repo.com',
    project_urls={
        'Documentation': 'docs.com',
        'Bug Reports':'repo/issues.com',
        'Source Code': 'repo.com',
    },
    # location of Python API related files
    package_dir={'': 'Python'},
    packages=setuptools.find_packages(where='Python'),
    package_data={'': ['path/to/_example.so']},
    classifiers=[
        # see https://pypi.org/classifiers/
        'Development Status :: 5 - Production/Stable',

        'Intended Audience :: Developers',
        'Topic :: Software Development :: Build Tools',

        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
        'Programming Language :: Python :: 3.8',
        'Programming Language :: Python :: 3.9',
        'Programming Language :: Python :: 3.10',
        'Programming Language :: Python :: 3 :: Only',
        'Operating System :: OS Independent',
    ],
    python_requires='>=3.6',
)

How can I modify my setup.py file to include the Swig binding creation process that creates a Pip package out of my project.


问:
Access page from Symfony 6 bundle - get route and twig in custom bundle
I created a bundle,
I want to create a route through the controller in the bundle and present it to the user with the twig file from the bundle.

Symfony is running my bundle successfully.
I am loading services.yaml and routes.yaml in the extension.

Error:
There is no extension able to load the configuration for "bundle_test" (in "hiddenpath\vendor\bundle-test\src\DependencyInjection/../Resources/config\routes.yaml"). Looked for namespace "bundle_test", found "none".

There is a point I missed and the documents don't tell me anything.

files:
bundle file:
src/BundleTestBundle
config files:

Resources/config/routes.yaml:
 bundle_test: resource: "@BundleTestBundle/Controller/" type: annotation

Resources/config/services.yaml
...
Extension & Configuration file:
src/DependencyInjection/BundleTestExtension.php (extends Extension)
src/DependencyInjection/Configuration.php

Controller:
src/Controller/TestController.php (extends AbstractController)

Servisleri okumayı ve yaml ve xml ile yapılandırmayı denedim.
Yapılandırma ve uzantı dosyalarıyla çok uğraştım.

istediğim şey bundle ile oluşturulmuş bir controller ve bundle üzerindeki bir twig'in çalışması

ex:
http://.........../routeInBundle
--> vendor/testbundle/../test_bundle.html.twig


问:
How to use playoutDelayHint and jitterBufferDelayHint in a Native WebRtc Java project
I'm currently using a self compiled WebRtc lib for my Android project and I try to get lowest latency for game streaming/ cloud gaming. I found out that on browsers you can use playoutDelayHint and or jitterBufferDelayHint to fine tune latency and how the underlying peer connection will handle things.

https://discourse.wicg.io/t/hint-attribute-in-webrtc-to-influence-underlying-audio-video-buffering/4038

Unfortunately I have no idea of how to use these functionality within a native WebRtc project (no browser)?

Is there a way to access and modify these flags in a native project and if not what actually must be adjusted in the WebRtc lib to achieve the same result? As I compile the WebRtc lib by my own I could just add this functionality by my own, I just don't have any idea what the playoutDelayHint and jitterBufferDelayHint flag is modifying in the background?

I found this in the native code which could be the correct part for the playbackDelayHint but not sure

https://github.com/maitrungduc1410/webrtc/blob/c2b1bad4c87a43d7e1af85e809d5abe04baf3104/api/video/video_timing.h#L116


问:
fontFamily "lonicons" is not a system font and has not been loaded through Font.loadAsync
My react native project all of a sudden stopped loading all vector icons with this error

```<code>fontFamily "Material Design Icons"     is not a system font and has not been      loaded through Font.loadAsync.
</code>```

And i have no idea what could be causing it.

I have deleted node_modules and ran ‘npm install’ still dose not load icons. This is how icons look like in my app

Please what else do i do to fix this

Body:
My react native project all of a sudden stopped loading all vector icons with this error

fontFamily "Material Design Icons"     is not a system font and has not been      loaded through Font.loadAsync.

And i have no idea what could be causing it.

I have deleted node_modules and ran ‘npm install’ still dose not load icons. This is how icons look like in my app

Please what else do i do to fix this


问:
VBA in Microsoft word. Input Table and Output Table
Im trying to create a form where I can fill in 10 variables into an input table, and this will populate an output table depending on combinations of inputs. I have written some code that i cannot for the life of me figure out why it wont work. My input table, table1, has 2 columns and 10 rows, and my output table has 3 columns and 20 rows.

This is the code so far. It is a basic start to try and get at least the first output to work, and will then be developed to include all variables.

```<code>Sub SelectInputsAndOutputs()

    Dim tbl1 As Table, tbl2 As Table
    Dim rng As Range
    Dim row As Long, col As Long
    Dim input1 As String, input2 As String

    ' Set tbl1 to the first table in the document
    Set tbl1 = ActiveDocument.Tables(1)

    ' Set tbl2 to the second table in the document
    Set tbl2 = ActiveDocument.Tables(2)

    ' Loop through each row in tbl1
    For row = 1 To tbl1.Rows.Count
        ' Set rng to the second cell in the current row
        Set rng = tbl1.Cell(row, 2).Range
        ' Read the input value from rng and store it in the appropriate variable
        If row = 1 Then
            input1 = rng.Text
        ElseIf row = 2 Then
            input2 = rng.Text
        End If
    Next

    ' Calculate the output value based on the inputs
    Dim output As String
    If input1 = "PiP" And input2 = "CMn" Then
        output = "Min:11.7"
    ElseIf input1 = "PiP" And input2 = "13Cr" Then
        output = "13Cr is the best"
    End If

    ' Write the output value to the third column of tbl2
    tbl2.Cell(1, 3).Range.Text = output

    End Sub
</code>```

Basically, nothing happens. My Tables look like this:

```<code>---------------------
:Type    :PiP     :
------------------
:Design  : 13Cr   :
-------------------
</code>```

and so on.....

My output table is just a blank 3x20 table.

Body:
Im trying to create a form where I can fill in 10 variables into an input table, and this will populate an output table depending on combinations of inputs. I have written some code that i cannot for the life of me figure out why it wont work. My input table, table1, has 2 columns and 10 rows, and my output table has 3 columns and 20 rows.

This is the code so far. It is a basic start to try and get at least the first output to work, and will then be developed to include all variables.

Sub SelectInputsAndOutputs()

    Dim tbl1 As Table, tbl2 As Table
    Dim rng As Range
    Dim row As Long, col As Long
    Dim input1 As String, input2 As String

    ' Set tbl1 to the first table in the document
    Set tbl1 = ActiveDocument.Tables(1)

    ' Set tbl2 to the second table in the document
    Set tbl2 = ActiveDocument.Tables(2)

    ' Loop through each row in tbl1
    For row = 1 To tbl1.Rows.Count
        ' Set rng to the second cell in the current row
        Set rng = tbl1.Cell(row, 2).Range
        ' Read the input value from rng and store it in the appropriate variable
        If row = 1 Then
            input1 = rng.Text
        ElseIf row = 2 Then
            input2 = rng.Text
        End If
    Next

    ' Calculate the output value based on the inputs
    Dim output As String
    If input1 = "PiP" And input2 = "CMn" Then
        output = "Min:11.7"
    ElseIf input1 = "PiP" And input2 = "13Cr" Then
        output = "13Cr is the best"
    End If

    ' Write the output value to the third column of tbl2
    tbl2.Cell(1, 3).Range.Text = output

    End Sub

Basically, nothing happens. My Tables look like this:

---------------------
:Type    :PiP     :
------------------
:Design  : 13Cr   :
-------------------

and so on.....

My output table is just a blank 3x20 table.


问:
Error while rendering buffer in chartjs-node-canvas
I am trying to render a line graph image using the renderToBuffer method in ChartJSNodeCanvas. It works fine locally, but when I have deployed I am getting the following error:

Can anyone help me in fixing this issue?


问:
Laravel Redis Session
In our application, we are using Redis to store the sessions. I have a request that requires running one background job for a user and at the end of the job I need to invalidate all active sessions for the user.

Any ideas on how can I get all sessions for a user from Redis in order to delete them?

Title: Laravel Redis Session


问:
Android Mapbox, Setting LineLayer on Snapshot results
Environment: Mapbox Sdk Ver: 10.10.0

I'm now struggling with snapshot results using [Snapshotter] which is embedded class of mapbox.map

I can check LineLayer has drawn perfectly on my MapView before taking snapshots, but after I take a snapshot and check on my local directory(I can see .PNG image files taken), LineLayer is never drawn on the map...

I've also checked documents(of course I might've missed)
and found these
https://docs.mapbox.com/android/legacy/maps/examples/share-a-snapshot/,
Mapbox: Problem with Line rendering on a Snapshot
It seemed pretty possible to get the result I wanted otherwise it was legacy code and I was not able to find replaceable methods for .withStyleBuilder(builder1);

I really appreciate any advices or help


问:
qwtknob set precision
In the default case qwtknob precision is two decimal places, I need to be accurate to three decimal places.

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

knobtest::knobtest(QWidget *parent, Qt::WFlags flags)
    : QMainWindow(parent, flags)
{
    ui.setupUi(this);
    connect(ui.Knob, SIGNAL(sliderMoved(double)), this, SLOT(knobChange(double)));
}

knobtest::~knobtest()
{

}

void knobtest::knobChange(double value)
{
    ui.lcdNumber->display(value);
}
</code>```

how should I write the code?

Title: qwtknob set precision

Body:
In the default case qwtknob precision is two decimal places, I need to be accurate to three decimal places.

#include "knobtest.h"

knobtest::knobtest(QWidget *parent, Qt::WFlags flags)
    : QMainWindow(parent, flags)
{
    ui.setupUi(this);
    connect(ui.Knob, SIGNAL(sliderMoved(double)), this, SLOT(knobChange(double)));
}

knobtest::~knobtest()
{

}

void knobtest::knobChange(double value)
{
    ui.lcdNumber->display(value);
}

how should I write the code?


问:
NodeList iteration behaving differently across js files
I've been trying to iterate over a NodeListOf<HTMLElement> . I can get the NodeList but not iterate over it using methods.

When I try examples from other stackoverflow questions or mdn web docs, they work but only when I iterate over the Nodelist in the same javascript file it was created.

The following code and the ones in the comments work, but not when I try to get at the nodelist which was written in main.js from another file called drawer.js . So it seems like that's what the problem is, and other stackoverflow questions don't specify if they are having problems across files.

The nodelist comes from these elements in main.js:

```<code>    const Bars = az.map((element, i) =>

        (
            <div name="barHolder" className="barHolder" >
                <div className="bar" key={element} id={element} onClick={() => clickedBar(element, i)} >
                    <div>{element}</div>
                        { element === viewAvailable && (
                            barInfo(element)
                        )}
                </div>
            </div>
        )
    )
</code>```

in drawer.js:

```<code>const barTags = document.getElementsByName('barHolder')

barTags.addEventListener("click", () => { console.log("clicked")}
</code>```

another way:

```<code>barTags.forEach(
    function () {
        console.log("ffs");
    },
'myThisArg'
);
</code>```

and using jquery after making the elements I wanted to select into a list:

```<code>$( document ).ready(function() {

    $( "li" ).each(function( index ) {
        console.log( "clicked");
    });

});
</code>```

When run const List = document.getElementById("list") in main.js, it works. When I run the code from drawer.js, I get Uncaught TypeError: e is null.

I'm trying to reach the NodeList because I would like add an event listener so that when they are clicked, it swipes down the drawer they are in.

This is using preact and parcel. The drawer is Material Ui /MUI

Body:
I've been trying to iterate over a NodeListOf<HTMLElement> . I can get the NodeList but not iterate over it using methods.

When I try examples from other stackoverflow questions or mdn web docs, they work but only when I iterate over the Nodelist in the same javascript file it was created.

The following code and the ones in the comments work, but not when I try to get at the nodelist which was written in main.js from another file called drawer.js . So it seems like that's what the problem is, and other stackoverflow questions don't specify if they are having problems across files.

The nodelist comes from these elements in main.js:

    const Bars = az.map((element, i) =>

        (

 clickedBar(element, i)} >

{element}

                        { element === viewAvailable && (
                            barInfo(element)
                        )}

        )
    )

in drawer.js:

const barTags = document.getElementsByName('barHolder')

barTags.addEventListener("click", () => { console.log("clicked")}

another way:

barTags.forEach(
    function () {
        console.log("ffs");
    },
'myThisArg'
);

and using jquery after making the elements I wanted to select into a list:

$( document ).ready(function() {

    $( "li" ).each(function( index ) {
        console.log( "clicked");
    });

});

When run const List = document.getElementById("list") in main.js, it works. When I run the code from drawer.js, I get Uncaught TypeError: e is null.

I'm trying to reach the NodeList because I would like add an event listener so that when they are clicked, it swipes down the drawer they are in.

This is using preact and parcel. The drawer is Material Ui /MUI


问:
In my code, you can set a score for 1 test, but I need for three tests
I need to modify my code . So that the user enters the number of students and their grades on three tests, and the program writes to him how many students have entered the institute (passing score = 7, maximum score = 10). I wrote the code for one test and don't know how to write for three.
This problem is under the comment: "//Information input and calculation"

```<code>import java.util.Scanner;

public class Attestation {

    static double InputNumber(String caption) {
        System.out.print(caption);
        Scanner sc = new Scanner(System.in);

        boolean IsError;
        do {
            IsError = !sc.hasNextDouble();
            if (IsError) {
                System.out.print("ERROR: ");
                sc.nextLine();
            }
        } while (IsError);

        return sc.nextDouble();
    }

    public static void main(String[] args) {

    // Entering quantities of numbers
        int count = (int) InputNumber("enter the number of students: ");

    // Header
        System.out.println("Test №1\t │ Test №2\t │ Test №3");
        System.out.println("---------------------------------------------");

    // Information input and calculation
        int passed = 0;
        for (int i = 1; i <= count; i = i + 1) {
            double number = InputNumber("enter the grades of the " + i + " student: ");
        if(number >= 7) {
        passed = passed + 1;

        }

    }

    // Displaying information
            System.out.println("---");
            System.out.println(passed + " students entered the institute");

        }

    }

</code>```

I tried to modify the code, but I was constantly getting an error

Body:
I need to modify my code . So that the user enters the number of students and their grades on three tests, and the program writes to him how many students have entered the institute (passing score = 7, maximum score = 10). I wrote the code for one test and don't know how to write for three.
This problem is under the comment: "//Information input and calculation"

import java.util.Scanner;

public class Attestation {

    static double InputNumber(String caption) {
        System.out.print(caption);
        Scanner sc = new Scanner(System.in);

        boolean IsError;
        do {
            IsError = !sc.hasNextDouble();
            if (IsError) {
                System.out.print("ERROR: ");
                sc.nextLine();
            }
        } while (IsError);

        return sc.nextDouble();
    }

    public static void main(String[] args) {

    // Entering quantities of numbers
        int count = (int) InputNumber("enter the number of students: ");

    // Header
        System.out.println("Test №1\t │ Test №2\t │ Test №3");
        System.out.println("---------------------------------------------");

    // Information input and calculation
        int passed = 0;
        for (int i = 1; i <= count; i = i + 1) {
            double number = InputNumber("enter the grades of the " + i + " student: ");
        if(number >= 7) {
        passed = passed + 1;

        }

    }

    // Displaying information
            System.out.println("---");
            System.out.println(passed + " students entered the institute");

        }

    }

I tried to modify the code, but I was constantly getting an error


问:
Redirect User to special content after he installed App
For example:
I have User A and User B.
Both Users get a link to Google Play to download my App.
After launching it first time without login or registration i want to redirect User B to other content than User A (Getting Data from DB).
How can I handle it without Firebase Dynamic Links?
How would the link look like?
How to handle it in React-Native?

I tried to find a solution and found Firebase Dynamic Links but would like to realize it without Firebase.


问:
Merging dataset into Dimension table with potentially duplicate PK's due to dimension history
I'm playing around with some snowflake ingestion from S3 using snowpipe and I've hit a slight snag with handling the edge case of multiple updates to a given dimension arriving at the same time.

The Background:

i have a source dumping heaps of parquet files in an S3 Bucket. Ideally we want to process these files and load them into snowflake, using snowpipe. For simplicty sake lets say the data has the below shape:

ID
FIRST_NAME
LAST_NAME
MODIFIED_ON
IS_DELETED

1
John
doe
2022-11-01
False

2
jane
doe
2022-11-01
False

I'm currently reading these files and their data raw into snowflake using snowpipe and COPY INTO from the S3 bucket. Storing them as a raw Variant with an INGEST_TIMESTAMP column in a table called RAW_PEOPLE.

PARQUET_RAW
INGEST_TIMESTAMP

{data:stuff}
2022-11-01 22:50:00

I have a steam configured off this table, which is driving a snowflake Task every few minutes to flatten out the Variant Data into a table called STG_PEOPLE. So now i have a table with:

ID
FIRST_NAME
LAST_NAME
MODIFIED_ON
IS_DELETED
INGEST_TIMESTAMP

1
John
doe
2022-11-01
False
2022-11-01 22:50:00

2
jane
doe
2022-11-01
False
2022-11-01 22:50:00

I have also configured a stream of this table to track CDC and would like to make a merge procedure to handle move this dataset into the final table outlined below:

Finally I have a target DIM_PEOPLE table which is a type 2 SCD table with the following columns:

ID, FIRST_NAME, LAST_NAME, MODIFIED_ON, IS_DELETED, RECORD_CREATED_TS,  RECORD_ACTIVE_FROM_TS, RECORD_ACTIVE_TO_TS

ID
FIRST_NAME
LAST_NAME
MODIFIED_ON
IS_DELETED
RECORD_ACTIVE_FROM_TS
RECORD_ACTIVE_TO_TS
RECORD_ACTIVE_FLAG

1
John
doe
2022-11-01
False
1900-01-01

Y

2
jane
doe
2022-11-01
False
1900-01-01

Y

I made up a very basic diagram to illustrate:

high level diagram

The Problem:

I cannot gurantee that the source wont drop multiple updates to the same ID in the same file, or that we might have multiple files build up that contain the updates to the same ID.

So in a given ingest run i could get the below data turn up in STG_PEOPLE that i want to merge into DIM_PEOPLE:

ID
FIRST_NAME
LAST_NAME
MODIFIED_ON
IS_DELETED
INGEST_TIMESTAMP

1
John-joe
doe
2022-11-02
False
2022-11-02 23:00

2
jane
doe
2022-11-01
False
2022-11-02 23:00

1
john-bill-joe
doe
2022-11-03
False
2022-12-03 23:00

I dont want to discard historical changes either. But I'm struggling on how to gracefully merge this STG_PEOPLE set into the DIM_PEOPLE set in a single merge statement?

As determining record active from periods for ID = 1, my plan is to set the latest ingest timestamp to active, and set the earlier duplicate record to have an active duration of 0, ie it has the same EFFECTIVE FROM and EFFECTIVE TO

My ideal dataset might be something like the below?

ID
FIRST_NAME
LAST_NAME
MODIFIED_ON
IS_DELETED
RECORD_ACTIVE_FROM_TS
RECORD_ACTIVE_TO_TS
RECORD_ACTIVE_FLAG

1
john-bill-joe
doe
2022-11-03
False
2022-11-02 23:00

Y

1
John-joe
doe
2022-11-02
False
2022-11-02 23:00
2022-11-02 23:00
N

1
John
doe
2022-11-01
False
1900-01-01
2022-11-02 23:00
N

2
jane
doe
2022-11-01
False
1900-01-01

Y

So my question is, within snowflake how would you execute a merge gracefully from a CDC stream if you capture multiple updates to the same record in the stream? Potentially i could union select both the target and source together and do some ranking in the merge, but it seems a bit heavyweight?

Thanks for taking the time to read my stream of consciousness, any help would be appreciated.

I have tried to merge this data using a ranking merge outlined below:

```<code>SET curr_time = CURRENT_TIMESTAMP()

MERGE INTO DIM_PEOPLE TARGET
        USING (
    SELECT
        PARQUET_RAW:id ID,
        PARQUET_RAW:first_name::STRING FIRST_NAME,
        PARQUET_RAW:last_name::STRING LAST_NAME,
        PARQUET_RAW:created_by::STRING CREATED_BY,
        TO_TIMESTAMP(PARQUET_RAW:created_on::NUMBER,3) CREATED_ON,
        TO_TIMESTAMP(PARQUET_RAW:modified_on::NUMBER,3) MODIFIED_ON,
        PARQUET_RAW:modified_by::STRING MODIFIED_BY,
        RANK() OVER (PARTITION BY PARQUET_RAW:id
    ORDER BY
        COALESCE(TO_TIMESTAMP(PARQUET_RAW:modified_on::NUMBER,3),
        TO_TIMESTAMP(PARQUET_RAW:created_on::NUMBER,3)) DESC,
        INTEGRATION_RECORD_CREATED_DT DESC) RANK,
        INTEGRATION_RECORD_CREATED_DT
    FROM
        STG_PEOPLE
    WHERE
        INTEGRATION_RECORD_CREATED_DT >
        {INSERTED TIMESTAMP}
    ORDER BY
        PARQUET_RAW:id,
        COALESCE(TO_TIMESTAMP(PARQUET_RAW:modified_on::NUMBER,3),
        TO_TIMESTAMP(PARQUET_RAW:created_on::NUMBER,3)) DESC,
        INTEGRATION_RECORD_CREATED_DT DESC
) AS SOURCE_TABLE
ON
    SOURCE_TABLE.ID = TARGET.ID
    -- DEACTIVATE OLD RECORD
WHEN MATCHED AND TARGET.RECORD_ACTIVE_FLAG = 'Y'
THEN UPDATE SET
    TARGET.RECORD_ACTIVE_TO = $curr_time,
    TARGET.RECORD_ACTIVE_FLAG = 'N',
    TARGET.RECORD_MODIFIED_DT = $curr_time
    --INSERT ANY NEW RECORD FOR AN UPDATE
--insert newest version
WHEN MATCHED AND SOURCE_TABLE.RANK = 1
THEN
INSERT (ID,FIRST_NAME,LAST_NAME,CREATED_BY,CREATED_ON,MODIFIED_BY,MODIFIED_ON,RECORD_CREATED_DT,RECORD_MODIFIED_DT,RECORD_ACTIVE_FROM,RECORD_ACTIVE_TO,RECORD_ACTIVE_FLAG,RECORD_INTEGRATION_TIMESTAMP)
VALUES(
ID,
FIRST_NAME,
LAST_NAME,
CREATED_BY,
CREATED_ON,
MODIFIED_BY,
MODIFIED_ON,
$curr_time,
$curr_time,
$curr_time,
TO_TIMESTAMP('2999-01-01'),
'Y',
RECORD_INTEGRATION_TIMESTAMP
)
--insert older versions
--WONT WORK BECAUSE THIS IS NOT PREDICATED ON MATCHED/NOT MATCHED
WHEN SOURCE_TABLE.RANK != 1
THEN
INSERT (ID,FIRST_NAME,LAST_NAME,CREATED_BY,CREATED_ON,MODIFIED_BY,MODIFIED_ON,RECORD_CREATED_DT,RECORD_MODIFIED_DT,RECORD_ACTIVE_FROM,RECORD_ACTIVE_TO,RECORD_ACTIVE_FLAG,RECORD_INTEGRATION_TIMESTAMP)
VALUES(
SOURCE_TABLE.ID,
SOURCE_TABLE.FIRST_NAME,
SOURCE_TABLE.LAST_NAME,
SOURCE_TABLE.CREATED_BY,
SOURCE_TABLE.CREATED_ON,
SOURCE_TABLE.MODIFIED_BY,
SOURCE_TABLE.MODIFIED_ON,
$curr_time,
$curr_time,
$curr_time,
$curr_time,
'N',
SOURCE_TABLE.RECORD_INTEGRATION_TIMESTAMP
);

</code>```

But this does not work as the case to append new records for duplicates which are lower rank does not actually meet the 'MATCHED' or 'NOT MATCHED' criteria.

Body:
I'm playing around with some snowflake ingestion from S3 using snowpipe and I've hit a slight snag with handling the edge case of multiple updates to a given dimension arriving at the same time.

The Background:

i have a source dumping heaps of parquet files in an S3 Bucket. Ideally we want to process these files and load them into snowflake, using snowpipe. For simplicty sake lets say the data has the below shape:

ID
FIRST_NAME
LAST_NAME
MODIFIED_ON
IS_DELETED

1
John
doe
2022-11-01
False

2
jane
doe
2022-11-01
False

I'm currently reading these files and their data raw into snowflake using snowpipe and COPY INTO from the S3 bucket. Storing them as a raw Variant with an INGEST_TIMESTAMP column in a table called RAW_PEOPLE.

PARQUET_RAW
INGEST_TIMESTAMP

{data:stuff}
2022-11-01 22:50:00

I have a steam configured off this table, which is driving a snowflake Task every few minutes to flatten out the Variant Data into a table called STG_PEOPLE. So now i have a table with:

ID
FIRST_NAME
LAST_NAME
MODIFIED_ON
IS_DELETED
INGEST_TIMESTAMP

1
John
doe
2022-11-01
False
2022-11-01 22:50:00

2
jane
doe
2022-11-01
False
2022-11-01 22:50:00

I have also configured a stream of this table to track CDC and would like to make a merge procedure to handle move this dataset into the final table outlined below:

Finally I have a target DIM_PEOPLE table which is a type 2 SCD table with the following columns:

ID, FIRST_NAME, LAST_NAME, MODIFIED_ON, IS_DELETED, RECORD_CREATED_TS,  RECORD_ACTIVE_FROM_TS, RECORD_ACTIVE_TO_TS

ID
FIRST_NAME
LAST_NAME
MODIFIED_ON
IS_DELETED
RECORD_ACTIVE_FROM_TS
RECORD_ACTIVE_TO_TS
RECORD_ACTIVE_FLAG

1
John
doe
2022-11-01
False
1900-01-01

Y

2
jane
doe
2022-11-01
False
1900-01-01

Y

I made up a very basic diagram to illustrate:

high level diagram

The Problem:

I cannot gurantee that the source wont drop multiple updates to the same ID in the same file, or that we might have multiple files build up that contain the updates to the same ID.

So in a given ingest run i could get the below data turn up in STG_PEOPLE that i want to merge into DIM_PEOPLE:

ID
FIRST_NAME
LAST_NAME
MODIFIED_ON
IS_DELETED
INGEST_TIMESTAMP

1
John-joe
doe
2022-11-02
False
2022-11-02 23:00

2
jane
doe
2022-11-01
False
2022-11-02 23:00

1
john-bill-joe
doe
2022-11-03
False
2022-12-03 23:00

I dont want to discard historical changes either. But I'm struggling on how to gracefully merge this STG_PEOPLE set into the DIM_PEOPLE set in a single merge statement?

As determining record active from periods for ID = 1, my plan is to set the latest ingest timestamp to active, and set the earlier duplicate record to have an active duration of 0, ie it has the same EFFECTIVE FROM and EFFECTIVE TO

My ideal dataset might be something like the below?

ID
FIRST_NAME
LAST_NAME
MODIFIED_ON
IS_DELETED
RECORD_ACTIVE_FROM_TS
RECORD_ACTIVE_TO_TS
RECORD_ACTIVE_FLAG

1
john-bill-joe
doe
2022-11-03
False
2022-11-02 23:00

Y

1
John-joe
doe
2022-11-02
False
2022-11-02 23:00
2022-11-02 23:00
N

1
John
doe
2022-11-01
False
1900-01-01
2022-11-02 23:00
N

2
jane
doe
2022-11-01
False
1900-01-01

Y

So my question is, within snowflake how would you execute a merge gracefully from a CDC stream if you capture multiple updates to the same record in the stream? Potentially i could union select both the target and source together and do some ranking in the merge, but it seems a bit heavyweight?

Thanks for taking the time to read my stream of consciousness, any help would be appreciated.

I have tried to merge this data using a ranking merge outlined below:

SET curr_time = CURRENT_TIMESTAMP()

MERGE INTO DIM_PEOPLE TARGET
        USING (
    SELECT
        PARQUET_RAW:id ID,
        PARQUET_RAW:first_name::STRING FIRST_NAME,
        PARQUET_RAW:last_name::STRING LAST_NAME,
        PARQUET_RAW:created_by::STRING CREATED_BY,
        TO_TIMESTAMP(PARQUET_RAW:created_on::NUMBER,3) CREATED_ON,
        TO_TIMESTAMP(PARQUET_RAW:modified_on::NUMBER,3) MODIFIED_ON,
        PARQUET_RAW:modified_by::STRING MODIFIED_BY,
        RANK() OVER (PARTITION BY PARQUET_RAW:id
    ORDER BY
        COALESCE(TO_TIMESTAMP(PARQUET_RAW:modified_on::NUMBER,3),
        TO_TIMESTAMP(PARQUET_RAW:created_on::NUMBER,3)) DESC,
        INTEGRATION_RECORD_CREATED_DT DESC) RANK,
        INTEGRATION_RECORD_CREATED_DT
    FROM
        STG_PEOPLE
    WHERE
        INTEGRATION_RECORD_CREATED_DT >
        {INSERTED TIMESTAMP}
    ORDER BY
        PARQUET_RAW:id,
        COALESCE(TO_TIMESTAMP(PARQUET_RAW:modified_on::NUMBER,3),
        TO_TIMESTAMP(PARQUET_RAW:created_on::NUMBER,3)) DESC,
        INTEGRATION_RECORD_CREATED_DT DESC
) AS SOURCE_TABLE
ON
    SOURCE_TABLE.ID = TARGET.ID
    -- DEACTIVATE OLD RECORD
WHEN MATCHED AND TARGET.RECORD_ACTIVE_FLAG = 'Y'
THEN UPDATE SET
    TARGET.RECORD_ACTIVE_TO = $curr_time,
    TARGET.RECORD_ACTIVE_FLAG = 'N',
    TARGET.RECORD_MODIFIED_DT = $curr_time
    --INSERT ANY NEW RECORD FOR AN UPDATE
--insert newest version
WHEN MATCHED AND SOURCE_TABLE.RANK = 1
THEN
INSERT (ID,FIRST_NAME,LAST_NAME,CREATED_BY,CREATED_ON,MODIFIED_BY,MODIFIED_ON,RECORD_CREATED_DT,RECORD_MODIFIED_DT,RECORD_ACTIVE_FROM,RECORD_ACTIVE_TO,RECORD_ACTIVE_FLAG,RECORD_INTEGRATION_TIMESTAMP)
VALUES(
ID,
FIRST_NAME,
LAST_NAME,
CREATED_BY,
CREATED_ON,
MODIFIED_BY,
MODIFIED_ON,
$curr_time,
$curr_time,
$curr_time,
TO_TIMESTAMP('2999-01-01'),
'Y',
RECORD_INTEGRATION_TIMESTAMP
)
--insert older versions
--WONT WORK BECAUSE THIS IS NOT PREDICATED ON MATCHED/NOT MATCHED
WHEN SOURCE_TABLE.RANK != 1
THEN
INSERT (ID,FIRST_NAME,LAST_NAME,CREATED_BY,CREATED_ON,MODIFIED_BY,MODIFIED_ON,RECORD_CREATED_DT,RECORD_MODIFIED_DT,RECORD_ACTIVE_FROM,RECORD_ACTIVE_TO,RECORD_ACTIVE_FLAG,RECORD_INTEGRATION_TIMESTAMP)
VALUES(
SOURCE_TABLE.ID,
SOURCE_TABLE.FIRST_NAME,
SOURCE_TABLE.LAST_NAME,
SOURCE_TABLE.CREATED_BY,
SOURCE_TABLE.CREATED_ON,
SOURCE_TABLE.MODIFIED_BY,
SOURCE_TABLE.MODIFIED_ON,
$curr_time,
$curr_time,
$curr_time,
$curr_time,
'N',
SOURCE_TABLE.RECORD_INTEGRATION_TIMESTAMP
);

But this does not work as the case to append new records for duplicates which are lower rank does not actually meet the 'MATCHED' or 'NOT MATCHED' criteria.


问:
CS50 Tideman - lock_pairs skips final pair if it creates cycle
I have no prior coding experience and i've been on this pset ofr like 3+ days now...very challenging and rewarding, but this last check is driving me crazy.

This is the lock_pairs function i wrote

```<code>void lock_pairs(void)
{

    for (int i = 0 ; i < pair_count ; i++)
    {
        int og_win = pairs[i].winner;
        int temp = pairs[i].loser;

       if (i < 1)
        {
            locked[pairs[i].winner][pairs[i].loser] = true;
        }
        else if(creates_cycle(i, og_win, temp) != true)
        {
            locked[pairs[i].winner][pairs[i].loser] = true;
        }
    }
    return;

}
</code>```

And this is the function i wrote to check if locking this pair would create a cycle

```<code>bool creates_cycle(int n, int original_winner, int temp_win_los)
{
    for (int j = 0 ; j < n ; j++)
    {
        if (locked[pairs[j].winner][pairs[j].loser] == true)
        {
            if ( pairs[j].winner == temp_win_los )
            {
                if ( pairs[j].loser == original_winner )
                {
                    return true;
                }
                else
                {
                    temp_win_los = pairs[j].loser;
                    creates_cycle(n, original_winner, temp_win_los);
                }
            }
        }
    }
    return false;
}
</code>```

I am pretty satisfied of being able to reach this point in the pset, but i really don't understand why and where my code is faulty.

Any help is appreciated.
Thanks!

Body:
I have no prior coding experience and i've been on this pset ofr like 3+ days now...very challenging and rewarding, but this last check is driving me crazy.

This is the lock_pairs function i wrote

void lock_pairs(void)
{

    for (int i = 0 ; i < pair_count ; i++)
    {
        int og_win = pairs[i].winner;
        int temp = pairs[i].loser;

       if (i < 1)
        {
            locked[pairs[i].winner][pairs[i].loser] = true;
        }
        else if(creates_cycle(i, og_win, temp) != true)
        {
            locked[pairs[i].winner][pairs[i].loser] = true;
        }
    }
    return;

}

And this is the function i wrote to check if locking this pair would create a cycle

bool creates_cycle(int n, int original_winner, int temp_win_los)
{
    for (int j = 0 ; j < n ; j++)
    {
        if (locked[pairs[j].winner][pairs[j].loser] == true)
        {
            if ( pairs[j].winner == temp_win_los )
            {
                if ( pairs[j].loser == original_winner )
                {
                    return true;
                }
                else
                {
                    temp_win_los = pairs[j].loser;
                    creates_cycle(n, original_winner, temp_win_los);
                }
            }
        }
    }
    return false;
}

I am pretty satisfied of being able to reach this point in the pset, but i really don't understand why and where my code is faulty.

Any help is appreciated.
Thanks!


问:
How do I create a playfab leaderboard and send player stats to it using to their playfab ID?
I am not sure how to create a Playfab leaderboard and add scores to a user, based on their Playfab ID retrieved from the details they've entered in my 2 player login system. Both players enter their details (email, password) separately.

My 2 player login system for the game is fully functional and I have worked out how to retrieve their unique Playfab IDs. I have stored both playfab IDs as strings I don't know how to use them to update a specific player's stats.


问:
Retrieve CPU utilization for each Google Cloud App Engine instance
I've deployed an app on Google Cloud App Engine instances.
I've enabled an autoscaling group that should increase the number of instances in case the CPU utilization of the instances goes beyond the 60% usage (as Google suggests).

Now from GCP dashboard I see these screen:

As you can see there are 3 instances (I've set the minimum number of instances to 3).

Hovering the blue line of the graph I see that CPU percentage changes over time, but I can't understand if this percentage is the total percentage for the 3 instances of what else.

In the image above 5.38% is the CPU percentage of a specific instance or is the sum of the percentage of the 3 instances?

I wonder to know how to retrieve CPU utilization for each of the 3 instances.


问:
How to select multiple images and print the paths of the images after a button is pressed in swiftui
Good day,

I am trying to make an image picker that you can choose multiple images and then print out the paths of the images once a button has been pressed on the screen.

But I could only manage to get it to pick on image at a time and it prints out the path when the image it picked.

Here is my code for the image picker

```<code>import SwiftUI

struct ImagePicker: UIViewControllerRepresentable {
    class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
        let parent: ImagePicker

        init(_ parent: ImagePicker) {
            self.parent = parent
        }

        func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
            var selectedImages = [UIImage]()
            for item in info {
                if let image = item.value as? UIImage, let imageURL = info[.imageURL] as? URL {
                    selectedImages.append(image)
                    print("Image URL: ", imageURL)
                }
            }

            self.parent.images.append(contentsOf: selectedImages)
            parent.showImagePicker = false
        }
    }

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    @Binding var showImagePicker: Bool
    @Binding var images: [UIImage]

    func makeUIViewController(context: UIViewControllerRepresentableContext<ImagePicker>) -> UIImagePickerController {
        let picker = UIImagePickerController()
        picker.delegate = context.coordinator
        picker.sourceType = .photoLibrary
        picker.allowsEditing = false
        picker.modalPresentationStyle = .fullScreen
        picker.mediaTypes = ["public.image"]
        picker.videoQuality = .typeHigh
        picker.videoMaximumDuration = TimeInterval(30)
        picker.modalPresentationStyle = .popover
        return picker
    }

    func updateUIViewController(_ uiViewController: UIImagePickerController, context: UIViewControllerRepresentableContext<ImagePicker>) {
        uiViewController.popoverPresentationController?.sourceRect = CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: 0, height: 0))
    }
}

struct ImagePickerView: View {
    @State private var showImagePicker = false
    @State private var images = [UIImage]()

    var body: some View {
        VStack{
            Button("Select Images") {
                self.showImagePicker = true
            }
            .sheet(isPresented: $showImagePicker) {
                ImagePicker(showImagePicker: $showImagePicker, images: $images)
            }

        }
    }

    struct ImagePickerViewPreviews: PreviewProvider {
        static var previews: some View {
            ImagePickerView()
        }
    }
}
</code>```

Body:
Good day,

I am trying to make an image picker that you can choose multiple images and then print out the paths of the images once a button has been pressed on the screen.

But I could only manage to get it to pick on image at a time and it prints out the path when the image it picked.

Here is my code for the image picker

import SwiftUI

struct ImagePicker: UIViewControllerRepresentable {
    class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
        let parent: ImagePicker

        init(_ parent: ImagePicker) {
            self.parent = parent
        }

        func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
            var selectedImages = [UIImage]()
            for item in info {
                if let image = item.value as? UIImage, let imageURL = info[.imageURL] as? URL {
                    selectedImages.append(image)
                    print("Image URL: ", imageURL)
                }
            }

            self.parent.images.append(contentsOf: selectedImages)
            parent.showImagePicker = false
        }
    }

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    @Binding var showImagePicker: Bool
    @Binding var images: [UIImage]

    func makeUIViewController(context: UIViewControllerRepresentableContext<ImagePicker>) -> UIImagePickerController {
        let picker = UIImagePickerController()
        picker.delegate = context.coordinator
        picker.sourceType = .photoLibrary
        picker.allowsEditing = false
        picker.modalPresentationStyle = .fullScreen
        picker.mediaTypes = ["public.image"]
        picker.videoQuality = .typeHigh
        picker.videoMaximumDuration = TimeInterval(30)
        picker.modalPresentationStyle = .popover
        return picker
    }

    func updateUIViewController(_ uiViewController: UIImagePickerController, context: UIViewControllerRepresentableContext<ImagePicker>) {
        uiViewController.popoverPresentationController?.sourceRect = CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: 0, height: 0))
    }
}

struct ImagePickerView: View {
    @State private var showImagePicker = false
    @State private var images = [UIImage]()

    var body: some View {
        VStack{
            Button("Select Images") {
                self.showImagePicker = true
            }
            .sheet(isPresented: $showImagePicker) {
                ImagePicker(showImagePicker: $showImagePicker, images: $images)
            }

        }
    }

    struct ImagePickerViewPreviews: PreviewProvider {
        static var previews: some View {
            ImagePickerView()
        }
    }
}


问:
Unable to bypass spring security filter chain for specific endpoints with the permitAll() and web.ignoring() methods
I'm using Spring Security for Single Sign On implementation. I've added the Spring Security filter chain in my application with annotations, and not in the web.xml.

I want the Spring Security filter chain to only apply to the /saml URLs, and I don't want the /myapi requests to go through Spring Security. But my /myapi requests are still going through the Spring Security filter chain, and Spring's filters.

Here's my code for Spring Security filter registration:

@Configuration
@EnableWebSecurity
public class SecurityConfiguration {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .addFilterBefore(new SamlExtensionUrlForwardingFilter(), DisableEncodeUrlFilter.class)
            .authorizeHttpRequests((authorize) -> authorize
                        .antMatchers("/saml/*").authenticated()
                        .antMatchers("/myapi/*").permitAll()
                )
            .saml2Login()
                    .successHandler(new MyAuthenticationSuccessHandler());
        return http.build();
    }

    @Bean
    public WebSecurityCustomizer webSecurityCustomizer() {
        return (web) -> web.ignoring().antMatchers("/myapi/*");
    }

```
<p>With the <code>webSecurityCustomizer()</code>, I tried to exclude the <code>/myapi/</code> endpoints from the Spring Security workflow, and bypass the Spring Security filter chain and other Spring Security filters for the endpoint.</p>
<p>Additionally, I tried to get the same results with the following as well, assuming that <code>permitAll()</code> would mean Spring Security authorization is not required for the <code>/myapi</code> requests:</p>
<pre class="lang-java prettyprint-override"><code>.antMatchers("/myapi/*").permitAll()
</code>```

Neither of the above two worked, and the /myapi requests still go through Spring'a filters like DisableEncodeUrlFilter, CsrfFilter etc. Ideally, I want only /saml/* requests to go through the Spring Security filter chain and Spring related filters.

Body:
I'm using Spring Security for Single Sign On implementation. I've added the Spring Security filter chain in my application with annotations, and not in the web.xml.

I want the Spring Security filter chain to only apply to the /saml URLs, and I don't want the /myapi requests to go through Spring Security. But my /myapi requests are still going through the Spring Security filter chain, and Spring's filters.

Here's my code for Spring Security filter registration:

@Configuration
@EnableWebSecurity
public class SecurityConfiguration {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .addFilterBefore(new SamlExtensionUrlForwardingFilter(), DisableEncodeUrlFilter.class)
            .authorizeHttpRequests((authorize) -> authorize
                        .antMatchers("/saml/*").authenticated()
                        .antMatchers("/myapi/*").permitAll()
                )
            .saml2Login()
                    .successHandler(new MyAuthenticationSuccessHandler());
        return http.build();
    }

    @Bean
    public WebSecurityCustomizer webSecurityCustomizer() {
        return (web) -> web.ignoring().antMatchers("/myapi/*");
    }

With the webSecurityCustomizer(), I tried to exclude the /myapi/ endpoints from the Spring Security workflow, and bypass the Spring Security filter chain and other Spring Security filters for the endpoint.

Additionally, I tried to get the same results with the following as well, assuming that permitAll() would mean Spring Security authorization is not required for the /myapi requests:

.antMatchers("/myapi/*").permitAll()

Neither of the above two worked, and the /myapi requests still go through Spring'a filters like DisableEncodeUrlFilter, CsrfFilter etc. Ideally, I want only /saml/* requests to go through the Spring Security filter chain and Spring related filters.


问:
What is the same of Spring 3.0's <mvc:annotation-driven> in Spring 2.5?
I study for maintain an old web-app (Spring 2.5, Java/JDK 1.6, Eclipse IDE 2022-06, Windows 10 x64).

Learned from tutorial https://mkyong.com/spring-mvc/spring-mvc-jquery-autocomplete-example/

File mvc-dispatcher-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:component-scan base-package="com.mkyong" />
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/pages/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>

    <mvc:resources mapping="/resources/**" location="/resources/" />

    <mvc:annotation-driven />

</beans>
```

I need convert this web-app (Spring 3.0) to Spring 2.5, how to revise? What is the same of Spring 3.0's mvc:annotation-driven in Spring 2.5?

Body:
I study for maintain an old web-app (Spring 2.5, Java/JDK 1.6, Eclipse IDE 2022-06, Windows 10 x64).

Learned from tutorial https://mkyong.com/spring-mvc/spring-mvc-jquery-autocomplete-example/

File mvc-dispatcher-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:component-scan base-package="com.mkyong" />
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/pages/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>

    <mvc:resources mapping="/resources/**" location="/resources/" />

    <mvc:annotation-driven />

</beans>

I need convert this web-app (Spring 3.0) to Spring 2.5, how to revise? What is the same of Spring 3.0's mvc:annotation-driven in Spring 2.5?


问:
Admin page Product gallery livewire full page multi image upload
I'm trying to make a product gallery for the e-commerce page on the admin side, while uploading bulk products, the row in the table provides two times again.

```<code> $this->validate([
'title' => 'required',
'NewsImage.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'product_id' => 'required',
]);

 if(!empty($this->NewsImage)) {
        foreach ($this->NewsImage as $image) {
            $imageName = $image->hashName();
            $image->store('public/products');
            Image::create([
                'title' => $this->title,
                'image' => $imageName,
                'product_id' => $this->product_id,
            ]);
        }
    }
    $this->modalFormVisible = false;
    $this->reset();
    $this->resetFields();

</code>```
```<code> @if(count($NewsImage))
   @foreach($NewsImage as $image)
     <td class="px-6 py-4 text-sm whitespace-no-wrap">
<img class="w-8 h-8 rounded-full" src="{{ \Illuminate\Support\Facades\Storage::url($Image->image) }}" />
 </td>
   @endforeach

  @endif

</code>```

I want to list it side by side but I couldn't do it can you help me thank you very much in advance

I shared a related photo, I'm trying to sort the image side by side, but when I add it, it adds an extra row.

Body:
I'm trying to make a product gallery for the e-commerce page on the admin side, while uploading bulk products, the row in the table provides two times again.

 $this->validate([
'title' => 'required',
'NewsImage.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'product_id' => 'required',
]);

 if(!empty($this->NewsImage)) {
        foreach ($this->NewsImage as $image) {
            $imageName = $image->hashName();
            $image->store('public/products');
            Image::create([
                'title' => $this->title,
                'image' => $imageName,
                'product_id' => $this->product_id,
            ]);
        }
    }
    $this->modalFormVisible = false;
    $this->reset();
    $this->resetFields();

 @if(count($NewsImage))
   @foreach($NewsImage as $image)

image) }}" />

   @endforeach

  @endif

I want to list it side by side but I couldn't do it can you help me thank you very much in advance

I shared a related photo, I'm trying to sort the image side by side, but when I add it, it adds an extra row.


问:
Save the user input parameters in perl config file from xaml file
I have a application which was developed using perl and its UI is designed by xaml and c# files in visual studio. So now I had created a confilg file in perl where the source code files uses this config file to read inputs from. For that I want to save the parameters into the perl config file that I had created already from user input xaml file and c# as binding for GUI. I want to know if there is a way to save the paramerts to perl file using xaml and c# file in visual studio.

Here is an example for xaml file and c# binding file from GUI of the tool.

xaml file:

```<code><TabItem Header="Properties" x:Name="tabItem1_Copy" Margin="-2,-2,-2,0">
    <Grid Margin="0,0,4.2,2">
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <TextBox Height="20" Margin="295,58,0,0" x:Name="tbShiftColumns" Width="40" />
        <TextBlock Height="20" x:Name="textBlock7" Text="Shift Columns" Width="75" />
    </Grid>
</TabItem>
</code>```

xaml.cs file:

```<code> private void bxxxxxx_Click(object sender, RoutedEventArgs e)
    {
        tFLog.Clear();

        Process prc = new Process();
        prc.StartInfo.FileName = "xxxxxxxxxxxxx.bat";
        prc.StartInfo.Arguments = "\"" + tbCustPar.Text + "\" \"" + tbShiftColumns.Text + "\"";
        prc.StartInfo.WindowStyle = ProcessWindowStyle.Normal;//.Hidden;
        prc.StartInfo.UseShellExecute = true;
        prc.StartInfo.WorkingDirectory = System.IO.Path.GetDirectoryName(System.Reflection);
        prc.Start();
        prc.WaitForExit();
        prc.Close();

        string logFileName = System.IO.Path.GetDirectoryName(System.Reflection) + "\\xxxx.log";
        StreamReader sr = new StreamReader(logFileName, System.Text.Encoding.Default, true);
        tFLog.Text = sr.ReadToEnd();
    }
</code>```

and in the above 2 example codes once can observe tbshift columns is one of the input parameters in .xaml file and it is binded using c# .xaml.cs file. that is what i mean. Now I want to find a way to save the user input parameters directly into a perl config file. I already created one and will be displayed below for reference.

perl config file:

```<code>#variables to be parsed to xyz.pl file

maxDepth = tbNoLevels
shiftt = tbshiftColumns
</code>```

I hope I had explained my problem as clear as possible. Any suggestion or answers are highly appriciated.

Thank you

I tried to create a app.config file in visual studio and it looked like this :

```<code><?xml version="1.0"?>
<configuration>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>
</code>```

I think here we can add dictionaries like key and value pairs : <add key="Key0" value="0" />

but I want to save the input parameters directly into a perl config file.

And I also tried to create a App.xaml file this has:

```<code><Application x:Class="xxxxxxxxxxxxxx"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="xxxxxxxx.xaml"\>
    <Application.Resources\>

    </Application.Resources>
</Application>
</code>```

I have no idea what can be done. Any proper direction of action to solve is issue is highly expected. Or suggest any other alternatives to achieve this. I am beginner I would expect a detailed answer please.

Body:
I have a application which was developed using perl and its UI is designed by xaml and c# files in visual studio. So now I had created a confilg file in perl where the source code files uses this config file to read inputs from. For that I want to save the parameters into the perl config file that I had created already from user input xaml file and c# as binding for GUI. I want to know if there is a way to save the paramerts to perl file using xaml and c# file in visual studio.

Here is an example for xaml file and c# binding file from GUI of the tool.

xaml file:

<TabItem Header="Properties" x:Name="tabItem1_Copy" Margin="-2,-2,-2,0">
    <Grid Margin="0,0,4.2,2">
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <TextBox Height="20" Margin="295,58,0,0" x:Name="tbShiftColumns" Width="40" />
        <TextBlock Height="20" x:Name="textBlock7" Text="Shift Columns" Width="75" />
    </Grid>
</TabItem>

xaml.cs file:

 private void bxxxxxx_Click(object sender, RoutedEventArgs e)
    {
        tFLog.Clear();

        Process prc = new Process();
        prc.StartInfo.FileName = "xxxxxxxxxxxxx.bat";
        prc.StartInfo.Arguments = "\"" + tbCustPar.Text + "\" \"" + tbShiftColumns.Text + "\"";
        prc.StartInfo.WindowStyle = ProcessWindowStyle.Normal;//.Hidden;
        prc.StartInfo.UseShellExecute = true;
        prc.StartInfo.WorkingDirectory = System.IO.Path.GetDirectoryName(System.Reflection);
        prc.Start();
        prc.WaitForExit();
        prc.Close();

        string logFileName = System.IO.Path.GetDirectoryName(System.Reflection) + "\\xxxx.log";
        StreamReader sr = new StreamReader(logFileName, System.Text.Encoding.Default, true);
        tFLog.Text = sr.ReadToEnd();
    }

and in the above 2 example codes once can observe tbshift columns is one of the input parameters in .xaml file and it is binded using c# .xaml.cs file. that is what i mean. Now I want to find a way to save the user input parameters directly into a perl config file. I already created one and will be displayed below for reference.

perl config file:

#variables to be parsed to xyz.pl file

maxDepth = tbNoLevels
shiftt = tbshiftColumns

I hope I had explained my problem as clear as possible. Any suggestion or answers are highly appriciated.

Thank you

I tried to create a app.config file in visual studio and it looked like this :

<?xml version="1.0"?>
<configuration>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>

I think here we can add dictionaries like key and value pairs : <add key="Key0" value="0" />

but I want to save the input parameters directly into a perl config file.

And I also tried to create a App.xaml file this has:

<Application x:Class="xxxxxxxxxxxxxx"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="xxxxxxxx.xaml"\>
    <Application.Resources\>

    </Application.Resources>
</Application>

I have no idea what can be done. Any proper direction of action to solve is issue is highly expected. Or suggest any other alternatives to achieve this. I am beginner I would expect a detailed answer please.


问:
Animating a real time breathing curve in python
I want to create an animation that people can use to align their breathing with. I have made a class with PyQt5 that does exactly this, and has the breathing period as parameter. (See code below).

It works well, apart from the timing. When setting a specific delta_t and window size during the FuncAnimation I can get accurate timings. But when I change the window size, it either speeds up or slows down...

Im probably going to model this in another language, but I am still curious if I can get this right in Python. Can anyone here point me in the right direction?

```<code>import os
import time
import sys
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure

import PyQt5.QtGui
import PyQt5.QtCore
import PyQt5.QtWidgets

class BreathingAnimation(PyQt5.QtWidgets.QMainWindow):
    # Could inherit from GenericInterface
    # Animate three ways:
    # o Fixed sinusoid -> moving ball
    # o Fixed ball (up/down) -> moving wave
    # o Expanding ball

    def __init__(self, period=1, delta_t=0.01, animation_type='ball'):
        super().__init__()
        self._main = PyQt5.QtWidgets.QWidget()
        self.setCentralWidget(self._main)
        """
        Plot variables

        sin(omega * x)

        period = 2 * np.pi * omega
        omega = period / (2 * np.pi)
        """
        self.delta_t = delta_t
        self.frequentie = 1/period
        self.max_plot_time = 5
        self.max_periods = 20
        self.t_range = np.arange(0, self.max_periods * period, delta_t)
        self.animation_type = animation_type
        self.cool_down = 10
        self.prev_time = time.time()
        self.prev_time_cor_time = time.time()
        """
        Graphical definitions
        """
        self.canvas, self.fig, self.axes = self.get_figure(self.max_plot_time)
        self.axes.set_axis_off()
        self.line_obj, self.scatter_obj = self.get_plot_objects(self.axes)

        # Get the animation object
        self.anim_obj = self.get_animation()

        h_layout = PyQt5.QtWidgets.QHBoxLayout(self._main)
        # Create buttons
        # self.button_box_layout = self.get_button_box_layout()
        # write_button = self.get_push_button(name='Write', shortcut='W', connect=self.write_animation)
        # self.edit_button = self.get_line_edit(name=f'{period}', connect=self.update_period, max_length=4)
        # self.button_box_layout.addWidget(self.edit_button)
        # self.button_box_layout.addWidget(write_button)

        # Add canvas to the figure
        temp_canvas_layout = PyQt5.QtWidgets.QVBoxLayout()
        temp_canvas_layout.addWidget(self.canvas)

        h_layout.addLayout(temp_canvas_layout, stretch=1)
        # h_layout.addLayout(self.button_box_layout, stretch=0.01)

    @staticmethod
    def get_figure(max_plot_time, debug=False):
        if debug:
            fig = plt.figure()
        else:
            fig = Figure(figsize=(5, 5), dpi=100)
        canvas = FigureCanvas(fig)
        axes = canvas.figure.subplots()
        # self.axes.set_axis_off()
        axes.set_ylim(-2, 2)
        axes.set_xlim(0, max_plot_time)
        return canvas, fig, axes

    @staticmethod
    def get_plot_objects(axes):
        # Create a line object
        line_obj = axes.plot([], [], zorder=1)[0]
        # Create a scatter object
        scatter_obj = axes.scatter([], [], s=40, marker='o', c='r')
        return line_obj, scatter_obj

    def get_y_value(self, i_t):
        omega = 2 * np.pi * self.frequentie
        y_value = np.sin(omega * i_t)
        return y_value

    def animate_moving_ball(self, i, line_obj=None, scatter_obj=None):
        i = i % len(self.t_range)
        if line_obj is None:
            line_obj = self.line_obj
        if scatter_obj is None:
            scatter_obj = self.scatter_obj
        line_obj.set_data(self.t_range, self.get_y_value(self.t_range))
        sel_time = self.t_range[i]
        scatter_obj.set_offsets(np.c_[sel_time, self.get_y_value(sel_time)])
        return scatter_obj

    def animate_moving_wave(self, i, line_obj=None, scatter_obj=None):
        i = i % len(self.t_range)
        if line_obj is None:
            line_obj = self.line_obj
        if scatter_obj is None:
            scatter_obj = self.scatter_obj
        line_obj.set_data(self.t_range, np.roll(self.get_y_value(self.t_range), -i))
        sel_time = self.t_range[i] + self.max_plot_time/2.
        # print(f'max plot time {i}', self.max_plot_time/2, self.get_y_value(sel_time))
        scatter_obj.set_offsets(np.c_[self.max_plot_time/2., self.get_y_value(sel_time)])
        # self.cool_down -= 1
        # # print(self.cool_down)
        if ((1 - self.get_y_value(sel_time)) < 0.0001):
            time_difference = time.time() - self.prev_time
            self.prev_time = time.time()
            print('Time interval in seconds ', time_difference)

        return scatter_obj

    def update_period(self):
        new_periode = float(self.edit_button.text())
        self.frequentie = 1./new_periode
        self.t_range = np.arange(0, self.max_periods * new_periode, self.delta_t)

    def get_animation(self):
        if self.animation_type == 'ball':
            # Return a moving ball..
            animation_fun = self.animate_moving_ball
        elif self.animation_type == 'wave':
            # Return a wave..
            animation_fun = self.animate_moving_wave
        else:
            animation_fun = None

        self.animation_obj = animation.FuncAnimation(self.canvas.figure, animation_fun,
                                                     blit=False, repeat=True,
                                                     interval=self.delta_t,  # Delay in ms
                                                     frames=len(self.t_range))
        self.animation_obj.new_frame_seq()
        return self.animation_obj

    def write_animation(self):
        num_frames = len(self.t_range)
        max_time = np.max(self.t_range) # in seconds?
        print('frames ', num_frames / max_time)
        ffmpeg_writer = animation.FFMpegWriter(fps=num_frames / max_time)
        self.animation_obj.save(os.path.expanduser('~/breathing_animation.mp4'), writer=ffmpeg_writer)
        print('Written')

if __name__ == "__main__":
    qapp = PyQt5.QtWidgets.QApplication(sys.argv)
    app = BreathingAnimation(period=3, animation_type='wave', delta_t=0.009)
    app.show()
    qapp.exec_()
</code>```

Body:
I want to create an animation that people can use to align their breathing with. I have made a class with PyQt5 that does exactly this, and has the breathing period as parameter. (See code below).

It works well, apart from the timing. When setting a specific delta_t and window size during the FuncAnimation I can get accurate timings. But when I change the window size, it either speeds up or slows down...

Im probably going to model this in another language, but I am still curious if I can get this right in Python. Can anyone here point me in the right direction?

import os
import time
import sys
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure

import PyQt5.QtGui
import PyQt5.QtCore
import PyQt5.QtWidgets

class BreathingAnimation(PyQt5.QtWidgets.QMainWindow):
    # Could inherit from GenericInterface
    # Animate three ways:
    # o Fixed sinusoid -> moving ball
    # o Fixed ball (up/down) -> moving wave
    # o Expanding ball

    def __init__(self, period=1, delta_t=0.01, animation_type='ball'):
        super().__init__()
        self._main = PyQt5.QtWidgets.QWidget()
        self.setCentralWidget(self._main)
        """
        Plot variables

        sin(omega * x)

        period = 2 * np.pi * omega
        omega = period / (2 * np.pi)
        """
        self.delta_t = delta_t
        self.frequentie = 1/period
        self.max_plot_time = 5
        self.max_periods = 20
        self.t_range = np.arange(0, self.max_periods * period, delta_t)
        self.animation_type = animation_type
        self.cool_down = 10
        self.prev_time = time.time()
        self.prev_time_cor_time = time.time()
        """
        Graphical definitions
        """
        self.canvas, self.fig, self.axes = self.get_figure(self.max_plot_time)
        self.axes.set_axis_off()
        self.line_obj, self.scatter_obj = self.get_plot_objects(self.axes)

        # Get the animation object
        self.anim_obj = self.get_animation()

        h_layout = PyQt5.QtWidgets.QHBoxLayout(self._main)
        # Create buttons
        # self.button_box_layout = self.get_button_box_layout()
        # write_button = self.get_push_button(name='Write', shortcut='W', connect=self.write_animation)
        # self.edit_button = self.get_line_edit(name=f'{period}', connect=self.update_period, max_length=4)
        # self.button_box_layout.addWidget(self.edit_button)
        # self.button_box_layout.addWidget(write_button)

        # Add canvas to the figure
        temp_canvas_layout = PyQt5.QtWidgets.QVBoxLayout()
        temp_canvas_layout.addWidget(self.canvas)

        h_layout.addLayout(temp_canvas_layout, stretch=1)
        # h_layout.addLayout(self.button_box_layout, stretch=0.01)

    @staticmethod
    def get_figure(max_plot_time, debug=False):
        if debug:
            fig = plt.figure()
        else:
            fig = Figure(figsize=(5, 5), dpi=100)
        canvas = FigureCanvas(fig)
        axes = canvas.figure.subplots()
        # self.axes.set_axis_off()
        axes.set_ylim(-2, 2)
        axes.set_xlim(0, max_plot_time)
        return canvas, fig, axes

    @staticmethod
    def get_plot_objects(axes):
        # Create a line object
        line_obj = axes.plot([], [], zorder=1)[0]
        # Create a scatter object
        scatter_obj = axes.scatter([], [], s=40, marker='o', c='r')
        return line_obj, scatter_obj

    def get_y_value(self, i_t):
        omega = 2 * np.pi * self.frequentie
        y_value = np.sin(omega * i_t)
        return y_value

    def animate_moving_ball(self, i, line_obj=None, scatter_obj=None):
        i = i % len(self.t_range)
        if line_obj is None:
            line_obj = self.line_obj
        if scatter_obj is None:
            scatter_obj = self.scatter_obj
        line_obj.set_data(self.t_range, self.get_y_value(self.t_range))
        sel_time = self.t_range[i]
        scatter_obj.set_offsets(np.c_[sel_time, self.get_y_value(sel_time)])
        return scatter_obj

    def animate_moving_wave(self, i, line_obj=None, scatter_obj=None):
        i = i % len(self.t_range)
        if line_obj is None:
            line_obj = self.line_obj
        if scatter_obj is None:
            scatter_obj = self.scatter_obj
        line_obj.set_data(self.t_range, np.roll(self.get_y_value(self.t_range), -i))
        sel_time = self.t_range[i] + self.max_plot_time/2.
        # print(f'max plot time {i}', self.max_plot_time/2, self.get_y_value(sel_time))
        scatter_obj.set_offsets(np.c_[self.max_plot_time/2., self.get_y_value(sel_time)])
        # self.cool_down -= 1
        # # print(self.cool_down)
        if ((1 - self.get_y_value(sel_time)) < 0.0001):
            time_difference = time.time() - self.prev_time
            self.prev_time = time.time()
            print('Time interval in seconds ', time_difference)

        return scatter_obj

    def update_period(self):
        new_periode = float(self.edit_button.text())
        self.frequentie = 1./new_periode
        self.t_range = np.arange(0, self.max_periods * new_periode, self.delta_t)

    def get_animation(self):
        if self.animation_type == 'ball':
            # Return a moving ball..
            animation_fun = self.animate_moving_ball
        elif self.animation_type == 'wave':
            # Return a wave..
            animation_fun = self.animate_moving_wave
        else:
            animation_fun = None

        self.animation_obj = animation.FuncAnimation(self.canvas.figure, animation_fun,
                                                     blit=False, repeat=True,
                                                     interval=self.delta_t,  # Delay in ms
                                                     frames=len(self.t_range))
        self.animation_obj.new_frame_seq()
        return self.animation_obj

    def write_animation(self):
        num_frames = len(self.t_range)
        max_time = np.max(self.t_range) # in seconds?
        print('frames ', num_frames / max_time)
        ffmpeg_writer = animation.FFMpegWriter(fps=num_frames / max_time)
        self.animation_obj.save(os.path.expanduser('~/breathing_animation.mp4'), writer=ffmpeg_writer)
        print('Written')

if __name__ == "__main__":
    qapp = PyQt5.QtWidgets.QApplication(sys.argv)
    app = BreathingAnimation(period=3, animation_type='wave', delta_t=0.009)
    app.show()
    qapp.exec_()


问:
Pass a reference of a struct to an func not expecting a pointer
I was looking into grips with go and have a question regarding the helloworld grpc demo in go. Link to repo here

The server implementation calls one of the grpc autogenerated function to start the server and listen for incoming messages. However, the code passes a reference " &hwServer{}" of the struct to the function as below.

```<code>// Register Greeter on the server.
hwpb.RegisterGreeterServer(s, &hwServer{})
</code>```

Meanwhile the autogenerated Function has the following signature, which at that position expects an interface but not as a pointer:

```<code>func RegisterGreeterServer(s grpc.ServiceRegistrar, srv GreeterServer) {
s.RegisterService(&Greeter_ServiceDesc, srv)
</code>```

}

Therefore my question is, can I use both, a reference and pass by value as long as it satisfies the interface requirement? Otherwise I was used, that is the func arg expected a value, I cannot pass a pointer.

Body:
I was looking into grips with go and have a question regarding the helloworld grpc demo in go. Link to repo here

The server implementation calls one of the grpc autogenerated function to start the server and listen for incoming messages. However, the code passes a reference " &hwServer{}" of the struct to the function as below.

// Register Greeter on the server.
hwpb.RegisterGreeterServer(s, &hwServer{})

Meanwhile the autogenerated Function has the following signature, which at that position expects an interface but not as a pointer:

func RegisterGreeterServer(s grpc.ServiceRegistrar, srv GreeterServer) {
s.RegisterService(&Greeter_ServiceDesc, srv)

}

Therefore my question is, can I use both, a reference and pass by value as long as it satisfies the interface requirement? Otherwise I was used, that is the func arg expected a value, I cannot pass a pointer.


问:
OpenReadStream consumes too much memory and memory is not released afterwards
I am trying upload a file (300 MB) via client application (BLazor) to a remote server. Here is the code:

```<code>    private async Task<bool> UploadFile(IReadOnlyCollection<IBrowserFile> imgFiles) {
        filesComponent.clearDragClass();
        foreach(var imgFile in imgFiles) {
            byte[] content = new byte[imgFile.Size];
            string fileName = imgFile.Name;
            await imgFile.OpenReadStream(1000000000).ReadAsync(content); // limit is a little bit less than 1GB

            co.buffers.Add(content); // co object is a parameter that is used to communicate among components
            co.fileNames.Add(imgFile.Name);
        }
        // send file(s) to a server (MultipartFormDataContent)
        //return result
    }
</code>```

Problem

My application normally consumes around 120 MB and when uploading a file (300MB) I was expecting around 420MB. However my applications consumes 1.6 GB of memory. While  debugging I noticed that line

```<code>await imgFile.OpenReadStream(1000000000).ReadAsync(content);
</code>```

was responsible for consuming extra 1.2GB of memory.

Another problem is that extra memory that was consumed is not release even when uploading process is done.

Calling garbage collector did not help

```<code>System.GC.Collect();
</code>```

Dotnet version : 6.0.101

Body:
I am trying upload a file (300 MB) via client application (BLazor) to a remote server. Here is the code:

    private async Task<bool> UploadFile(IReadOnlyCollection<IBrowserFile> imgFiles) {
        filesComponent.clearDragClass();
        foreach(var imgFile in imgFiles) {
            byte[] content = new byte[imgFile.Size];
            string fileName = imgFile.Name;
            await imgFile.OpenReadStream(1000000000).ReadAsync(content); // limit is a little bit less than 1GB

            co.buffers.Add(content); // co object is a parameter that is used to communicate among components
            co.fileNames.Add(imgFile.Name);
        }
        // send file(s) to a server (MultipartFormDataContent)
        //return result
    }

Problem

My application normally consumes around 120 MB and when uploading a file (300MB) I was expecting around 420MB. However my applications consumes 1.6 GB of memory. While  debugging I noticed that line

await imgFile.OpenReadStream(1000000000).ReadAsync(content);

was responsible for consuming extra 1.2GB of memory.

Another problem is that extra memory that was consumed is not release even when uploading process is done.

Calling garbage collector did not help

System.GC.Collect();

Dotnet version : 6.0.101


问:
OpenLayers 6 "panning" map with Cypress
I'm trying to test the panning action in open layers but I can't get the map to move.
The versions I am using are these:

OpenLayers: 6.10.0

Cypress: 9.7.0

This is the code I have:

```<code>When('I pan the map to a different area', () => {
  cy.wait(3000)

  cy.get('.ol-layer canvas').trigger('pointerdown', {
    clientX: 900,
    clientY: 300,
    force: true,
    pointerId: 1,
  })
  cy.get('.ol-layer canvas').trigger('pointermove', {
    x: 600,
    y: 200,
    force: true,
    pointerId: 2,
  })
  cy.get('.ol-layer canvas').trigger('pointermove', {
    x: 300,
    y: 100,
    force: true,
    pointerId: 1,
  })
  cy.wait(2000)
  cy.get('.ol-layer canvas').trigger('pointerup', { force: true, pointerId: 1 })
})
</code>```

Title: OpenLayers 6 "panning" map with Cypress

Body:
I'm trying to test the panning action in open layers but I can't get the map to move.
The versions I am using are these:

OpenLayers: 6.10.0

Cypress: 9.7.0

This is the code I have:

When('I pan the map to a different area', () => {
  cy.wait(3000)

  cy.get('.ol-layer canvas').trigger('pointerdown', {
    clientX: 900,
    clientY: 300,
    force: true,
    pointerId: 1,
  })
  cy.get('.ol-layer canvas').trigger('pointermove', {
    x: 600,
    y: 200,
    force: true,
    pointerId: 2,
  })
  cy.get('.ol-layer canvas').trigger('pointermove', {
    x: 300,
    y: 100,
    force: true,
    pointerId: 1,
  })
  cy.wait(2000)
  cy.get('.ol-layer canvas').trigger('pointerup', { force: true, pointerId: 1 })
})


问:
MongoDB - How to replace specified field with $cond only when the condition is `True`?
here's my document:

```<code>{
    _id: 1,
    status: "estimate.sent",
    request_info: {request_id: 1, request_status: "done"},
    estimate_info: {
        estimate_id: 1
        estimate_status: "sent",
        expire_date: "2022-12-08T05:49:56.908149"
    }
}
</code>```

and what I'm trying to do is to change estimate_info.estimate_status's value to expired if expire_date is less than today's datetime.

so I'm currently running query following like this (I'm using pymongo FYI):

```<code>today = datetime.utcnow()
db.collection.aggregate(
    [
        {$match: {_id: 1}},
        {$addFields: {
            "estimate_info.estimate_status": {$cond: [
                {$and: [
                    {$eq: [$status, "estimate.sent"]},
                    {$lt: [$estimate_info.expire_date, today]}
                    ]
                }, "expired", "$estimate_info.estimate_status"]
            }}
        }
    ]
)
</code>```

it works fine, but what i expected is doing nothing if the $cond expression is false. because if status is not equal to estimate.sent, estimate_info must be null, not {}. My query returns {} when the expression is false. is there any fancy way to replace fields depending on condition as I expected?

Body:
here's my document:

{
    _id: 1,
    status: "estimate.sent",
    request_info: {request_id: 1, request_status: "done"},
    estimate_info: {
        estimate_id: 1
        estimate_status: "sent",
        expire_date: "2022-12-08T05:49:56.908149"
    }
}

and what I'm trying to do is to change estimate_info.estimate_status's value to expired if expire_date is less than today's datetime.

so I'm currently running query following like this (I'm using pymongo FYI):

today = datetime.utcnow()
db.collection.aggregate(
    [
        {$match: {_id: 1}},
        {$addFields: {
            "estimate_info.estimate_status": {$cond: [
                {$and: [
                    {$eq: [$status, "estimate.sent"]},
                    {$lt: [$estimate_info.expire_date, today]}
                    ]
                }, "expired", "$estimate_info.estimate_status"]
            }}
        }
    ]
)

it works fine, but what i expected is doing nothing if the $cond expression is false. because if status is not equal to estimate.sent, estimate_info must be null, not {}. My query returns {} when the expression is false. is there any fancy way to replace fields depending on condition as I expected?


问:
How To Send Gift Card Mail With External Api
i tried to build a custom gift card app to shopify.
one of the functionality is that the customer can send the giftcard to other customer.
i create a webhook that listen to order creation an get the info.
if there is a line item property like "send to other" i want to prevent shopify automatic mail and send it from my api, to the email that the customer insert in "email to send" line item property.
any ideas how i can do that ? i know that gift card hero app do something like this.
thanks for the help !

i didnt tried anything yet cause i dont find any solution


问:
rxjs update the list in all components after create method
I have a read function that returns a Subject, I subscribe and get a list of all entries in the component, but after the create method, I need to reload the page to see the changes, how can I update the list in the component without reloading the page?
component:

```<code>ngOnInit(): void {
this._bs.read({}).subscribe((birds: Bird) => {
  this.birds = birds
})
</code>```

service:

```<code>create(doc: Document = this.new()): Subject<Document> {
if (Object(doc)._id && Object(doc).keys.indexOf(this._id) === -1) {
  return this.update(doc);
}
else {
  const sub = this._http.post(this._url + '/create', doc);
  this._reads.push(sub)
  return sub;
 }
}
read(opts: CrudOptions = {} as CrudOptions): any {
const sub = this._http.get(this._url + '/get');
  return sub;
}
</code>```

Body:
I have a read function that returns a Subject, I subscribe and get a list of all entries in the component, but after the create method, I need to reload the page to see the changes, how can I update the list in the component without reloading the page?
component:

ngOnInit(): void {
this._bs.read({}).subscribe((birds: Bird) => {
  this.birds = birds
})

service:

create(doc: Document = this.new()): Subject<Document> {
if (Object(doc)._id && Object(doc).keys.indexOf(this._id) === -1) {
  return this.update(doc);
}
else {
  const sub = this._http.post(this._url + '/create', doc);
  this._reads.push(sub)
  return sub;
 }
}
read(opts: CrudOptions = {} as CrudOptions): any {
const sub = this._http.get(this._url + '/get');
  return sub;
}


问:
PHPmyadmin wordpress comments count query
```<code>UPDATE mydomain.1we9ZZc0_posts wpp
LEFT JOIN
(SELECT comment_post_id AS c_post_id, count(*) AS cnt FROM mydomain.1we9ZZc0_comments
WHERE comment_approved = 1 GROUP BY comment_post_id) wpc
ON wpp.id=wpc.c_post_id
SET wpp.comment_count=wpc.cnt
WHERE wpp.post_type IN ('post', 'page')
AND (wpp.comment_count!=wpc.cnt OR (wpp.comment_count != 0 AND wpc.cnt IS NULL));
</code>```

That query is supposed to correct a list of false comment counts on my site but I am getting this error....

```<code>UPDATE mydomain.1we9ZZc0_posts wppLEFT JOIN(SELECT comment_post_id AS c_post_id, count(*) AS cnt FROM mydomain.1we9ZZc0_commentsWHERE comment_approved = 1 GROUP BY comment_post_id) wpcON wpp.id=wpc.c_post_idSET wpp.comment_count=wpc.cntWHERE wpp.post_type IN ('post', 'page')AND (wpp.comment_count!=wpc.cnt OR (wpp.comment_count != 0 AND wpc.cnt IS NULL));
</code>```

MySQL said:

#1048 - Column 'comment_count' cannot be null

See above. I tried that query but I got it from a 5 year old thread so the "cannot be null" must be something having to do with the age of the query.

Body:
UPDATE mydomain.1we9ZZc0_posts wpp
LEFT JOIN
(SELECT comment_post_id AS c_post_id, count(*) AS cnt FROM mydomain.1we9ZZc0_comments
WHERE comment_approved = 1 GROUP BY comment_post_id) wpc
ON wpp.id=wpc.c_post_id
SET wpp.comment_count=wpc.cnt
WHERE wpp.post_type IN ('post', 'page')
AND (wpp.comment_count!=wpc.cnt OR (wpp.comment_count != 0 AND wpc.cnt IS NULL));

That query is supposed to correct a list of false comment counts on my site but I am getting this error....

UPDATE mydomain.1we9ZZc0_posts wppLEFT JOIN(SELECT comment_post_id AS c_post_id, count(*) AS cnt FROM mydomain.1we9ZZc0_commentsWHERE comment_approved = 1 GROUP BY comment_post_id) wpcON wpp.id=wpc.c_post_idSET wpp.comment_count=wpc.cntWHERE wpp.post_type IN ('post', 'page')AND (wpp.comment_count!=wpc.cnt OR (wpp.comment_count != 0 AND wpc.cnt IS NULL));

MySQL said:

#1048 - Column 'comment_count' cannot be null

See above. I tried that query but I got it from a 5 year old thread so the "cannot be null" must be something having to do with the age of the query.


问:
How i can fix my functions automatic repetition
So i have a voice assistant project i use speech recognition and pytsx3, the problem is the functions repetition, so this is my code

main.py:

```<code>import possibilities as ps

clear = lambda: os.system('cls')
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[3].id)
engine.setProperty("rate", 160)
def speak(audio):
    engine.say(audio)
    engine.runAndWait()
while True:

    rec = sr.Recognizer()
    with sr.Microphone() as mic:
        print("Manini listen...")
        audio = rec.listen(mic)
        try:
            text = rec.recognize_google(audio, language='en')
            query = text.lower()
        except Exception as e:
            print("Manini Listen...")

    if 'wikipedia' in query:
        ps.wikipediaSer(query)

    elif "say" in query:
        ps.sayrep(query)

    elif 'open youtube' in query:
        ps.openyoutube()
</code>```

possibilties.py:

```<code>def wikipediaSer(query):
    speak('Searching Wikipedia...')
    query = query.replace("wikipedia", "")
    results = wikipedia.summary(query, sentences = 2)
    speak("According to Wikipedia")
    print(results)
    speak(results)

def sayrep(query):
        say_text = query.replace("say", "")
        speak(say_text)

def openyoutube():
    speak("Here you go to Youtube\n")
    webbrowser.open("youtube.com")
</code>```

so when I execute the project and say a command Wikipedia par example, Wikipedia code repet 5 times. how I can fix this repetition please.

Body:
So i have a voice assistant project i use speech recognition and pytsx3, the problem is the functions repetition, so this is my code

main.py:

import possibilities as ps

clear = lambda: os.system('cls')
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[3].id)
engine.setProperty("rate", 160)
def speak(audio):
    engine.say(audio)
    engine.runAndWait()
while True:

    rec = sr.Recognizer()
    with sr.Microphone() as mic:
        print("Manini listen...")
        audio = rec.listen(mic)
        try:
            text = rec.recognize_google(audio, language='en')
            query = text.lower()
        except Exception as e:
            print("Manini Listen...")

    if 'wikipedia' in query:
        ps.wikipediaSer(query)

    elif "say" in query:
        ps.sayrep(query)

    elif 'open youtube' in query:
        ps.openyoutube()

possibilties.py:

def wikipediaSer(query):
    speak('Searching Wikipedia...')
    query = query.replace("wikipedia", "")
    results = wikipedia.summary(query, sentences = 2)
    speak("According to Wikipedia")
    print(results)
    speak(results)

def sayrep(query):
        say_text = query.replace("say", "")
        speak(say_text)

def openyoutube():
    speak("Here you go to Youtube\n")
    webbrowser.open("youtube.com")

so when I execute the project and say a command Wikipedia par example, Wikipedia code repet 5 times. how I can fix this repetition please.


问:
Memory Leak with readFile
Node-v12.14.2

I'm using the same code here and I observe no memory leak here.

readFileHandle takes around 48MB of memory.

Node-v16.14.2

When I updated to node 16 the memory leak is happening which is observed with the readFile function of fs.

readFileHandle takes around 101MB of memory.

I'm running the same code in both cases, while the garbage collection is happening in the case of node 12, in node 16 the memory keeps on increasing without being released.

In the below code, I'm reading a file from the path and passing it to another function for adding a few details and then returning the data back to the function where it was invoked.
If possible I want to release the memory that's stored by readFile in memory once the execution is done.

Code:

```<code>const readData = () => {
    const jsCode = await fs.readFile('/path', {'utf8'})
    const data = requireString(jsCode) // Add few details
    return data;
}

const handleRoute = () => {
    const comp = readData();
}
</code>```

Title: Memory Leak with readFile

Body:
Node-v12.14.2

I'm using the same code here and I observe no memory leak here.

readFileHandle takes around 48MB of memory.

Node-v16.14.2

When I updated to node 16 the memory leak is happening which is observed with the readFile function of fs.

readFileHandle takes around 101MB of memory.

I'm running the same code in both cases, while the garbage collection is happening in the case of node 12, in node 16 the memory keeps on increasing without being released.

In the below code, I'm reading a file from the path and passing it to another function for adding a few details and then returning the data back to the function where it was invoked.
If possible I want to release the memory that's stored by readFile in memory once the execution is done.

Code:

const readData = () => {
    const jsCode = await fs.readFile('/path', {'utf8'})
    const data = requireString(jsCode) // Add few details
    return data;
}

const handleRoute = () => {
    const comp = readData();
}


问:
Data Not Found Hit API of Unit Testing Laravel 8.x
I'm new to working on backend to make a unit testing of index method with Bearer Token for authentication.

But, I got failure after I run the command : .\vendor\bin\phpunit like below :

```<code>PHPUnit 9.5.27 by Sebastian Bergmann and contributors.

..F                                                                 3 / 3 (100%)

Time: 00:00.228, Memory: 24.00 MB

There was 1 failure:

1) Tests\Feature\UserControllerTest::test_returns_user_data_list_successfully
Expected response status code [200] but received 404.

The following errors occurred during the request:

{
    "success": false,
    "message": "Failed",
    "error_code": 4041,
    "errors": {
        "message": "Data not found"
    }
}

Failed asserting that 200 is identical to 404.

C:\Users\artha\Documents\Switch\vendor\laravel\framework\src\Illuminate\Testing\TestResponse.php:177
C:\Users\artha\Documents\Switch\tests\Feature\UserControllerTest.php:18
</code>```

For UserContoller.php :

```<code>class UserController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth.jwt');
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $user = User::orderBy('created_at', 'DESC')->all();
        $message = 'Success';
        return $this->sendResponse($user->makeVisible('role'), $message, 200);
    }
}
</code>```

The code of route/api.php :

```<code>Route::resource('user', UserController::class, ['except' => ['create', 'edit']]);
</code>```

And I made UserContollerTest.php like below :

```<code><?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Tests\TestCase;

class UserControllerTest extends TestCase
{
    public function test_returns_user_data_list_successfully()
    {
        $token    = 'eyJ0eXA.....dY3CtVO1T4o--8nM';
        $response = $this->withHeaders(['Authorization' => 'Bearer '. $token,
                        'Accept' => 'application/json'])
                        ->get('api/user/index');

        $response->assertStatus(200);
    }
}
</code>```

I tried to solved with various ways on internet like read all official documentations and others but I didn't get insight right to solve this. I made .env.testing, too.

Any idea, how to solving this problem?

Thank you for your insight.

I tried to solve with these link :
https://stackoverflow.com/questions/46769959/laravel-phpunit-test-with-api-token-authentication

https://stackoverflow.com/questions/55568924/how-to-pass-bearer-token-to-test-api-using-phpunit-and-liip

https://laravel.com/docs/6.x/http-tests#session-and-authentication

Body:
I'm new to working on backend to make a unit testing of index method with Bearer Token for authentication.

But, I got failure after I run the command : .\vendor\bin\phpunit like below :

PHPUnit 9.5.27 by Sebastian Bergmann and contributors.

..F                                                                 3 / 3 (100%)

Time: 00:00.228, Memory: 24.00 MB

There was 1 failure:

1) Tests\Feature\UserControllerTest::test_returns_user_data_list_successfully
Expected response status code [200] but received 404.

The following errors occurred during the request:

{
    "success": false,
    "message": "Failed",
    "error_code": 4041,
    "errors": {
        "message": "Data not found"
    }
}

Failed asserting that 200 is identical to 404.

C:\Users\artha\Documents\Switch\vendor\laravel\framework\src\Illuminate\Testing\TestResponse.php:177
C:\Users\artha\Documents\Switch\tests\Feature\UserControllerTest.php:18

For UserContoller.php :

class UserController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth.jwt');
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $user = User::orderBy('created_at', 'DESC')->all();
        $message = 'Success';
        return $this->sendResponse($user->makeVisible('role'), $message, 200);
    }
}

The code of route/api.php :

Route::resource('user', UserController::class, ['except' => ['create', 'edit']]);

And I made UserContollerTest.php like below :

<?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Tests\TestCase;

class UserControllerTest extends TestCase
{
    public function test_returns_user_data_list_successfully()
    {
        $token    = 'eyJ0eXA.....dY3CtVO1T4o--8nM';
        $response = $this->withHeaders(['Authorization' => 'Bearer '. $token,
                        'Accept' => 'application/json'])
                        ->get('api/user/index');

        $response->assertStatus(200);
    }
}

I tried to solved with various ways on internet like read all official documentations and others but I didn't get insight right to solve this. I made .env.testing, too.

Any idea, how to solving this problem?

Thank you for your insight.

I tried to solve with these link :
https://stackoverflow.com/questions/46769959/laravel-phpunit-test-with-api-token-authentication

https://stackoverflow.com/questions/55568924/how-to-pass-bearer-token-to-test-api-using-phpunit-and-liip

https://laravel.com/docs/6.x/http-tests#session-and-authentication