问:
0xc0000142 Error when calling CreateProcess while spoofing parent pid
I am currently trying to launch a program while spoofing the parent pid. Below is my code that does all the work..

```<code>
int main(int argc, char* argv[]) {
    STARTUPINFOEX si = { sizeof(si) };
    PROCESS_INFORMATION pi;
    SIZE_T attributeSize;

    InitializeProcThreadAttributeList(NULL, 1, 0, &attributeSize);
    si.lpAttributeList = (LPPROC_THREAD_ATTRIBUTE_LIST)HeapAlloc(GetProcessHeap(), 0, attributeSize);
    InitializeProcThreadAttributeList(si.lpAttributeList, 1, 0, &attributeSize);

    DWORD dwParentPID = 14256; //cmd.exe pid

    HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwParentPID);
    if (!hProcess) {
        return -1;
    }

    UpdateProcThreadAttribute(si.lpAttributeList, 0, PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, &hProcess, sizeof(HANDLE), NULL, NULL);

    LPCWSTR spawnProcess1 = L"C:\\Users\\user\\source\\repos\\random_testing\\x64\\Debug\\test.exe";
    CreateProcess(spawnProcess1, NULL, NULL, NULL, FALSE, EXTENDED_STARTUPINFO_PRESENT, NULL, NULL, (STARTUPINFO*)&si, &pi);
    return 0;
}
</code>```

The second program I have is just a program that prints hello world.

test.exe

```<code>int main(int argc, char* argv[]) {
    printf("Hello World!\n");
    getchar();
    return 1;
}
</code>```

When I run the above code to spoof the PPID of test.exe I get an error "The application was unable to start correctly (0xc0000142). Click OK to close the application." I am trying to spoof the cmd.exe process.

If I try do CreateProcess on something like notepad or calc, it will work. But some reason it does not for my simple hello world.

Body:
I am currently trying to launch a program while spoofing the parent pid. Below is my code that does all the work..

int main(int argc, char* argv[]) {
    STARTUPINFOEX si = { sizeof(si) };
    PROCESS_INFORMATION pi;
    SIZE_T attributeSize;

    InitializeProcThreadAttributeList(NULL, 1, 0, &attributeSize);
    si.lpAttributeList = (LPPROC_THREAD_ATTRIBUTE_LIST)HeapAlloc(GetProcessHeap(), 0, attributeSize);
    InitializeProcThreadAttributeList(si.lpAttributeList, 1, 0, &attributeSize);

    DWORD dwParentPID = 14256; //cmd.exe pid

    HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwParentPID);
    if (!hProcess) {
        return -1;
    }

    UpdateProcThreadAttribute(si.lpAttributeList, 0, PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, &hProcess, sizeof(HANDLE), NULL, NULL);

    LPCWSTR spawnProcess1 = L"C:\\Users\\user\\source\\repos\\random_testing\\x64\\Debug\\test.exe";
    CreateProcess(spawnProcess1, NULL, NULL, NULL, FALSE, EXTENDED_STARTUPINFO_PRESENT, NULL, NULL, (STARTUPINFO*)&si, &pi);
    return 0;
}

The second program I have is just a program that prints hello world.

test.exe

int main(int argc, char* argv[]) {
    printf("Hello World!\n");
    getchar();
    return 1;
}

When I run the above code to spoof the PPID of test.exe I get an error "The application was unable to start correctly (0xc0000142). Click OK to close the application." I am trying to spoof the cmd.exe process.

If I try do CreateProcess on something like notepad or calc, it will work. But some reason it does not for my simple hello world.


来源: stackexchange

问:
How to rewrite a tensorboard file? (checksum error)
I can't find anywhere how to open read and rewrite a tensorboard file (without the dependency of tensorflow).
Using the following code yields a mysterious checksum error:

Do you know what is causing this and how I can rewrite the file?
(If you print event it looks normal.)

Here is the code:

```<code>import sys
import struct
import tensorboard.compat.proto.event_pb2 as event_pb2
import mmap

log_file = sys.argv[1]

def read(data, offset):
    header = struct.unpack_from('Q', data, offset)
    event_str = data[offset+12:offset+12+int(header[0])]
    return 12+int(header[0])+4+offset, event_str

with open(log_file, 'rb') as f:
    data = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)

offset = 0
while offset < len(data):
    offset, event_str = read(data, offset)
    event = event_pb2.Event()
    event.ParseFromString(event_str)

    with open('test.tfevents', 'ab') as w:
        w.write(event.SerializeToString())
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I can't find anywhere how to open read and rewrite a tensorboard file (without the dependency of tensorflow).
Using the following code yields a mysterious checksum error:

Do you know what is causing this and how I can rewrite the file?
(If you print event it looks normal.)

Here is the code:

import sys
import struct
import tensorboard.compat.proto.event_pb2 as event_pb2
import mmap

log_file = sys.argv[1]

def read(data, offset):
    header = struct.unpack_from('Q', data, offset)
    event_str = data[offset+12:offset+12+int(header[0])]
    return 12+int(header[0])+4+offset, event_str

with open(log_file, 'rb') as f:
    data = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)

offset = 0
while offset < len(data):
    offset, event_str = read(data, offset)
    event = event_pb2.Event()
    event.ParseFromString(event_str)

    with open('test.tfevents', 'ab') as w:
        w.write(event.SerializeToString())


问:
error while trying to implement native android stripe sdk into a flutter app
I have a flutter app running on old framework version, therefore I can't use flutter stripe sdk. I decided to implement native stripe android sdk and call it through method channel from flutter.

After copying code from stripe sdk implementation page (https://stripe.com/docs/google-pay) and trying to show google pay activity, I get the following error:

```<code>E/MethodChannel#methodChannel(12740): Failed to handle method call
E/MethodChannel#methodChannel(12740): java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
E/MethodChannel#methodChannel(12740):   at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:129)
E/MethodChannel#methodChannel(12740):   at com.stripe.android.networking.AnalyticsRequestFactory.<init>(AnalyticsRequestFactory.kt:60)
E/MethodChannel#methodChannel(12740):   at com.stripe.android.networking.AnalyticsRequestFactory.<init>(AnalyticsRequestFactory.kt:37)
E/MethodChannel#methodChannel(12740):   at com.stripe.android.googlepaylauncher.GooglePayLauncher.<init>(GooglePayLauncher.kt:74)
E/MethodChannel#methodChannel(12740):   at au.com.xxxxx.xxxxx.MainActivity$configureFlutterEngine$1.onMethodCall(MainActivity.kt:40)
E/MethodChannel#methodChannel(12740):   at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:233)
E/MethodChannel#methodChannel(12740):   at io.flutter.embedding.engine.dart.DartMessenger.handleMessageFromDart(DartMessenger.java:85)
E/MethodChannel#methodChannel(12740):   at io.flutter.embedding.engine.FlutterJNI.handlePlatformMessage(FlutterJNI.java:692)
E/MethodChannel#methodChannel(12740):   at android.os.MessageQueue.nativePollOnce(Native Method)
</code>```

Seems like its is failing to get context of my flutter app, but I might be mistaken. Any idea how to fix this?

I was thinking about manually assigning context in onCreate() method to flutter context, but it seems like context is a final variable.

My code

```<code>import android.app.Activity
import android.content.Context
import android.os.Bundle
import androidx.annotation.NonNull
import com.stripe.android.PaymentConfiguration
import com.stripe.android.googlepaylauncher.GooglePayEnvironment
import com.stripe.android.googlepaylauncher.GooglePayLauncher
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.android.FlutterFragmentActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodChannel

class MainActivity: FlutterActivity() {

    private lateinit var clientSecret: String
    private val CHANNEL = "methodChannel"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {

    super.configureFlutterEngine(flutterEngine)
        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler {
            // This method is invoked on the main thread.
            call, result ->
            if (call.method == "payWithGoogle") {
                println("Pay with google")

                PaymentConfiguration.init(this, "xxxxxxxxxx")
                val googlePayLauncher = GooglePayLauncher(
                        activity = FlutterFragmentActivity(),
                        config = GooglePayLauncher.Config(
                        environment = GooglePayEnvironment.Test,
                        merchantCountryCode = "AU",
                        merchantName = "xxxxxxx"
                ),
                readyCallback = ::onGooglePayReady,
                resultCallback = ::onGooglePayResult
                )

               googlePayLauncher.presentForPaymentIntent(clientSecret)

            } else {
                result.notImplemented()
            }

        }
    }

    private fun onGooglePayReady(isReady: Boolean) {
       println("onGooglePayReady")

    }

    private fun onGooglePayResult(result: GooglePayLauncher.Result) {

        when (result) {
            GooglePayLauncher.Result.Completed -> {
                "Successfully collected payment."
            }
            GooglePayLauncher.Result.Canceled -> {
                "Customer cancelled Google Pay."
            }
            is GooglePayLauncher.Result.Failed -> {
                "Google Pay failed. ${result.error.message}"
            }
        }
    }
}
</code>```

Body:
I have a flutter app running on old framework version, therefore I can't use flutter stripe sdk. I decided to implement native stripe android sdk and call it through method channel from flutter.

After copying code from stripe sdk implementation page (https://stripe.com/docs/google-pay) and trying to show google pay activity, I get the following error:

E/MethodChannel#methodChannel(12740): Failed to handle method call
E/MethodChannel#methodChannel(12740): java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
E/MethodChannel#methodChannel(12740):   at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:129)
E/MethodChannel#methodChannel(12740):   at com.stripe.android.networking.AnalyticsRequestFactory.<init>(AnalyticsRequestFactory.kt:60)
E/MethodChannel#methodChannel(12740):   at com.stripe.android.networking.AnalyticsRequestFactory.<init>(AnalyticsRequestFactory.kt:37)
E/MethodChannel#methodChannel(12740):   at com.stripe.android.googlepaylauncher.GooglePayLauncher.<init>(GooglePayLauncher.kt:74)
E/MethodChannel#methodChannel(12740):   at au.com.xxxxx.xxxxx.MainActivity$configureFlutterEngine$1.onMethodCall(MainActivity.kt:40)
E/MethodChannel#methodChannel(12740):   at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:233)
E/MethodChannel#methodChannel(12740):   at io.flutter.embedding.engine.dart.DartMessenger.handleMessageFromDart(DartMessenger.java:85)
E/MethodChannel#methodChannel(12740):   at io.flutter.embedding.engine.FlutterJNI.handlePlatformMessage(FlutterJNI.java:692)
E/MethodChannel#methodChannel(12740):   at android.os.MessageQueue.nativePollOnce(Native Method)

Seems like its is failing to get context of my flutter app, but I might be mistaken. Any idea how to fix this?

I was thinking about manually assigning context in onCreate() method to flutter context, but it seems like context is a final variable.

My code

import android.app.Activity
import android.content.Context
import android.os.Bundle
import androidx.annotation.NonNull
import com.stripe.android.PaymentConfiguration
import com.stripe.android.googlepaylauncher.GooglePayEnvironment
import com.stripe.android.googlepaylauncher.GooglePayLauncher
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.android.FlutterFragmentActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodChannel

class MainActivity: FlutterActivity() {

    private lateinit var clientSecret: String
    private val CHANNEL = "methodChannel"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {

    super.configureFlutterEngine(flutterEngine)
        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler {
            // This method is invoked on the main thread.
            call, result ->
            if (call.method == "payWithGoogle") {
                println("Pay with google")

                PaymentConfiguration.init(this, "xxxxxxxxxx")
                val googlePayLauncher = GooglePayLauncher(
                        activity = FlutterFragmentActivity(),
                        config = GooglePayLauncher.Config(
                        environment = GooglePayEnvironment.Test,
                        merchantCountryCode = "AU",
                        merchantName = "xxxxxxx"
                ),
                readyCallback = ::onGooglePayReady,
                resultCallback = ::onGooglePayResult
                )

               googlePayLauncher.presentForPaymentIntent(clientSecret)

            } else {
                result.notImplemented()
            }

        }
    }

    private fun onGooglePayReady(isReady: Boolean) {
       println("onGooglePayReady")

    }

    private fun onGooglePayResult(result: GooglePayLauncher.Result) {

        when (result) {
            GooglePayLauncher.Result.Completed -> {
                "Successfully collected payment."
            }
            GooglePayLauncher.Result.Canceled -> {
                "Customer cancelled Google Pay."
            }
            is GooglePayLauncher.Result.Failed -> {
                "Google Pay failed. ${result.error.message}"
            }
        }
    }
}


问:
Referral program - keep query string
I am looking for a way to maintain a query string entry in all routes. I am adding the option of a referral program in the application.

Let's say the main URL is:

```<code>www.example.com

</code>```

We also have :

```<code>www.example.com/faq
www.example.com/about
www.example.com/login
</code>```

I want to share my code and I could share it in any path, let's say I share the following url:

```<code>www.example.com/faq?refCode=123
</code>```

If the person I sent the url to decides to check the about page, the result should be the following (keeping the referral code):

```<code>www.example.com/about?refCode=123
</code>```

I have been able to handle this value in the controller but I need to keep the parameter in the URL.

I hope it is understood and thank you very much!

Title: Referral program - keep query string

Body:
I am looking for a way to maintain a query string entry in all routes. I am adding the option of a referral program in the application.

Let's say the main URL is:

www.example.com

We also have :

www.example.com/faq
www.example.com/about
www.example.com/login

I want to share my code and I could share it in any path, let's say I share the following url:

www.example.com/faq?refCode=123

If the person I sent the url to decides to check the about page, the result should be the following (keeping the referral code):

www.example.com/about?refCode=123

I have been able to handle this value in the controller but I need to keep the parameter in the URL.

I hope it is understood and thank you very much!


问:
Why does my react render does not show up on soft refresh (with cache) only when I hard refresh the page?
UPDATE: Apparently it shows up when I press 'Ctrl + Shift + R' but no idea why...

I had it working just fine where my icon was showing up where I wanted but for some reason it stopped working and when I go to Console it shows that the problem is in my .tsx file, saying that my querySelector is null (I can see it isn't when I run the code on console

I tried removing all the "extra" lines and left it very simple and still won't work

```<code>import React from "react";
import ReactDOM from "react-dom";

class IconComp extends React.Component {

    render() {
        return (
            <div id="IconIDIconID">I</div>

        )
    }
}

const app: HTMLElement = document.createElement('div') as HTMLElement;
const pos: HTMLElement = document.querySelector('.gb_1d.gb_3a.gb_Pd.gb_4d') as HTMLElement;
pos.appendChild(app);
ReactDOM.render(<IconComp />, app);
</code>```

Body:
UPDATE: Apparently it shows up when I press 'Ctrl + Shift + R' but no idea why...

I had it working just fine where my icon was showing up where I wanted but for some reason it stopped working and when I go to Console it shows that the problem is in my .tsx file, saying that my querySelector is null (I can see it isn't when I run the code on console

I tried removing all the "extra" lines and left it very simple and still won't work

import React from "react";
import ReactDOM from "react-dom";

class IconComp extends React.Component {

    render() {
        return (

I

        )
    }
}

const app: HTMLElement = document.createElement('div') as HTMLElement;
const pos: HTMLElement = document.querySelector('.gb_1d.gb_3a.gb_Pd.gb_4d') as HTMLElement;
pos.appendChild(app);
ReactDOM.render(<IconComp />, app);


问:
I am trying to stream an audio file in my android media player app which is placed in aws s3 bucket
I am trying to achieve this through URL and when I add the s3 URL of that item activity in my app is getting crashed...
how can I stream the audio file from s3 in android studio?

In the below code with the commented line it is working fine but with s3 item URL app is crashing

```<code>private void prepareMediaPlayer(){
    try{
       // mediaPlayer.setDataSource("https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3");
      mediaPlayer.setDataSource("https://testing-ariya.s3.ap-   south1.amazonaws.com/Faded_320(PaglaSongs).mp3");
            mediaPlayer.prepare();
            textTotalDuration.setText(milisecToTimer(mediaPlayer.getDuration()));

    }catch (Exception e){
        Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
    }
}
</code>```

Body:
I am trying to achieve this through URL and when I add the s3 URL of that item activity in my app is getting crashed...
how can I stream the audio file from s3 in android studio?

In the below code with the commented line it is working fine but with s3 item URL app is crashing

private void prepareMediaPlayer(){
    try{
       // mediaPlayer.setDataSource("https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3");
      mediaPlayer.setDataSource("https://testing-ariya.s3.ap-   south1.amazonaws.com/Faded_320(PaglaSongs).mp3");
            mediaPlayer.prepare();
            textTotalDuration.setText(milisecToTimer(mediaPlayer.getDuration()));

    }catch (Exception e){
        Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
    }
}


问:
Unable to load private Nuget packages in MAC VisualStudio
First of all I am able to use the same private nugget package in Windows VisualStudio2022 but not in MacBook.

What I tried:-

Has used the PAT method,
Also used the SetApikey method,

I am not able to figure what I am missing can anyone please help me out of this.


问:
ConcurrentModificationException in LiveData Android
There is one background service that provides a stream of data and updates the live data.
We receive an exception when iterating through the arraylist. We got a concurrent modification exception while iterating through the arraylist. How we can solve this problem?

val _receivedCommandList = MutableLiveData<ArrayList<String>>() val receivedCommandList: LiveData<ArrayList<String>> get() = _receivedCommandList

```<code>homeViewModel.command.observe(viewLifecycleOwner, Observer {
    binding.descriptionText.text = ""
    var cmd = ""
    for (command in it){
        cmd += "${command.trim()}\n\n"
    }
    binding.descriptionText.text = cmd
})
</code>```

The mutable live data (_receivedCommandList) will be updated inside the service when onCharacteristicChanged() in BLE.

```<code>repository?.let {
       val sdf = SimpleDateFormat("yyyyMMdd hh:mm:ss ")
       val command = "\n${sdf.format(Date())} A -> B = $cmd\n"
                        commandList.add(0,command)
       it._receivedCommandList.postValue(commandList)
}
</code>```

We tried to put delay while iterating through list, it works fine when list is small but when list becomes large it gives exception again.

Body:
There is one background service that provides a stream of data and updates the live data.
We receive an exception when iterating through the arraylist. We got a concurrent modification exception while iterating through the arraylist. How we can solve this problem?

val _receivedCommandList = MutableLiveData<ArrayList<String>>() val receivedCommandList: LiveData<ArrayList<String>> get() = _receivedCommandList

homeViewModel.command.observe(viewLifecycleOwner, Observer {
    binding.descriptionText.text = ""
    var cmd = ""
    for (command in it){
        cmd += "${command.trim()}\n\n"
    }
    binding.descriptionText.text = cmd
})

The mutable live data (_receivedCommandList) will be updated inside the service when onCharacteristicChanged() in BLE.

repository?.let {
       val sdf = SimpleDateFormat("yyyyMMdd hh:mm:ss ")
       val command = "\n${sdf.format(Date())} A -> B = $cmd\n"
                        commandList.add(0,command)
       it._receivedCommandList.postValue(commandList)
}

We tried to put delay while iterating through list, it works fine when list is small but when list becomes large it gives exception again.


问:
How to do a Local Communication between Console and Web application
I'm trying to send Data from a console application to a web application locally + I want to active the search function in the webapplication by calling : pressing Enter event :

this one represents the console application which will send the Part's ID when we press on SEND button;

this image represents my webapplication which is the destination of my Part's ID.

I want from the SEND button to do :

Copy the Part's ID

Send it to the webapplication "

start the Enter event : to launch the searching ( Enter Key)

I tried to do the Copy function :

```<code>  private void btnCopy_Click(object sender, EventArgs e)
        {
            Clipboard.SetText(textBox1.Text);
        }
</code>```

and it works , but when i came to the paste phase ( get ) i  couldn't figure out how to specify the correct direction ( Webapplication )  in my console application + i didn't figure out how to launch the Enter event Key after pasting in the Webapplication in order to launch the searching phase of my part.

Remark : I want my connexion to be local that's why i didn't use WebAPI in order to connect.

Any help please ?!

Body:
I'm trying to send Data from a console application to a web application locally + I want to active the search function in the webapplication by calling : pressing Enter event :

this one represents the console application which will send the Part's ID when we press on SEND button;

this image represents my webapplication which is the destination of my Part's ID.

I want from the SEND button to do :

Copy the Part's ID

Send it to the webapplication "

start the Enter event : to launch the searching ( Enter Key)

I tried to do the Copy function :

  private void btnCopy_Click(object sender, EventArgs e)
        {
            Clipboard.SetText(textBox1.Text);
        }

and it works , but when i came to the paste phase ( get ) i  couldn't figure out how to specify the correct direction ( Webapplication )  in my console application + i didn't figure out how to launch the Enter event Key after pasting in the Webapplication in order to launch the searching phase of my part.

Remark : I want my connexion to be local that's why i didn't use WebAPI in order to connect.

Any help please ?!


问:
Error running and debugging c file (VS Code
I'm new to C and installed necessary extensions for C but whenever I try to run a simple program I get this error:

"Unable to resolve ${workspaceFolder} in configuration ("workspaceFolder")"

Any solutions in simple terms ?

Some answers on here said to change the path of the workspace folder but I don't have a workspace folder. Some other answers said to not save into OneDrive. The file was saved into OneDrive but another made wasn't and the same issue persisted


问:
filtering files for query databricks taking too long
I have three datasets which join them together with unionAll command. Those datasets are already computed(with count() command) and persisted. The new dataset that i'm generating by unioning those three keeps stucked in 'Filtering files for query' for hours. Since those datasets are already in disk and memory, why it is take so long to filter files? I'm using databricks with 3 workers and 1 main worker, each worker has 14GB of ram and running on pyspark.</p>


问:
Using Source Control on a SSH folder in VS Code
Since I am working on a Windows Machine, recently I connected and configure SSH to my Linux server in VS Code. Usually, when I work on a local folder I always configure the Source Control option in VS Code and it is really simple. However, I am trying to configure the source control using the SSH Folder but I don't know if this is possible as it is not letting me use the Initialize Repository button on my SSH Folder.

Can someone please let me know if this is possible or what is the best way to use Source Control for my SSH folder using VS Code?


问:
How to restart a selenium webdriver that went down in an ongoing testing?
I have setup a selenium grid with 1 Hub and 2 nodes, each node with a capability to host 8 instances of firefox browser, so in total 16 firefox browsers are possible.

Following that, I am running a code which first creates 16 firefox webdrivers. Then goes through a list of websites and executes some task on each website by running that website in any of the 16 firefox webdriver that is available.

Now the issue I am facing is that while going through the list of websites, sometime 1-2 webdrivers go down (quits automatically, don't know why). I am trying to figure out that how to restart/repawn the webdrivers that went down so that the effective number of available webdrivers to perform the job remain at 16.

Here is what I have tried..

```<code>while executed_website_count != len(list_of_websites):

    # getting an available driver from the 16 drivers we had created
    driver = get_driver()

    # getting the next website
    current_link = get_link()

    # if the driver is dead, it will throw an error
    try:
        driver.get(current_link)
    except InvalidSessionIdException:
        new_driver = webdriver.Remote(
            command_executor='http://localhost:4444',
            options=firefox_options
        )
        new_driver.set_window_size(1366, 784)
        drivers_list.append(new_driver)  #storing the new driver in our map of drivers
        driver = new_driver
    except WebDriverException:
        pass

    driver.get(current_link)

    ...further operation on the newly created driver...

</code>```

The issue with this fix is that though it does create a new driver but it is never shown as running (in headless mode) and also, no websites gets assigned to it (basically it is never used).

Body:
I have setup a selenium grid with 1 Hub and 2 nodes, each node with a capability to host 8 instances of firefox browser, so in total 16 firefox browsers are possible.

Following that, I am running a code which first creates 16 firefox webdrivers. Then goes through a list of websites and executes some task on each website by running that website in any of the 16 firefox webdriver that is available.

Now the issue I am facing is that while going through the list of websites, sometime 1-2 webdrivers go down (quits automatically, don't know why). I am trying to figure out that how to restart/repawn the webdrivers that went down so that the effective number of available webdrivers to perform the job remain at 16.

Here is what I have tried..

while executed_website_count != len(list_of_websites):

    # getting an available driver from the 16 drivers we had created
    driver = get_driver()

    # getting the next website
    current_link = get_link()

    # if the driver is dead, it will throw an error
    try:
        driver.get(current_link)
    except InvalidSessionIdException:
        new_driver = webdriver.Remote(
            command_executor='http://localhost:4444',
            options=firefox_options
        )
        new_driver.set_window_size(1366, 784)
        drivers_list.append(new_driver)  #storing the new driver in our map of drivers
        driver = new_driver
    except WebDriverException:
        pass

    driver.get(current_link)

    ...further operation on the newly created driver...

The issue with this fix is that though it does create a new driver but it is never shown as running (in headless mode) and also, no websites gets assigned to it (basically it is never used).


问:
matSideNav showing its own scroll with virtual scroll
I am using a list of expansion panels inside virtual-scroll using scrollWindow,
it works fine until I put this virtual scroll in matSideNav.

```<code><mat-sidenav-container class="example-container">
  <mat-sidenav mode="side" opened>Sidenav content</mat-sidenav>
    <mat-accordion multi>
      <cdk-virtual-scroll-viewport itemSize="50" scrollWindow>
        <mat-expansion-panel *cdkVirtualFor="let item of items">
          <mat-expansion-panel-header>
            <mat-panel-title>
              {{item}}
            </mat-panel-title>
          </mat-expansion-panel-header>
          <div>
            <div>
              Content for {{item}}
            </div>
            <div>
              <button mat-raised-button color='accent'>OK</button>
            </div><div>
              <button mat-raised-button color='accent'>OK</button>
            </div><div>
              <button mat-raised-button color='accent'>OK</button>
            </div>
          </div>
        </mat-expansion-panel>
      </cdk-virtual-scroll-viewport>
    </mat-accordion>
</mat-sidenav-container>
</code>```

when I expand an expansion panel, the side-nav shows its own scroll instead of varying the height of the virtual scroll.

here is the scenario.

steps to recreate the issue

scroll to the bottom

expand the last item

I am using:

angular15

material-design 15

Body:
I am using a list of expansion panels inside virtual-scroll using scrollWindow,
it works fine until I put this virtual scroll in matSideNav.

<mat-sidenav-container class="example-container">
  <mat-sidenav mode="side" opened>Sidenav content</mat-sidenav>
    <mat-accordion multi>
      <cdk-virtual-scroll-viewport itemSize="50" scrollWindow>
        <mat-expansion-panel *cdkVirtualFor="let item of items">
          <mat-expansion-panel-header>
            <mat-panel-title>
              {{item}}
            </mat-panel-title>
          </mat-expansion-panel-header>

              Content for {{item}}

              <button mat-raised-button color='accent'>OK</button>

              <button mat-raised-button color='accent'>OK</button>

              <button mat-raised-button color='accent'>OK</button>

        </mat-expansion-panel>
      </cdk-virtual-scroll-viewport>
    </mat-accordion>
</mat-sidenav-container>

when I expand an expansion panel, the side-nav shows its own scroll instead of varying the height of the virtual scroll.

here is the scenario.

steps to recreate the issue

scroll to the bottom

expand the last item

I am using:

angular15

material-design 15


问:
copy std::vector<unsigned char> address to unsigned char[] array
I have a vector that receives bytes from the network:

std:vector<unsigned char> data

I am trying to copy the address of the data into an unsigned char *[] array:

unsigned char *buffer = new unsigned char [1024*1024]

I want to loop through it to find a valid data packet that I am looking for. The sample code is below.

How do I copy the address of data into buffer?

header file:

```<code>typedef struct {
    uint word;
    int id;
    int nubBytes;
}Header;

#define WORD 0xA345
unsigned char * buffer = new unsigned char[1024*1024];
Header *hdr;
int pktOffset;
</code>```

cpp file:

```<code>Decode msg(std:vector<unsigned char> data, uint32_t bytesrcvd){
    pktOffset = 0;
    buffer = &data;
    rcvBufOffSet += bytesRcvd;
    numBytesInRecBuff += bytesRcvd;
    hdr = (Header *)(& buffer[pktOffset])
    if(hdr->word != WORD){
        while(hdr->word != WORD && numBytesInRecBuff > 0)
            pktOffset++;
        numBytesInRecBuff--;
        hdr = (Header *)(& Buffer[pktOffset])
    }
    if(hdr->word != WORD){
        return;
    }
    else{
        //process packet data
    }
}
</code>```

Body:
I have a vector that receives bytes from the network:

std:vector<unsigned char> data

I am trying to copy the address of the data into an unsigned char *[] array:

unsigned char *buffer = new unsigned char [1024*1024]

I want to loop through it to find a valid data packet that I am looking for. The sample code is below.

How do I copy the address of data into buffer?

header file:

typedef struct {
    uint word;
    int id;
    int nubBytes;
}Header;

#define WORD 0xA345
unsigned char * buffer = new unsigned char[1024*1024];
Header *hdr;
int pktOffset;

cpp file:

Decode msg(std:vector<unsigned char> data, uint32_t bytesrcvd){
    pktOffset = 0;
    buffer = &data;
    rcvBufOffSet += bytesRcvd;
    numBytesInRecBuff += bytesRcvd;
    hdr = (Header *)(& buffer[pktOffset])
    if(hdr->word != WORD){
        while(hdr->word != WORD && numBytesInRecBuff > 0)
            pktOffset++;
        numBytesInRecBuff--;
        hdr = (Header *)(& Buffer[pktOffset])
    }
    if(hdr->word != WORD){
        return;
    }
    else{
        //process packet data
    }
}


问:
dependency-injection: AttributeError: 'DynamicContainer' object has no attribute 'urls'
I'm using a DB notebook and have:

container.py

```<code>class Container(containers.DeclarativeContainer):
    config = providers.Configuration(yaml_files=[path])

def initialize(config_path: Optional[str] = None) -> Container:
  container = Container()
  if config_path:
    container.config.from_yaml(config_path, required=True)

  return container
</code>```

credentials.py

```<code>config = initialize(path)
print (f"{config}")
print (f"{config.urls.my_url()}")
</code>```

init.py

```<code>import os

goal_dir = os.path.join(os.getcwd(), "../../config.yaml")
absolute_configuration_path = os.path.abspath(goal_dir)
</code>```

Instead of gettng the parameter in my path, I get:

```<code>AttributeError: 'DynamicContainer' object has no attribute 'urls'
</code>```

Where am I going wrong? I don't understand exactly why the attribute 'DynamicContainer' is appearing.

Body:
I'm using a DB notebook and have:

container.py

class Container(containers.DeclarativeContainer):
    config = providers.Configuration(yaml_files=[path])

def initialize(config_path: Optional[str] = None) -> Container:
  container = Container()
  if config_path:
    container.config.from_yaml(config_path, required=True)

  return container

credentials.py

config = initialize(path)
print (f"{config}")
print (f"{config.urls.my_url()}")

init.py

import os

goal_dir = os.path.join(os.getcwd(), "../../config.yaml")
absolute_configuration_path = os.path.abspath(goal_dir)

Instead of gettng the parameter in my path, I get:

AttributeError: 'DynamicContainer' object has no attribute 'urls'

Where am I going wrong? I don't understand exactly why the attribute 'DynamicContainer' is appearing.


问:
Ubuntu python cron job outputs "Freeing CompressedMemoryCache" and freezes
I'm running a conventional ML python project on a Ubuntu 18.04 LTS system with 64GB of RAM, registered as a cron job.
At some point during execution, I'm getting output messages like below:

```<code>Freeing CompressedMemoryCache (0)...
Freed 9021
Freeing CompressedMemoryCache (1)...
Freed 10259
Freeing CompressedMemoryCache (2)...
Freed 10549
Freeing CompressedMemoryCache (3)...
Freed 10091
Freeing CompressedMemoryCache (4)...
Freed 10080
Freeing CompressedMemoryCache (0)...
Freed 9678
Freeing CompressedMemoryCache (1)...
Freed 10210
Freeing CompressedMemoryCache (2)...
Freed 10001
Freeing CompressedMemoryCache (3)...
Freed 10010
Freeing CompressedMemoryCache (4)...
Freed 10101
Freeing CompressedMemoryCache (0)...
Freed 9893
</code>```

after that, execution appears to hang / freeze without any error. The number of messages, quantities of what's freed and when the messages pop up during the application execution flow appears to be random.

What library / system produces such messages? I've been unable to find any relevant information online and no component in my code or used packages appears to generate it.

This appears to happen only at a cron setting, this is however difficult to verify due to specifics of how the project is setup.

Do you have any advice for debugging this?

Body:
I'm running a conventional ML python project on a Ubuntu 18.04 LTS system with 64GB of RAM, registered as a cron job.
At some point during execution, I'm getting output messages like below:

Freeing CompressedMemoryCache (0)...
Freed 9021
Freeing CompressedMemoryCache (1)...
Freed 10259
Freeing CompressedMemoryCache (2)...
Freed 10549
Freeing CompressedMemoryCache (3)...
Freed 10091
Freeing CompressedMemoryCache (4)...
Freed 10080
Freeing CompressedMemoryCache (0)...
Freed 9678
Freeing CompressedMemoryCache (1)...
Freed 10210
Freeing CompressedMemoryCache (2)...
Freed 10001
Freeing CompressedMemoryCache (3)...
Freed 10010
Freeing CompressedMemoryCache (4)...
Freed 10101
Freeing CompressedMemoryCache (0)...
Freed 9893

after that, execution appears to hang / freeze without any error. The number of messages, quantities of what's freed and when the messages pop up during the application execution flow appears to be random.

What library / system produces such messages? I've been unable to find any relevant information online and no component in my code or used packages appears to generate it.

This appears to happen only at a cron setting, this is however difficult to verify due to specifics of how the project is setup.

Do you have any advice for debugging this?


问:
Group/Aggregate by tag in a custom metric
I have my own custom counter:

```<code>Counter.builder(NAMESPACE + "country_code")
                .tag("country", country_code)
                .description("Total number of requests per country code (e.g. 0049, 0043, 0044, ...)")
                .register(meterRegistry);
</code>```

I want to get amount of requests grouped by tag country

I have so far:
count(test_country_code_total)

My question: Is it possible to group by tag in promql or is there any alternatives?

Body:
I have my own custom counter:

Counter.builder(NAMESPACE + "country_code")
                .tag("country", country_code)
                .description("Total number of requests per country code (e.g. 0049, 0043, 0044, ...)")
                .register(meterRegistry);

I want to get amount of requests grouped by tag country

I have so far:
count(test_country_code_total)

My question: Is it possible to group by tag in promql or is there any alternatives?


问:
SKPayment Unknown error after paying for subscription ONLY on production
So we're having a hard time trying to debug an error that only occurs when paying for a subscription on production because we cannot get any sort of log. When purchasing on sandbox everything works fine because it never leaves the app, which is even more frustrating since this only happens on apps downloaded from the AppStore.

Here's the thing, whenever we start the purchase of the subscription the app goes to the AppStore to validate the user's payment info but on return the app for whatever reason is greeted by an Unknown error as a description for SKErrorDomain 0 and the purchase flow ends with an error.

What we've ended up doing is trying to restore the purchase whenever the app returns from background but this is only a workaround that still shows an error or not always is called (for whatever reason).

Is there any way to replicate this behavior on sandbox? Or debug an app on the appstore? Because right now whatever fix we try needs to be published on the AppStore before testing.


问:
how to intercept a request to a controller and add a parameter in it
I have an application, which I have to add a parameter to the controller as @requestParam, as would be the best way
With a filter I can filter but not modify the request

I want to add the user by taking it out of the token, for this I have to decode the token and then add the controllers in all the calls


问:
Change Data Capture's unexpected behaviour when altering the table
I'm using CDC feature from SQL Server 2019.

I understand that if I make any DDL changes to the tracked table the changes info will be added to [cdc].[ddl_history] table, but the changes will not reflect in the existing capture instance.

But in my case the following two things happening.

If I make changes to a key column after cdc is enabled, for eg. set IDENTITY Yes to No or vice versa, the cdc is straightaway disabled
automatically and I lost all the capture information.

If I add new columns and delete existing data from the table, it is disabling cdc automatically without adding DDL changes to ddl_history
tables.

Due to this issue the existing jobs failing and creating a big mess of the whole process. please can someone help me on how to deal with this unexpected behaviour. I have gone through most of the documentation on cdc topic from ms documentation. I didn't come across the automatic disabling of cdc on a table, or I must have missed.
Thanks for looking at my query.

UPDATE: I'm making the changes in SSMS, in table designer.

For IDENTITY: Select column properties and then under Identity Specification  set IsIdentity to Yes/No.

For New columns: Add new columns in the designer. Not using ALTER TABLE script (Not sure if it makes a difference to cdc)


问:
How to convert an ONNX model with dynamic input shape to Tensorflow model?
I am trying to convert an ONNX model with a dynamic input shape to TensorFlow format using the onnx_tf package. I am using TensorFlow 2.11.0, ONNX 1.13.0, and onnx_tf 1.10.0. The input to the model contains 3 arrays: the data with dynamic shape (1, None) and 2 arrays with fixed shapes (2,1,64). When I run the following code, I get on the last line a "ValueError: Cannot take the length of shape with unknown rank" :

```<code># Imports
import onnx
from onnx import version_converter
import os
from onnx_tf.backend import prepare

# load onnx model
model_dir = r'model\vad'
model_name = 'vad.onnx'
onnx_model = onnx.load(os.path.join(model_dir,'onnx', model_name))  # load onnx model

# Export to Tensorflow
os.makedirs(os.path.join(model_dir ,'tensorflow'), exist_ok=True)
tf_rep = prepare(onnx_model)  # prepare tf representation
tf_rep.export_graph(os.path.join(model_dir,'tensorflow','vad'))  # export the model
</code>```

What could be causing this error and how can I fix it?

Body:
I am trying to convert an ONNX model with a dynamic input shape to TensorFlow format using the onnx_tf package. I am using TensorFlow 2.11.0, ONNX 1.13.0, and onnx_tf 1.10.0. The input to the model contains 3 arrays: the data with dynamic shape (1, None) and 2 arrays with fixed shapes (2,1,64). When I run the following code, I get on the last line a "ValueError: Cannot take the length of shape with unknown rank" :

# Imports
import onnx
from onnx import version_converter
import os
from onnx_tf.backend import prepare

# load onnx model
model_dir = r'model\vad'
model_name = 'vad.onnx'
onnx_model = onnx.load(os.path.join(model_dir,'onnx', model_name))  # load onnx model

# Export to Tensorflow
os.makedirs(os.path.join(model_dir ,'tensorflow'), exist_ok=True)
tf_rep = prepare(onnx_model)  # prepare tf representation
tf_rep.export_graph(os.path.join(model_dir,'tensorflow','vad'))  # export the model

What could be causing this error and how can I fix it?


问:
Regarding Needs to create an Index on MongoDB for $lookup query
I have 3 different collections which has build relation with the another field then primary id.

For ex, I have users, educations and user profiles 3 different collection and users and educations have relation with key user_id of user and same for userinfo. please find sample data.

```<code>let users = [
    { _id: ObjectId("1"), user_id: 1, name: "Nitin", is_active: true, is_deleted: false },
    { _id: ObjectId("2"), user_id: 2, name: "Vishal", is_active: true, is_deleted: false },
]

let educations =
    [
        { _id: ObjectId("33"), user: 1, std: "10", is_active: true, is_deleted: false },
        { _id: ObjectId("44"), user: 2, std: "8", is_active: true, is_deleted: false },
    ]
let userinfo = [
    { _id: ObjectId("33"), user: 1, weight: "50", is_active: true, is_deleted: false },
    { _id: ObjectId("44"), user: 2, weight: "45", is_active: true, is_deleted: false },
]
</code>```

Now I would like to fetch the relation data and created query by using $lookup by following way.

```<code>let criteria = {
    is_active: true,
    is_deleted: false,
};
const result = await mongoose.connection.db.collection('users').aggregate([
    //education
    { $lookup: { from: "education", localField: "user_id", foreignField: "user", as: "education" } },
    { $unwind: { path: "$education", preserveNullAndEmptyArrays: true } },
    //userinfo
    { $lookup: { from: "userinfo", localField: "user_id", foreignField: "user", as: "userinfo" } },
    { $unwind: { path: "$userinfo", preserveNullAndEmptyArrays: true } },
    { $match: { is_deleted: false } },

    { $match: criteria },
    {
        "$facet": {
            "totalLocation": [
                { $match: criteria },
                { "$count": "count" },
            ],

        }
    },
    {
        "$project": {
            "totalLocation": { "$arrayElemAt": ["$totalLocation.count", 0] },
        }
    }
], { allowDiskUse: true, collation: { locale: 'en_US', alternate: "shifted" } }).toArray();
</code>```

This query works completely fine and return data as expected. But now as data are growing so this query became slower and we would make it faster. one of solution which I found that to create an index in a way so we can have faster result. I have tried but it doesn't works for me

so can anyone help me to create a index on this kind of query. or any another solution.

Explanation as requested in comment

```<code>{
"stages" : [
    {
        "$cursor" : {
            "queryPlanner" : {
                "plannerVersion" : 1,
                "namespace" : "mydata.users",
                "indexFilterSet" : false,
                "parsedQuery" : {
                    "is_deleted" : {
                        "$eq" : false
                    }
                },
                "queryHash" : "242D9E6F",
                "planCacheKey" : "386E80BB",
                "winningPlan" : {
                    "stage" : "PROJECTION_SIMPLE",
                    "transformBy" : {
                        "cb_id" : 1,
                        "user" : 1,
                        "_id" : 0
                    },
                    "inputStage" : {
                        "stage" : "COLLSCAN",
                        "filter" : {
                            "is_deleted" : {
                                "$eq" : false
                            }
                        },
                        "direction" : "forward"
                    }
                },
                "rejectedPlans" : []
            },
            "executionStats" : {
                "executionSuccess" : true,
                "nReturned" : 2328,
                "executionTimeMillis" : 265,
                "totalKeysExamined" : 0,
                "totalDocsExamined" : 2355,
                "executionStages" : {
                    "stage" : "PROJECTION_SIMPLE",
                    "nReturned" : 2328,
                    "executionTimeMillisEstimate" : 10,
                    "works" : 2357,
                    "advanced" : 2328,
                    "needTime" : 28,
                    "needYield" : 0,
                    "saveState" : 3,
                    "restoreState" : 3,
                    "isEOF" : 1,
                    "transformBy" : {
                        "cb_id" : 1,
                        "user" : 1,
                        "_id" : 0
                    },
                    "inputStage" : {
                        "stage" : "COLLSCAN",
                        "filter" : {
                            "is_deleted" : {
                                "$eq" : false
                            }
                        },
                        "nReturned" : 2328,
                        "executionTimeMillisEstimate" : 0,
                        "works" : 2357,
                        "advanced" : 2328,
                        "needTime" : 28,
                        "needYield" : 0,
                        "saveState" : 3,
                        "restoreState" : 3,
                        "isEOF" : 1,
                        "direction" : "forward",
                        "docsExamined" : 2355
                    }
                }
            }
        },
        "nReturned" : NumberLong(2328),
        "executionTimeMillisEstimate" : NumberLong(20)
    },
    {
        "$lookup" : {
            "from" : "education",
            "as" : "education",
            "localField" : "user_id",
            "foreignField" : "user",
            "unwinding" : {
                "preserveNullAndEmptyArrays" : true
            }
        },
        "nReturned" : NumberLong(2328),
        "executionTimeMillisEstimate" : NumberLong(136)
    },
    {
        "$lookup" : {
            "from" : "userinfo",
            "as" : "userinfo",
            "localField" : "user_id",
            "foreignField" : "user",
            "unwinding" : {
                "preserveNullAndEmptyArrays" : true
            }
        },
        "nReturned" : NumberLong(2328),
        "executionTimeMillisEstimate" : NumberLong(264)
    },
    {
        "$facet" : {
            "totalLocation" : [
                {
                    "$teeConsumer" : {},
                    "nReturned" : NumberLong(2328),
                    "executionTimeMillisEstimate" : NumberLong(264)
                },
                {
                    "$group" : {
                        "_id" : {
                            "$const" : null
                        },
                        "count" : {
                            "$sum" : {
                                "$const" : 1
                            }
                        }
                    },
                    "nReturned" : NumberLong(1),
                    "executionTimeMillisEstimate" : NumberLong(264)
                },
                {
                    "$project" : {
                        "count" : true,
                        "_id" : false
                    },
                    "nReturned" : NumberLong(1),
                    "executionTimeMillisEstimate" : NumberLong(264)
                }
            ]
        },
        "nReturned" : NumberLong(1),
        "executionTimeMillisEstimate" : NumberLong(264)
    },
    {
        "$project" : {
            "_id" : true,
            "totalLocation" : {
                "$arrayElemAt" : [
                    "$totalLocation.count",
                    {
                        "$const" : 0.0
                    }
                ]
            }
        },
        "nReturned" : NumberLong(1),
        "executionTimeMillisEstimate" : NumberLong(264)
    }
],
"serverInfo" : {},
"ok" : 1.0
</code>```

}

Thanks

Body:
I have 3 different collections which has build relation with the another field then primary id.

For ex, I have users, educations and user profiles 3 different collection and users and educations have relation with key user_id of user and same for userinfo. please find sample data.

let users = [
    { _id: ObjectId("1"), user_id: 1, name: "Nitin", is_active: true, is_deleted: false },
    { _id: ObjectId("2"), user_id: 2, name: "Vishal", is_active: true, is_deleted: false },
]

let educations =
    [
        { _id: ObjectId("33"), user: 1, std: "10", is_active: true, is_deleted: false },
        { _id: ObjectId("44"), user: 2, std: "8", is_active: true, is_deleted: false },
    ]
let userinfo = [
    { _id: ObjectId("33"), user: 1, weight: "50", is_active: true, is_deleted: false },
    { _id: ObjectId("44"), user: 2, weight: "45", is_active: true, is_deleted: false },
]

Now I would like to fetch the relation data and created query by using $lookup by following way.

let criteria = {
    is_active: true,
    is_deleted: false,
};
const result = await mongoose.connection.db.collection('users').aggregate([
    //education
    { $lookup: { from: "education", localField: "user_id", foreignField: "user", as: "education" } },
    { $unwind: { path: "$education", preserveNullAndEmptyArrays: true } },
    //userinfo
    { $lookup: { from: "userinfo", localField: "user_id", foreignField: "user", as: "userinfo" } },
    { $unwind: { path: "$userinfo", preserveNullAndEmptyArrays: true } },
    { $match: { is_deleted: false } },

    { $match: criteria },
    {
        "$facet": {
            "totalLocation": [
                { $match: criteria },
                { "$count": "count" },
            ],

        }
    },
    {
        "$project": {
            "totalLocation": { "$arrayElemAt": ["$totalLocation.count", 0] },
        }
    }
], { allowDiskUse: true, collation: { locale: 'en_US', alternate: "shifted" } }).toArray();

This query works completely fine and return data as expected. But now as data are growing so this query became slower and we would make it faster. one of solution which I found that to create an index in a way so we can have faster result. I have tried but it doesn't works for me

so can anyone help me to create a index on this kind of query. or any another solution.

Explanation as requested in comment

{
"stages" : [
    {
        "$cursor" : {
            "queryPlanner" : {
                "plannerVersion" : 1,
                "namespace" : "mydata.users",
                "indexFilterSet" : false,
                "parsedQuery" : {
                    "is_deleted" : {
                        "$eq" : false
                    }
                },
                "queryHash" : "242D9E6F",
                "planCacheKey" : "386E80BB",
                "winningPlan" : {
                    "stage" : "PROJECTION_SIMPLE",
                    "transformBy" : {
                        "cb_id" : 1,
                        "user" : 1,
                        "_id" : 0
                    },
                    "inputStage" : {
                        "stage" : "COLLSCAN",
                        "filter" : {
                            "is_deleted" : {
                                "$eq" : false
                            }
                        },
                        "direction" : "forward"
                    }
                },
                "rejectedPlans" : []
            },
            "executionStats" : {
                "executionSuccess" : true,
                "nReturned" : 2328,
                "executionTimeMillis" : 265,
                "totalKeysExamined" : 0,
                "totalDocsExamined" : 2355,
                "executionStages" : {
                    "stage" : "PROJECTION_SIMPLE",
                    "nReturned" : 2328,
                    "executionTimeMillisEstimate" : 10,
                    "works" : 2357,
                    "advanced" : 2328,
                    "needTime" : 28,
                    "needYield" : 0,
                    "saveState" : 3,
                    "restoreState" : 3,
                    "isEOF" : 1,
                    "transformBy" : {
                        "cb_id" : 1,
                        "user" : 1,
                        "_id" : 0
                    },
                    "inputStage" : {
                        "stage" : "COLLSCAN",
                        "filter" : {
                            "is_deleted" : {
                                "$eq" : false
                            }
                        },
                        "nReturned" : 2328,
                        "executionTimeMillisEstimate" : 0,
                        "works" : 2357,
                        "advanced" : 2328,
                        "needTime" : 28,
                        "needYield" : 0,
                        "saveState" : 3,
                        "restoreState" : 3,
                        "isEOF" : 1,
                        "direction" : "forward",
                        "docsExamined" : 2355
                    }
                }
            }
        },
        "nReturned" : NumberLong(2328),
        "executionTimeMillisEstimate" : NumberLong(20)
    },
    {
        "$lookup" : {
            "from" : "education",
            "as" : "education",
            "localField" : "user_id",
            "foreignField" : "user",
            "unwinding" : {
                "preserveNullAndEmptyArrays" : true
            }
        },
        "nReturned" : NumberLong(2328),
        "executionTimeMillisEstimate" : NumberLong(136)
    },
    {
        "$lookup" : {
            "from" : "userinfo",
            "as" : "userinfo",
            "localField" : "user_id",
            "foreignField" : "user",
            "unwinding" : {
                "preserveNullAndEmptyArrays" : true
            }
        },
        "nReturned" : NumberLong(2328),
        "executionTimeMillisEstimate" : NumberLong(264)
    },
    {
        "$facet" : {
            "totalLocation" : [
                {
                    "$teeConsumer" : {},
                    "nReturned" : NumberLong(2328),
                    "executionTimeMillisEstimate" : NumberLong(264)
                },
                {
                    "$group" : {
                        "_id" : {
                            "$const" : null
                        },
                        "count" : {
                            "$sum" : {
                                "$const" : 1
                            }
                        }
                    },
                    "nReturned" : NumberLong(1),
                    "executionTimeMillisEstimate" : NumberLong(264)
                },
                {
                    "$project" : {
                        "count" : true,
                        "_id" : false
                    },
                    "nReturned" : NumberLong(1),
                    "executionTimeMillisEstimate" : NumberLong(264)
                }
            ]
        },
        "nReturned" : NumberLong(1),
        "executionTimeMillisEstimate" : NumberLong(264)
    },
    {
        "$project" : {
            "_id" : true,
            "totalLocation" : {
                "$arrayElemAt" : [
                    "$totalLocation.count",
                    {
                        "$const" : 0.0
                    }
                ]
            }
        },
        "nReturned" : NumberLong(1),
        "executionTimeMillisEstimate" : NumberLong(264)
    }
],
"serverInfo" : {},
"ok" : 1.0

}

Thanks


问:
React Native SectionList different data structure. Type FirstObject is not assignable to SecondObject
I'm using React Native SectionList with different data structure with the following below

```<code>const firstObject: FirstObject = [{
    id: 1,
    age: null,
    breed: null,
    gender: 'female',
    isCastrated: false,
    isCrossbreed: false,
  },
  ...
]

const secondObject: SecondObject = [{
  id: 1,
  text: "qwrqwr12r",
  callDuration: 15,
  callAt: "2022-12-22T11:09:07Z",
  completionDeadline: "2022-12-24T11:09:07Z",
  consultationFreeLength: 1,
  },
  ...
]
</code>```

It works but I got a typescript error that I can't figure out? And it seems it only allowed 1 typing for the section data. What I need is every data from the section must be different. For now we only have 2 and its default the FirstObject and SecondObject its not dynamic

```<code>
    No overload matches this call.
  Overload 1 of 2, '(props: SectionListProps<SecondObject, DefaultSectionT> | Readonly<SectionListProps<SecondObject, DefaultSectionT>>): SectionList<...>', gave the following error.
    Type 'FC<ListRenderItemInfo<FirstObject>>' is not assignable to type 'SectionListRenderItem<SecondObject, DefaultSectionT>'.
      Types of parameters 'props' and 'info' are incompatible.
        Type 'SectionListRenderItemInfo<SecondObject, DefaultSectionT>' is not assignable to type 'ListRenderItemInfo<FirstObject>'.
          Types of property 'item' are incompatible.
            Type 'SecondObject' is missing the following properties from type 'FirstObject': userId, name, speciesId, speciesOther, and 9 more.
  Overload 2 of 2, '(props: SectionListProps<SecondObject, DefaultSectionT>, context: any): SectionList<SecondObject, DefaultSectionT>', gave the following error.
    Type 'FC<ListRenderItemInfo<FirstObject>>' is not assignable to type 'SectionListRenderItem<SecondObject, DefaultSectionT>'.ts(2769)
</code>```

My section list

```<code>  <SectionList
    style={styles.container}
    contentContainerStyle={styles.contentContainer}
    ListEmptyComponent={<TranslatedNoData onClick={refetch} />}
    scrollEventThrottle={16}
    bouncesZoom={false}
    maxToRenderPerBatch={8}
    removeClippedSubviews
    refreshControl={<FlatListRefreshControl refreshing={isFetching} onRefresh={refetch} />}
    sections={[
      {
        data: [],
        title: 'FirstObject',
        keyExtractor: ({id}) => id.toString(),
        renderItem: FirstObjectItem, // <- Error, If I removed the object below it works.
        ItemSeparatorComponent: () => <Box pt="12px" />,
      },
      {
        data: currentData?.data || [],
        title: 'SecondObject',
        keyExtractor: ({id}) => id.toString(),
        renderItem: SecondObjectItem,
        ItemSeparatorComponent: () => <Box pt="12px" />,
      },
    ]}
    renderSectionFooter={() => <Box h="32px" />}
    renderSectionHeader={({section: {title}}) => <Text>{title}</Text>}
    onScroll={
      scrollOffsetY &&
      Animated.event([{nativeEvent: {contentOffset: {y: scrollOffsetY}}}], {useNativeDriver: false})
    }
  />
</code>```

My two components

```<code>const FirstObjectItem: FC<ListRenderItemInfo<FirstObject>> = ({item}) => {
   ...
});
const SecondObjectItem: FC<ListRenderItemInfo<SecondObject>> = ({item}) => {
   ....
});
</code>```

Body:
I'm using React Native SectionList with different data structure with the following below

const firstObject: FirstObject = [{
    id: 1,
    age: null,
    breed: null,
    gender: 'female',
    isCastrated: false,
    isCrossbreed: false,
  },
  ...
]

const secondObject: SecondObject = [{
  id: 1,
  text: "qwrqwr12r",
  callDuration: 15,
  callAt: "2022-12-22T11:09:07Z",
  completionDeadline: "2022-12-24T11:09:07Z",
  consultationFreeLength: 1,
  },
  ...
]

It works but I got a typescript error that I can't figure out? And it seems it only allowed 1 typing for the section data. What I need is every data from the section must be different. For now we only have 2 and its default the FirstObject and SecondObject its not dynamic

    No overload matches this call.
  Overload 1 of 2, '(props: SectionListProps<SecondObject, DefaultSectionT> | Readonly<SectionListProps<SecondObject, DefaultSectionT>>): SectionList<...>', gave the following error.
    Type 'FC<ListRenderItemInfo<FirstObject>>' is not assignable to type 'SectionListRenderItem<SecondObject, DefaultSectionT>'.
      Types of parameters 'props' and 'info' are incompatible.
        Type 'SectionListRenderItemInfo<SecondObject, DefaultSectionT>' is not assignable to type 'ListRenderItemInfo<FirstObject>'.
          Types of property 'item' are incompatible.
            Type 'SecondObject' is missing the following properties from type 'FirstObject': userId, name, speciesId, speciesOther, and 9 more.
  Overload 2 of 2, '(props: SectionListProps<SecondObject, DefaultSectionT>, context: any): SectionList<SecondObject, DefaultSectionT>', gave the following error.
    Type 'FC<ListRenderItemInfo<FirstObject>>' is not assignable to type 'SectionListRenderItem<SecondObject, DefaultSectionT>'.ts(2769)

My section list

  <SectionList
    style={styles.container}
    contentContainerStyle={styles.contentContainer}
    ListEmptyComponent={<TranslatedNoData onClick={refetch} />}
    scrollEventThrottle={16}
    bouncesZoom={false}
    maxToRenderPerBatch={8}
    removeClippedSubviews
    refreshControl={<FlatListRefreshControl refreshing={isFetching} onRefresh={refetch} />}
    sections={[
      {
        data: [],
        title: 'FirstObject',
        keyExtractor: ({id}) => id.toString(),
        renderItem: FirstObjectItem, // <- Error, If I removed the object below it works.
        ItemSeparatorComponent: () => <Box pt="12px" />,
      },
      {
        data: currentData?.data || [],
        title: 'SecondObject',
        keyExtractor: ({id}) => id.toString(),
        renderItem: SecondObjectItem,
        ItemSeparatorComponent: () => <Box pt="12px" />,
      },
    ]}
    renderSectionFooter={() => <Box h="32px" />}
    renderSectionHeader={({section: {title}}) => <Text>{title}</Text>}
    onScroll={
      scrollOffsetY &&
      Animated.event([{nativeEvent: {contentOffset: {y: scrollOffsetY}}}], {useNativeDriver: false})
    }
  />

My two components

const FirstObjectItem: FC<ListRenderItemInfo<FirstObject>> = ({item}) => {
   ...
});
const SecondObjectItem: FC<ListRenderItemInfo<SecondObject>> = ({item}) => {
   ....
});


问:
Angular Material 15 it's duplicating styles
Yesterday I updated my project (advanced complexity) from Angular 14 to 15 (Angular Material too obviously, and I know it came with a lot of breaking changes). After this, I started seeing repeated CSS classes from components:

I made a project from zero just for test, thinking that maybe in the other project I have some stylesheets causing this problem, but got the same issue with the MatTable in this case:

Table styles


问:
I implemented date range fliter in JQuery DataTable . But it is not working

I used the resources from the jQuery DataTable website and also implemented the JQuery  dataTable plugin.

When using the Range Filter code throw jQuery error 'DateTime is not defined'

This is Datepicker

I use the HTML date picker

```<code>            <tbody>
                <tr>
                    <td>Minimum date:</td>
                    <td><input type="date" id="min" name="min"></td>
                </tr>
                <tr>
                    <td>Maximum date:</td>
                    <td><input type="date" id="max" name="max"></td>
                </tr>
            </tbody>
        </table>
</code>```

This is HTML

I binding the data in a table  using jQuery Ajax

```<code>
<table class="table table-striped table-hover table table-bordered border-primary" id="myTable">
            <thead>
                <tr>
                    <th>S.No</th>
                    <th width="20%">State</th>
                    <th width="20%">District</th>
                    <th width="20%">Date</th>
                    <th>Submitted</th>
                    <th>Completed</th>
                    <th>Not Completed</th>
                    <th>Rejected</th>

                </tr>
            </thead>
            <tbody id="OpeatatorDetails">

            </tbody>
 </table>
</code>```

Here jQuery code that I have copied from Jquery Data Table website

```<code>>I have uses following plugin.
<script src="~/js/jquery.min.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.13.1/js/jquery.dataTables.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>

<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/datetime/1.2.0/js/dataTables.dateTime.min.js"></script>
<script type="text/javascript">
   $(document).ready(function () {

        // Create date inputs
        minDate = new DateTime($('#min'), {
            format: 'yyyy-MM-dd'
        });

        maxDate = new DateTime($('#max'), {
            format: 'yyyy-MM-dd'
        });

        // DataTables initialisation
        var table = $('#myTable').DataTable();

        // Refilter the table
        $('#min, #max').on('change', function () {
            table.draw();
        });

    });
var minDate, maxDate;

    $.fn.DataTable.ext.search.push(
        function (settings, data, dataIndex) {
            var min = minDate.val();
            var max = maxDate.val();
            var date = new Date(data[3]);

            if (
                (min === null && max === null) ||
                (min === null && date <= max) ||
                (min <= date && max === null) ||
                (min <= date && date <= max)
            ) {
                return true;
            }
            return false;
        }
    );
</script>
</code>```

Body:
I used the resources from the jQuery DataTable website and also implemented the JQuery  dataTable plugin.

When using the Range Filter code throw jQuery error 'DateTime is not defined'

This is Datepicker

I use the HTML date picker

                    Minimum date:
                    <input type="date" id="min" name="min">

                    Maximum date:
                    <input type="date" id="max" name="max">

This is HTML

I binding the data in a table  using jQuery Ajax

                    S.No
                    State
                    District
                    Date
                    Submitted
                    Completed
                    Not Completed
                    Rejected

Here jQuery code that I have copied from Jquery Data Table website

>I have uses following plugin.


问:
Can't access <Select> on keyboard with screen reader
I have  html element (actually React styled component) that is used for changing interval on stock price chart.

```<code>          <Select
            aria-label="select interval"
            name="interval"
            id="line-chart-interval"
            defaultValue={chartInterval}
            onChange={({ target }) => {
              setChartInterval(target.value);
            }}
            on
          >
            <option value="1min">1 min</option>
            <option value="5min">5 min</option>
            <option value="15min">15 min</option>
            <option value="30min">30 min</option>
            <option value="1h">1 h</option>
            <option value="2h">2 h</option>
            <option value="4h">4 h</option>
            <option value="1day">1 day</option>
            <option value="1week">1 week</option>
            <option value="1month">1 month</option>
          </Select>
</code>```

I can normaly access the options when I click ENTER but when screen reader is on It is somehow blocked.

Screen reader extension that I use: https://chrome.google.com/webstore/detail/screen-reader/kgejglhpjiefppelpmljglcjbhoiplfn?hl=en

Body:
I have  html element (actually React styled component) that is used for changing interval on stock price chart.

          <Select
            aria-label="select interval"
            name="interval"
            id="line-chart-interval"
            defaultValue={chartInterval}
            onChange={({ target }) => {
              setChartInterval(target.value);
            }}
            on
          >
            <option value="1min">1 min</option>
            <option value="5min">5 min</option>
            <option value="15min">15 min</option>
            <option value="30min">30 min</option>
            <option value="1h">1 h</option>
            <option value="2h">2 h</option>
            <option value="4h">4 h</option>
            <option value="1day">1 day</option>
            <option value="1week">1 week</option>
            <option value="1month">1 month</option>
          </Select>

I can normaly access the options when I click ENTER but when screen reader is on It is somehow blocked.

Screen reader extension that I use: https://chrome.google.com/webstore/detail/screen-reader/kgejglhpjiefppelpmljglcjbhoiplfn?hl=en


问:
Template usage within class declaration
I have found some weird code and I do not exactly know what it does:
`

```<code>class TestBaseClass
{
public:
    TestBaseClass() = default;
    const uint32_t channel{3};
};

template<uint32_t NO_OF_CHANNELS, uint32_t NO_OF_SAMPLES = 1>
class TestClass : public TestBaseClass
{
};

template <uint32_t NO_OF_CHANNELS>
class TestClass<NO_OF_CHANNELS, 1> : public TestBaseClass
{
public:
    TestClass()
    {
    }

private:
    uint16_t test_array[NO_OF_CHANNELS] = {
        0,
    };
};

TestClass<2> obj;
</code>```

`
The interesting part here is class TestClass<NO_OF_CHANNELS, 1>. For this the previous class definition is needed, otherwise it will not compile.

I looked at it with cpp insights, but could not find any major difference to just not use the template after class TestClass...
What does this code do?

Title: Template usage within class declaration

Body:
I have found some weird code and I do not exactly know what it does:
`

class TestBaseClass
{
public:
    TestBaseClass() = default;
    const uint32_t channel{3};
};

template<uint32_t NO_OF_CHANNELS, uint32_t NO_OF_SAMPLES = 1>
class TestClass : public TestBaseClass
{
};

template <uint32_t NO_OF_CHANNELS>
class TestClass<NO_OF_CHANNELS, 1> : public TestBaseClass
{
public:
    TestClass()
    {
    }

private:
    uint16_t test_array[NO_OF_CHANNELS] = {
        0,
    };
};

TestClass<2> obj;

`
The interesting part here is class TestClass<NO_OF_CHANNELS, 1>. For this the previous class definition is needed, otherwise it will not compile.

I looked at it with cpp insights, but could not find any major difference to just not use the template after class TestClass...
What does this code do?


问:
Whenever we use seekbar on cardview how to stop seekbar to get into focus on when cardview have clickable true attribute
When click on cardview, seek bar is get into focus, when cardview have clickable "true" attribute.

<androidx.cardview.widget.CardView
    android:id="@+id/cardview"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_marginStart="12dp"
    android:layout_marginTop="4dp"
    android:layout_marginBottom="12dp"
    android:clickable="true"
    android:visibility="visible"
    app:cardBackgroundColor="@color/darkGray"
    tools:ignore="MissingConstraints">

    <SeekBar
        android:id="@+id/seekbar"
        android:layout_width="0dp"
        android:layout_height="20dp"
        android:max="360"
        android:progressBackgroundTint="@color/white"
        android:progressTint="@color/white" />

</androidx.cardview.widget.CardView>
```

When I use clickable true property in cardview , after click anywhere on cardview seekbar is get in foucus. But when I remove that property map drags and moves because cardview is on MapView.

Cardview is on Mapview so mapview should not be clicked when I click on cardview and seekbar should not get in focus.

Body:
When click on cardview, seek bar is get into focus, when cardview have clickable "true" attribute.

<androidx.cardview.widget.CardView
    android:id="@+id/cardview"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_marginStart="12dp"
    android:layout_marginTop="4dp"
    android:layout_marginBottom="12dp"
    android:clickable="true"
    android:visibility="visible"
    app:cardBackgroundColor="@color/darkGray"
    tools:ignore="MissingConstraints">

    <SeekBar
        android:id="@+id/seekbar"
        android:layout_width="0dp"
        android:layout_height="20dp"
        android:max="360"
        android:progressBackgroundTint="@color/white"
        android:progressTint="@color/white" />

</androidx.cardview.widget.CardView>

When I use clickable true property in cardview , after click anywhere on cardview seekbar is get in foucus. But when I remove that property map drags and moves because cardview is on MapView.

Cardview is on Mapview so mapview should not be clicked when I click on cardview and seekbar should not get in focus.


问:
Running a Video from a background python script
Hello i have this basic script
import vlc
import time

```<code>video_file = vlc.MediaPlayer("/home/bartender/Desktop/flare.mp4")
video_file.set_fullscreen(True)
video_file.play()
time.sleep(22)
video_file.stop()</kbd>
</code>```

when i test from the desktop terminal it launch VLC and play the video, but when i test via SSH and im connected via VNC to the desktop it wont show VLC on the screen, only in my SSH console show ramdon asics emulatin the video.

Is there a way i can tell VLC to play the video in the specific screen or desktop interface when i launch the script from remote SSH?

this is made in a raspberry pi 3B

i try creating a instanse with

```<code>--directx-device={,display,\\.\DISPLAY1}
</code>```

but get errors

Body:
Hello i have this basic script
import vlc
import time

video_file = vlc.MediaPlayer("/home/bartender/Desktop/flare.mp4")
video_file.set_fullscreen(True)
video_file.play()
time.sleep(22)
video_file.stop()

when i test from the desktop terminal it launch VLC and play the video, but when i test via SSH and im connected via VNC to the desktop it wont show VLC on the screen, only in my SSH console show ramdon asics emulatin the video.

Is there a way i can tell VLC to play the video in the specific screen or desktop interface when i launch the script from remote SSH?

this is made in a raspberry pi 3B

i try creating a instanse with

--directx-device={,display,\\.\DISPLAY1}

but get errors


问:
Google reCaptcha verification fails with invalid response
I am trying to verify the captcha using https://www.google.com/recaptcha/api/siteverify
But I am getting issue with validating it. I am passing secret and response in query string as well, and also in body, tried with both approach.

Please find the code below:

```<code>let post_data = {
        secret: process.env.RECAPTCHA_LEGACY_IOS,
        response: token
      };

 let data = await axios.post(`https://www.google.com/recaptcha/api/siteverify?`,post_data);
</code>```

Body:
I am trying to verify the captcha using https://www.google.com/recaptcha/api/siteverify
But I am getting issue with validating it. I am passing secret and response in query string as well, and also in body, tried with both approach.

Please find the code below:

let post_data = {
        secret: process.env.RECAPTCHA_LEGACY_IOS,
        response: token
      };

 let data = await axios.post(`https://www.google.com/recaptcha/api/siteverify?`,post_data);


问:
React useEffect runs twice (not on StrictMode)
I'm building an app that works with sockets, so running twice is a real issue. I'm having some "race" problems and some emits and up registering twice.

I've noticed that the useEffect in which I have the emit runs twice. I couldn't figure out why, so decided to simplify things an replace that page with a much simpler test page and see if the use effect still runs twice. It does, and I can't understand why.

I will list down all the relevant code.

index.tsx (no StrictMode)

```<code>const container = document.getElementById("root")!;
const root = createRoot(container);

root.render(
  <Provider store={store}>
    <App />
  </Provider>
);
</code>```

src/App.tsx

```<code>export function App() {

  return (
    <Wrapper data-test="app">
      <Route path="/" element={<HomePage />} />
      <Route path="/test" element={<TestPage />} />
      <Route path="/join-room" element={<JoinRoomPage />} />
      <Route path="/:id" element={<RoomPage />} />
      <Route path="/admin-add-answer" element={<AdminAddAnswerPage />} />
      <Route path="/admin-add-question" element={<AdminAddQuestionPage />} />
    </Wrapper>
  );
}
</code>```

src/wrapper

```<code>export const Wrapper: React.FunctionComponent<WrapperProps> = (
  props: WrapperProps
): React.ReactElement<WrapperProps> => {
  const [user, setUser] = React.useState<User>();
  const [room, setRoom] = React.useState<Room>();
  const [round, setRound] = React.useState<Round>();

  return (
    <React.StrictMode>
      <BrowserRouter data-test="wrapper-router">
        <Provider store={store} data-test="wrapper-store-provider">
          <SocketProvider>
            <UserContext.Provider value={{ user, setUser }}>
              <RoomContext.Provider value={{ room, setRoom }}>
                <RoundContext.Provider value={{ round, setRound }}>
                  <Box
                    sx={{
                      fontFamily: "main",
                      height: "100vh",
                      width: "100vw",
                      position: "relative",
                    }}
                  >
                    <Routes data-test="wrapper-routes">{props.children}</Routes>
                  </Box>
                </RoundContext.Provider>
              </RoomContext.Provider>
            </UserContext.Provider>
          </SocketProvider>
        </Provider>
      </BrowserRouter>
    </React.StrictMode>
  );
};
</code>```

So this is the basic setup. Now I have the home page where the user opens a new room (building a multiplayer online game). I send the request and make sure to only navigate to the test page after the user object is set in the context and also after getting the success confirmation (I'm using RTK Query).

Note: I split my components for container/presentational, where container holds any logic/state and presentational is purely, well, presentational component. So I'm not including the code for that.

src/pages/home

```<code>export const HomeContainer = () => {
  const navigate = useNavigate();

  const [createRoom, { isSuccess, data }] = useCreateRoomMutation();

  const socket = useContext(SocketContext);
  const { user, setUser } = useContext(UserContext);

  const [settings, setSettings] = useState({
    points_to_win: 10,
    max_time_per_round: 15,
  });

  useEffect(() => {
    if (isSuccess && user) {
      navigate(`/test`);
    }
  }, [isSuccess, data, navigate, user]);

  const handleSubmit = (settings: {
    points_to_win: number;
    max_time_per_round: number;
  }) => {
    try {
      const newUser = {
        _id: uuidv4(),
        is_tv: true,
        nickname: "main_projector",
      };
      sessionStorage.setItem("user", JSON.stringify(newUser));
      setUser(newUser);
      createRoom({ projector_id: socket.id, settings });
    } catch (e) {
      console.log("Failed to create a new room", e);
    }
  };

  return (
    <HomePresentational
      handleSubmit={handleSubmit}
      onClickJoin={() => navigate("/join-room")}
      settings={settings}
      setSettings={(s: { points_to_win: number; max_time_per_round: number }) =>
        setSettings(s)
      }
    />
  );
};
</code>```

And then finally

src/pages/test

```<code>export const TestContainer = () => {
  console.log("test container");

  useEffect(() => {
    console.log("test container useEffect");
  }, []);
  return <Box>This is test container</Box>;
};
</code>```

After opening a new room, and being automatically directed to the test page, this is what I get logged:

```<code>test-container.tsx:5 test container
test-container.tsx:8 test container useEffect
test-container.tsx:8 test container useEffect
</code>```

Body:
I'm building an app that works with sockets, so running twice is a real issue. I'm having some "race" problems and some emits and up registering twice.

I've noticed that the useEffect in which I have the emit runs twice. I couldn't figure out why, so decided to simplify things an replace that page with a much simpler test page and see if the use effect still runs twice. It does, and I can't understand why.

I will list down all the relevant code.

index.tsx (no StrictMode)

const container = document.getElementById("root")!;
const root = createRoot(container);

root.render(
  <Provider store={store}>
    <App />
  </Provider>
);

src/App.tsx

export function App() {

  return (
    <Wrapper data-test="app">
      <Route path="/" element={<HomePage />} />
      <Route path="/test" element={<TestPage />} />
      <Route path="/join-room" element={<JoinRoomPage />} />
      <Route path="/:id" element={<RoomPage />} />
      <Route path="/admin-add-answer" element={<AdminAddAnswerPage />} />
      <Route path="/admin-add-question" element={<AdminAddQuestionPage />} />
    </Wrapper>
  );
}

src/wrapper

export const Wrapper: React.FunctionComponent<WrapperProps> = (
  props: WrapperProps
): React.ReactElement<WrapperProps> => {
  const [user, setUser] = React.useState<User>();
  const [room, setRoom] = React.useState<Room>();
  const [round, setRound] = React.useState<Round>();

  return (
    <React.StrictMode>
      <BrowserRouter data-test="wrapper-router">
        <Provider store={store} data-test="wrapper-store-provider">
          <SocketProvider>
            <UserContext.Provider value={{ user, setUser }}>
              <RoomContext.Provider value={{ room, setRoom }}>
                <RoundContext.Provider value={{ round, setRound }}>
                  <Box
                    sx={{
                      fontFamily: "main",
                      height: "100vh",
                      width: "100vw",
                      position: "relative",
                    }}
                  >
                    <Routes data-test="wrapper-routes">{props.children}</Routes>
                  </Box>
                </RoundContext.Provider>
              </RoomContext.Provider>
            </UserContext.Provider>
          </SocketProvider>
        </Provider>
      </BrowserRouter>
    </React.StrictMode>
  );
};

So this is the basic setup. Now I have the home page where the user opens a new room (building a multiplayer online game). I send the request and make sure to only navigate to the test page after the user object is set in the context and also after getting the success confirmation (I'm using RTK Query).

Note: I split my components for container/presentational, where container holds any logic/state and presentational is purely, well, presentational component. So I'm not including the code for that.

src/pages/home

export const HomeContainer = () => {
  const navigate = useNavigate();

  const [createRoom, { isSuccess, data }] = useCreateRoomMutation();

  const socket = useContext(SocketContext);
  const { user, setUser } = useContext(UserContext);

  const [settings, setSettings] = useState({
    points_to_win: 10,
    max_time_per_round: 15,
  });

  useEffect(() => {
    if (isSuccess && user) {
      navigate(`/test`);
    }
  }, [isSuccess, data, navigate, user]);

  const handleSubmit = (settings: {
    points_to_win: number;
    max_time_per_round: number;
  }) => {
    try {
      const newUser = {
        _id: uuidv4(),
        is_tv: true,
        nickname: "main_projector",
      };
      sessionStorage.setItem("user", JSON.stringify(newUser));
      setUser(newUser);
      createRoom({ projector_id: socket.id, settings });
    } catch (e) {
      console.log("Failed to create a new room", e);
    }
  };

  return (
    <HomePresentational
      handleSubmit={handleSubmit}
      onClickJoin={() => navigate("/join-room")}
      settings={settings}
      setSettings={(s: { points_to_win: number; max_time_per_round: number }) =>
        setSettings(s)
      }
    />
  );
};

And then finally

src/pages/test

export const TestContainer = () => {
  console.log("test container");

  useEffect(() => {
    console.log("test container useEffect");
  }, []);
  return <Box>This is test container</Box>;
};

After opening a new room, and being automatically directed to the test page, this is what I get logged:

test-container.tsx:5 test container
test-container.tsx:8 test container useEffect
test-container.tsx:8 test container useEffect


问:
How can I set the Content Security Policy to make connection with web socket
main.dce055597222845a4f8f.js:1 Refused to connect to 'ws://URL:PORT/' because it violates the following Content Security Policy directive: "default-src 'self' blob:". Note that 'connect-src' was not explicitly set, so 'default-src' is used as a fallback.

when I am trying to connect Active Message Queue from web socket


问:
Flask html iframe embeding using nginx and gunicron not working
I have a application built with flask that I use to monitor changing data. The data itself is processed using another python application managed with cron. These python applications procuce html graphs using both plotly and mpld3. In my HTML code for the flask website, I use  to embed the html graphs into my webpage. This works perfectly fine when running flask in development mode ( $python run.py ) and I can see my graphs embeded.

I have set up nginx and gunicron with supervisor to have the flask application run a little more like a production set up. However using this, my iframe in my html code does not include my graphs that work perfectly fine in testing. The page is just blank.

After searching around for hours on the google machine, I have tried adding add_header X-Frame-Options "ALLOW-FROM http://localhost:$PORT"; in both the nginx.conf and conf.d/mywebsite.conf both to no avail.

my directory structure is as follows:

www/run.py

www/flask-app/templates/dynamic (this is where the html graphs live produced by the other python code)

www/flask-app/static (main.css and any static images)

www/flask-app/*.py (rest of my flask related python code)

Here is my iframe embed in my html:

```<code><div class="embed-responsive embed-responsive-16by9">
    <iframe class="embed-responsive-item" src="{{ url_for('htmlgraph1') }}" allowfullscreen></iframe>
</div>
</code>```

my relative nginx conf below:

```<code>server {
        listen SOMEPORT;
        server_name SOMEIPADDR;

        location /static {
                autoindex on;
                alias /home/user/www/flask-app/static;
        }
        location / {
                proxy_pass http://localhost:8000;
                #include /etc/nginx/proxy_params;
                #proxy_set_header Host $http_host;
                #proxy_set_header X-Real-IP $remote_addr;
                #proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                #proxy_set_header X-Forwarded-Proto $scheme;
                #proxy_redirect off;
        }
        location /templates/dynamic {
                add_header X-Frame-Options "ALLOW-FROM http://localhost:8000";
        }
}
</code>```

NOTE that i have also tried the specified port with localhost on X-Frame-Options that the nginx server is running on thinking it is calling itself, to no avail. the port 8000 is the gunicron port. So I am stumped. I dont know if this is a gunicron issue, flask issue or nginx conf issue or to be honest a me issue. If anyones got any ideas, It would be greatly appreciated, I spent some time scouring for this answer and all I could fine was adding x-frame-options.

Body:
I have a application built with flask that I use to monitor changing data. The data itself is processed using another python application managed with cron. These python applications procuce html graphs using both plotly and mpld3. In my HTML code for the flask website, I use  to embed the html graphs into my webpage. This works perfectly fine when running flask in development mode ( $python run.py ) and I can see my graphs embeded.

I have set up nginx and gunicron with supervisor to have the flask application run a little more like a production set up. However using this, my iframe in my html code does not include my graphs that work perfectly fine in testing. The page is just blank.

After searching around for hours on the google machine, I have tried adding add_header X-Frame-Options "ALLOW-FROM http://localhost:$PORT"; in both the nginx.conf and conf.d/mywebsite.conf both to no avail.

my directory structure is as follows:

www/run.py

www/flask-app/templates/dynamic (this is where the html graphs live produced by the other python code)

www/flask-app/static (main.css and any static images)

www/flask-app/*.py (rest of my flask related python code)

Here is my iframe embed in my html:

my relative nginx conf below:

server {
        listen SOMEPORT;
        server_name SOMEIPADDR;

        location /static {
                autoindex on;
                alias /home/user/www/flask-app/static;
        }
        location / {
                proxy_pass http://localhost:8000;
                #include /etc/nginx/proxy_params;
                #proxy_set_header Host $http_host;
                #proxy_set_header X-Real-IP $remote_addr;
                #proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                #proxy_set_header X-Forwarded-Proto $scheme;
                #proxy_redirect off;
        }
        location /templates/dynamic {
                add_header X-Frame-Options "ALLOW-FROM http://localhost:8000";
        }
}

NOTE that i have also tried the specified port with localhost on X-Frame-Options that the nginx server is running on thinking it is calling itself, to no avail. the port 8000 is the gunicron port. So I am stumped. I dont know if this is a gunicron issue, flask issue or nginx conf issue or to be honest a me issue. If anyones got any ideas, It would be greatly appreciated, I spent some time scouring for this answer and all I could fine was adding x-frame-options.


问:
The Page Title in Google search resoult didn't display correctly
enter image description here

I tried to use my cell phone to  search 'Toshiba lifestyle vietnam' in Google homepage but the title displayed 'Midea'. I am really confusing on this because that is no 'Midea' charater when I access the relevant link.
I think it related to SEO but I have no idea. please help.

what did the title 'Midea' come from and how to fixed it.


问:
How to calculate SSR in python
I've trained a linear regression model:

```<code>reg = linear_model.LinearRegression()
reg.fit(X, Y)
</code>```

And I want to calculate the three sum of squares SST, SSR and SSRES (a.k.a SSE).

I've calculated the SSE like this: (X is 4 predictive features)

```<code>y_pred = reg.predict(X)
df = pd.DataFrame({'Actual': Y, 'Predicted':y_pred})

print('SS_Res : '+ str(np.sum(np.square(df['Actual']-df['Predicted']))))
</code>```

How do I calculate the SSR (sum of squares regression)? it's supposed to be the sum of the differences between the predicted value by the model and the mean of the dependent variable, but in code how do I put this?

the SST would be easy as soon as I get the SSR, because SST = SSR + SSE

EDIT-

Something like this maybe? I'll be glad if anyone can just make sure that I'm right:

```<code>y_pred = reg.predict(X)
y_mean = np.mean(Y)
df = pd.DataFrame({'Actual': Y, 'Predicted':y_pred, 'mean':y_mean})

print('SS_Res : '+ str(np.sum(np.square(df['Actual']-df['Predicted']))))
print('SS_R : '+ str(np.sum(np.square(df['Predicted']-df['mean']))))
</code>```

Title: How to calculate SSR in python

Body:
I've trained a linear regression model:

reg = linear_model.LinearRegression()
reg.fit(X, Y)

And I want to calculate the three sum of squares SST, SSR and SSRES (a.k.a SSE).

I've calculated the SSE like this: (X is 4 predictive features)

y_pred = reg.predict(X)
df = pd.DataFrame({'Actual': Y, 'Predicted':y_pred})

print('SS_Res : '+ str(np.sum(np.square(df['Actual']-df['Predicted']))))

How do I calculate the SSR (sum of squares regression)? it's supposed to be the sum of the differences between the predicted value by the model and the mean of the dependent variable, but in code how do I put this?

the SST would be easy as soon as I get the SSR, because SST = SSR + SSE

EDIT-

Something like this maybe? I'll be glad if anyone can just make sure that I'm right:

y_pred = reg.predict(X)
y_mean = np.mean(Y)
df = pd.DataFrame({'Actual': Y, 'Predicted':y_pred, 'mean':y_mean})

print('SS_Res : '+ str(np.sum(np.square(df['Actual']-df['Predicted']))))
print('SS_R : '+ str(np.sum(np.square(df['Predicted']-df['mean']))))


问:
TypeError:preview.CaptureStream is not a function In Apple phones
I am developing one web application which need to access camera to record and submit it server.

It was working using below code in mac book chrome, but not in safari

```<code>
if (sUsrAg.indexOf('Firefox') > -1) {
  console.log('Firefox');
  document.getElementById("my_video").mozCaptureStream();
} else {
  console.log('Other');
  document.getElementById("my_video").captureStream();
}
</code>```

But after Dec 14 2022 update, even iphone chrome also using webKit it stopped working in all apple device.

Now I cannot proceed with apple phone neither in safari nor chrome. Its blocking my work.

I looking for solution.

Body:
I am developing one web application which need to access camera to record and submit it server.

It was working using below code in mac book chrome, but not in safari

if (sUsrAg.indexOf('Firefox') > -1) {
  console.log('Firefox');
  document.getElementById("my_video").mozCaptureStream();
} else {
  console.log('Other');
  document.getElementById("my_video").captureStream();
}

But after Dec 14 2022 update, even iphone chrome also using webKit it stopped working in all apple device.

Now I cannot proceed with apple phone neither in safari nor chrome. Its blocking my work.

I looking for solution.