问:
How to pass variable retrieved in database to base_url function? in codeigniter 4
How to pass variable retrieved in database to base_url function? this variable contains the image placement link where this image cannot appear if not using the base_url function. This is caused by the use of routing with segments.

The code :

```<code>var div = document.getElementById('sp-image1');
<?php $img = $user['link_panorama1'] ?>
var link = <?= base_url($img); ?>
var PSV = new PhotoSphereViewer({
    panorama: link,
    container: div,
    time_anim: 1000,
    anim_speed: '1.3rpm',
    navbar: true,
    navbar_style: {
        backgroundColor: 'rgba(58, 67, 77, 0.7)'
    },
    long_offset: 3.17 / 1800,
    lat_offset: 3.17 / 1440,
});
</code>```

Body:
How to pass variable retrieved in database to base_url function? this variable contains the image placement link where this image cannot appear if not using the base_url function. This is caused by the use of routing with segments.

The code :

var div = document.getElementById('sp-image1');
<?php $img = $user['link_panorama1'] ?>
var link = <?= base_url($img); ?>
var PSV = new PhotoSphereViewer({
    panorama: link,
    container: div,
    time_anim: 1000,
    anim_speed: '1.3rpm',
    navbar: true,
    navbar_style: {
        backgroundColor: 'rgba(58, 67, 77, 0.7)'
    },
    long_offset: 3.17 / 1800,
    lat_offset: 3.17 / 1440,
});


来源: stackexchange

问:
I want to return xml response in Laravel
In Laravel, I sent a response to front end and the body is xml form
But it arrives in a text form
Text formatted response

I set the content-type of response header 'text/xml'
And then echo SimpleXMLElement::asXML()
I want the response body to arrive as a xml form
Desired result

ContentLicense: CC BY-SA 4.0


问:
Testing Implementation Details (React Testing Library)
I have a project with a functional component which basically consist of a useEffect that makes calls to an API and depends on state changes. This is basically a behind-the-scenes file that does all the work while my other components actually hold the code for user interaction and DOM manipulation.
My question is: how do i test state changes within the behind-the-scenes file? I know react testing library goes against implementation details BUT it feels weird to just let them go untested. Is there any work around for this? Switching from enyzme to RTL.</p>


问:
Pytorch to Tensorflow initializer
i would like to change this Pytorch code to Tensorflow, but after many attempts, I did not manage. Could you help me please?

```<code>class MeanShift(nn.Conv2D):
    def __init__(self, rgb_range, rgb_mean, rgb_std, sign=-1):
        super(MeanShift, self).__init__(3, 3, kernel_size=1)
        std = paddle.to_tensor(rgb_std)
        self.weight.set_value(paddle.eye(3).reshape([3, 3, 1, 1]))
        self.weight.set_value(self.weight / (std.reshape([3, 1, 1, 1])))

        mean = paddle.to_tensor(rgb_mean)
        self.bias.set_value(sign * rgb_range * mean / std)

        self.weight.trainable = False
        self.bias.trainable = False
</code>```

I tried the following code: (where x is the output of the previous layer)

```<code>def MeanShift(rgb_range, rgb_mean, rgb_std, sign=-1):
    def _func(x):
        # Initilize weights
        weight_initer = tf.constant(shape=[1, 1, 3, 3], value=np.eye(3).reshape(1,  1, 3, 3), dtype=tf.float32)
        W = tf.Variable(weight_initer, name="Weight", dtype=tf.float32, shape=[1, 1, 3, 3])

        # Initilize bias
        bias_initer = tf.constant(shape=[3], value=[rgb_mean * rgb_range * sign], dtype=tf.float32)
        b = tf.Variable(bias_initer, name="Bias", dtype=tf.float32)

        x = Conv2D(3, 1, padding="same", kernel_initializer=keras.initializers.Constant(weight_initer), bias_initializer=keras.initializers.Constant(bias_initer))(x)
        return x

    return _func
</code>```

And I get the error:

TypeError: Eager execution of tf.constant with unsupported shape. > Tensor [[[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]]] (converted from [[[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]]]) has 9 elements, but got shape (1, 1, 1, 3) with > 3 elements).

Title: Pytorch to Tensorflow initializer

Body:
i would like to change this Pytorch code to Tensorflow, but after many attempts, I did not manage. Could you help me please?

class MeanShift(nn.Conv2D):
    def __init__(self, rgb_range, rgb_mean, rgb_std, sign=-1):
        super(MeanShift, self).__init__(3, 3, kernel_size=1)
        std = paddle.to_tensor(rgb_std)
        self.weight.set_value(paddle.eye(3).reshape([3, 3, 1, 1]))
        self.weight.set_value(self.weight / (std.reshape([3, 1, 1, 1])))

        mean = paddle.to_tensor(rgb_mean)
        self.bias.set_value(sign * rgb_range * mean / std)

        self.weight.trainable = False
        self.bias.trainable = False

I tried the following code: (where x is the output of the previous layer)

def MeanShift(rgb_range, rgb_mean, rgb_std, sign=-1):
    def _func(x):
        # Initilize weights
        weight_initer = tf.constant(shape=[1, 1, 3, 3], value=np.eye(3).reshape(1,  1, 3, 3), dtype=tf.float32)
        W = tf.Variable(weight_initer, name="Weight", dtype=tf.float32, shape=[1, 1, 3, 3])

        # Initilize bias
        bias_initer = tf.constant(shape=[3], value=[rgb_mean * rgb_range * sign], dtype=tf.float32)
        b = tf.Variable(bias_initer, name="Bias", dtype=tf.float32)

        x = Conv2D(3, 1, padding="same", kernel_initializer=keras.initializers.Constant(weight_initer), bias_initializer=keras.initializers.Constant(bias_initer))(x)
        return x

    return _func

And I get the error:

TypeError: Eager execution of tf.constant with unsupported shape. > Tensor [[[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]]] (converted from [[[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]]]) has 9 elements, but got shape (1, 1, 1, 3) with > 3 elements).


问:
How to add simple moving average to macd kind of indicator
I have a indicator same like MACD I want to add SMA to it. But when I try to embed SMA code in MACD code it is not showing as MACD is range bound where as SMA can go between 0 to 1000's. Here as a workaround I am doing this way,,,enabling MA and move to EXISTING PANE BELOW. Kind of stuff. Could any one help us in achieving this</p>
```<code>//
// @author LazyBear
//@version=2
//
// If you use this code in its original/modified form, do drop me a note.
//
study(title="WaveTrend [LazyBear]", shorttitle="BUCKET")
n1 = input(10, "Channel Length")
n2 = input(21, "Average Length")
obLevel1 = input(60, "Over Bought Level 1")
obLevel2 = input(53, "Over Bought Level 2")
obLevel3 = input(40, "Over Bought Level 3")
osLevel1 = input(-60, "Over Sold Level 1")
osLevel2 = input(-53, "Over Sold Level 2")
osLevel3 = input(-40, "Over Sold Level 3")

ap = hlc3
esa = ema(ap, n1)
d = ema(abs(ap - esa), n1)
ci = (ap - esa) / (0.015 * d)
tci = ema(ci, n2)

wt1 = tci
wt2 = sma(wt1,4)

plot(0, color=gray)
plot(obLevel1, color=red)
plot(osLevel1, color=green)
plot(obLevel2, color=red, style=3)
plot(obLevel3, color=red)
plot(osLevel2, color=green, style=3)
plot(osLevel3, color=green)

plot(wt1, color=green,title = 'GREEN')
plot(wt2, color=red, style=3)
plot(wt1-wt2, color=blue, style=area, transp=80)

// I am trying to embed sma but it is going in vain. Please help here

signal = sma(close, 9)
plot(signal, color=color.blue)

</code>```

Body:
I have a indicator same like MACD I want to add SMA to it. But when I try to embed SMA code in MACD code it is not showing as MACD is range bound where as SMA can go between 0 to 1000's. Here as a workaround I am doing this way,,,enabling MA and move to EXISTING PANE BELOW. Kind of stuff. Could any one help us in achieving this

//
// @author LazyBear
//@version=2
//
// If you use this code in its original/modified form, do drop me a note.
//
study(title="WaveTrend [LazyBear]", shorttitle="BUCKET")
n1 = input(10, "Channel Length")
n2 = input(21, "Average Length")
obLevel1 = input(60, "Over Bought Level 1")
obLevel2 = input(53, "Over Bought Level 2")
obLevel3 = input(40, "Over Bought Level 3")
osLevel1 = input(-60, "Over Sold Level 1")
osLevel2 = input(-53, "Over Sold Level 2")
osLevel3 = input(-40, "Over Sold Level 3")

ap = hlc3
esa = ema(ap, n1)
d = ema(abs(ap - esa), n1)
ci = (ap - esa) / (0.015 * d)
tci = ema(ci, n2)

wt1 = tci
wt2 = sma(wt1,4)

plot(0, color=gray)
plot(obLevel1, color=red)
plot(osLevel1, color=green)
plot(obLevel2, color=red, style=3)
plot(obLevel3, color=red)
plot(osLevel2, color=green, style=3)
plot(osLevel3, color=green)

plot(wt1, color=green,title = 'GREEN')
plot(wt2, color=red, style=3)
plot(wt1-wt2, color=blue, style=area, transp=80)

// I am trying to embed sma but it is going in vain. Please help here

signal = sma(close, 9)
plot(signal, color=color.blue)


问:
How to edit a function in your code in swift?
I'm fairly new to coding and trying to make a game where you attack an enemy with a shop/potions. I sell a potion for 50% more damage and i don't know how to edit the attack function while the code is ran. this is what i have

this is in class Character

```<code>func attack(enemy: Character, extra: Bool)
    {
        if extra == false
        {let dmgDealt = Int.random(in:0...30)
        updateHealth(amount: -dmgDealt, target: enemy)}
        else if extra == true
        {
        let dmgDealt = Int.random(in:15...45)
        updateHealth(amount: -dmgDealt, target: enemy)
        }

    }
</code>```

and

```<code>func shop(target: Character, currency: myCoins)
    {
        print("Hello! Welcome to the shop! Our stock includes: \nHarming Potion: You do 50% more damage. 200 Coins.\nHealth Potion: Gives a one-time       grant of 75 health. 150 Coins.\nTurtle Potion: You heal for more health but are more susceptible to attacks from the enemy. 300 coins.\n Damage Potion: Throw this at the enemy to deal 50 Damage! 200 coins.")
        let potionChoice = String(readLine()!)
        print("Good Choice!")
        switch potionChoice
        {
            case "harming":
            currency -= 200

            case "health":
            currency -= 150
            case "turtle":
            currency -= 300
            case "damage":
            currency -= 200
        }
     }
</code>```

i haven't done the others yet but i cant figure out how to do it

i tried making a bool where if it is true then deal extra damage but idk how that works

Body:
I'm fairly new to coding and trying to make a game where you attack an enemy with a shop/potions. I sell a potion for 50% more damage and i don't know how to edit the attack function while the code is ran. this is what i have

this is in class Character

func attack(enemy: Character, extra: Bool)
    {
        if extra == false
        {let dmgDealt = Int.random(in:0...30)
        updateHealth(amount: -dmgDealt, target: enemy)}
        else if extra == true
        {
        let dmgDealt = Int.random(in:15...45)
        updateHealth(amount: -dmgDealt, target: enemy)
        }

    }

and

func shop(target: Character, currency: myCoins)
    {
        print("Hello! Welcome to the shop! Our stock includes: \nHarming Potion: You do 50% more damage. 200 Coins.\nHealth Potion: Gives a one-time       grant of 75 health. 150 Coins.\nTurtle Potion: You heal for more health but are more susceptible to attacks from the enemy. 300 coins.\n Damage Potion: Throw this at the enemy to deal 50 Damage! 200 coins.")
        let potionChoice = String(readLine()!)
        print("Good Choice!")
        switch potionChoice
        {
            case "harming":
            currency -= 200

            case "health":
            currency -= 150
            case "turtle":
            currency -= 300
            case "damage":
            currency -= 200
        }
     }

i haven't done the others yet but i cant figure out how to do it

i tried making a bool where if it is true then deal extra damage but idk how that works


问:
SwiftUI - Making a String to conform to a View
I want to load a new view. If I phrase the code as:

```<code>NavigationLink("Target", destination: TargetView() )
</code>```

it works. But if I have a string var of food.target = "TargetView()"

```<code>NavigationLink("Target", destination: (food.target))
</code>```

It doesn't work as the string doesn't conform to a view. Can you metamorphose a string into a destination view for these purposes?

Body:
I want to load a new view. If I phrase the code as:

NavigationLink("Target", destination: TargetView() )

it works. But if I have a string var of food.target = "TargetView()"

NavigationLink("Target", destination: (food.target))

It doesn't work as the string doesn't conform to a view. Can you metamorphose a string into a destination view for these purposes?


问:
Running a Task triggered by Apple Watch
I have an App, that collects some data using URLSession Requests. These requests can't run in parallel, because I need the response of one request to trigger the next one. This whole process could take up to 30 seconds. On iPhone this works fine using Background Tasks...

Now I would like to trigger that using an Apple Watch, but as soon as the app goes to "Inactive" (display darkens) everything stops. When I keep the display on and so the app active, it runs fine...

What is the best way to solve this or is there even no way to solve this?

Title: Running a Task triggered by Apple Watch


问:
Create MySql docker image with preloaded data
I have a Dockerfile that uses the MySql 5.7 Docker image and copies a SQL script that I have to create the database schema on first startup.  I create a container with that image and use docker commit to create a new image from that container.  If I create a new container using that new image, then the schema is created again rather then restored from the previous commit.

My understanding is this is because, as per the docker commit documentation:

The commit operation will not include any data contained in volumes mounted inside the container.

And the SQL data is stored in a volume defined in the MySql Dockerfile, so that explains it.

However, the MySql docker documentation also states:

You can easily populate your mysql services by mounting a SQL dump into that directory and provide custom images with contributed data

I'm not sure how to "provide custom images with contributed data".  Any ideas?

Thank you


问:
J-link Failed to attach to CPU, connect under reset failed
Trying to connect to J-Link to my PCB and when trying to connect, this is message appears. Was able to connect and flash the drive, but after like 30 seconds, when trying to connect again, this error occurs. And since then, I am not able to connect properly

Here is the message that I received:

Connection Failure

So, I have two boards, the expected response came from that board.

Expected response:

Connection Success

There is a solution I found, but this does not make sense to me since I know little about the Segger J-Link connector's Pin diagram and the same J-Link setup worked on another board, so it does not make sense that the issue is with the J-Link connector.

Found solution (but does not help my case):
*The problem is the NRST of the MCU is not connected to the RESET pin of the J-Link connector.


问:
Error url, aplication.properties or pom.xml
I see that there are many questions like this, I came to show my solution, in my project that had this error.

```<code>***************************
APPLICATION FAILED TO START
***************************

Description:

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

Reason: Failed to determine a suitable driver class

Action:

Consider the following:
    If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
    If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).
</code>```

Because the application.properties was not in a source folder, with the name src/main/resource

Body:
I see that there are many questions like this, I came to show my solution, in my project that had this error.

***************************
APPLICATION FAILED TO START
***************************

Description:

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

Reason: Failed to determine a suitable driver class

Action:

Consider the following:
    If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
    If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).

Because the application.properties was not in a source folder, with the name src/main/resource


问:
Run exe with passing input file in Python
I wanted to analyse the test report from CANoe. I have an sample exe file from CANoe, where I can pass my vtestreport to the executable file. Once I pass the input file, I can get the verdicts from the report in Command Prompt. This is working in Command Prompt.

Output in Command Prompt

```<code>C:\Users\Public\Documents\Vector\Test Report Viewer 15 SP4\DataApiSample\DataApiSampleClient\bin\Debug>DataApiSampleClient.exe "C:\Thesis\Test_Report_Viewer\Test.vtestreport"
Test Report "MainPowerSupply" has Verdict Fail
Test Report "MainPowerSupply" contains one or more comments.
Test Report "MainPowerSupply" contains no reassessments.
Last change of annotations on 12/6/2022 2:08:45 PM +01:00.
Traverse tree looking for first failure in a Testcase in Test Report "MainPowerSupply" ...
First failed Testcase: 1. 28199_MainPowerSupply 12V/ 24V - Heating Operation voltage (Ventilation)
First failed activity is a Violation at simulation time 50484.736781
  Title: Measured ' = 0 (Standby), condition: 210 (Ventilation) <= value <= 210 (Ventilation)', Check type: Value Valid
</code>```

But I need to do the same in Python.

My executable file is in this folder:

C:\Users\Public\Documents\Vector\Test Report Viewer 15 SP4\DataApiSample\DataApiSampleClient\bin\Debug>DataApiSampleClient.exe

My input file is in this folder:

C:\Thesis\Test_Report_Viewer\Test.vtestreport

I tried passing the input file to the exe. But, I'm not able to get the output as it did in Command Prompt. Here is my code.

import subprocess
import os
inputFile = open('C:\Thesis\Test_Report_Viewer\Test.vtestreport','rb')
output = subprocess.check_output(["C:\Users\Public\Documents\Vector\Test Report Viewer 15 SP4\DataApiSample\DataApiSampleClient\bin\Debug>DataApiSampleClient.exe"], stdin = inputFile)
inpFile.close()
# outputStr = str(pieOut)[2:-5] #remove garbage
print(output)
```

When I run the above code, I'm encountered with an error.

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

I need get the output in Python as it did in Command Prompt.

Body:
I wanted to analyse the test report from CANoe. I have an sample exe file from CANoe, where I can pass my vtestreport to the executable file. Once I pass the input file, I can get the verdicts from the report in Command Prompt. This is working in Command Prompt.

Output in Command Prompt

C:\Users\Public\Documents\Vector\Test Report Viewer 15 SP4\DataApiSample\DataApiSampleClient\bin\Debug>DataApiSampleClient.exe "C:\Thesis\Test_Report_Viewer\Test.vtestreport"
Test Report "MainPowerSupply" has Verdict Fail
Test Report "MainPowerSupply" contains one or more comments.
Test Report "MainPowerSupply" contains no reassessments.
Last change of annotations on 12/6/2022 2:08:45 PM +01:00.
Traverse tree looking for first failure in a Testcase in Test Report "MainPowerSupply" ...
First failed Testcase: 1. 28199_MainPowerSupply 12V/ 24V - Heating Operation voltage (Ventilation)
First failed activity is a Violation at simulation time 50484.736781
  Title: Measured ' = 0 (Standby), condition: 210 (Ventilation) <= value <= 210 (Ventilation)', Check type: Value Valid

But I need to do the same in Python.

My executable file is in this folder:

C:\Users\Public\Documents\Vector\Test Report Viewer 15 SP4\DataApiSample\DataApiSampleClient\bin\Debug>DataApiSampleClient.exe

My input file is in this folder:

C:\Thesis\Test_Report_Viewer\Test.vtestreport

I tried passing the input file to the exe. But, I'm not able to get the output as it did in Command Prompt. Here is my code.

import subprocess
import os
inputFile = open('C:\Thesis\Test_Report_Viewer\Test.vtestreport','rb')
output = subprocess.check_output(["C:\Users\Public\Documents\Vector\Test Report Viewer 15 SP4\DataApiSample\DataApiSampleClient\bin\Debug>DataApiSampleClient.exe"], stdin = inputFile)
inpFile.close()
# outputStr = str(pieOut)[2:-5] #remove garbage
print(output)

When I run the above code, I'm encountered with an error.

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

I need get the output in Python as it did in Command Prompt.


问:
auto.arima mclapply Error in Forecast when trying to run parallel = TRUE
Sorry, this is the very first post on this site any help would be appreciated.
I am getting the following Error when running this code.

```<code>fit_arima_Sales<-auto.arima(
         ForecastTS, d=1, D=1, xreg = Forecastxreg, stepwise = FALSE, approximation = FALSE,
parallel = TRUE, num.cores = 14)
</code>```
```<code>Error in mclapply(X = to.check, FUN = par.all.arima, max.order = max.order,  :
  'mc.cores' > 1 is not supported on Windows
</code>```

So I have been running this code for about 2 years on my old computer. ( Windows 10 , i9 with 8 Core, 16 Logical Processors)

I recently upgraded to a desktop that has windows 10 i9 with 8 core and 24 logical processors. and I am getting that error. I am pretty sure I downloaded every package that I had on my old computer.
I for the life of me cannot figure out why I am getting this error.

if I set parallel = FALSE and delete the num.cores = 14. the function will run. But only on 1 core.

Body:
Sorry, this is the very first post on this site any help would be appreciated.
I am getting the following Error when running this code.

fit_arima_Sales<-auto.arima(
         ForecastTS, d=1, D=1, xreg = Forecastxreg, stepwise = FALSE, approximation = FALSE,
parallel = TRUE, num.cores = 14)

Error in mclapply(X = to.check, FUN = par.all.arima, max.order = max.order,  :
  'mc.cores' > 1 is not supported on Windows

So I have been running this code for about 2 years on my old computer. ( Windows 10 , i9 with 8 Core, 16 Logical Processors)

I recently upgraded to a desktop that has windows 10 i9 with 8 core and 24 logical processors. and I am getting that error. I am pretty sure I downloaded every package that I had on my old computer.
I for the life of me cannot figure out why I am getting this error.

if I set parallel = FALSE and delete the num.cores = 14. the function will run. But only on 1 core.


问:
How to call a function from a script in VUE
I am using SEON SDK in my vue project (https://cdn.getdeviceinf.com/js/v5/agent.js). This  i have called in the index.html file.

Now I want to use the functions of this script(like seon.config()...) on button click.
On button click I have tried calling a function which looks like this:

```<code> seon.config({
  host: "seondf.com",
  session_id: "123456abc",
  audio_fingerprint: true,
  canvas_fingerprint: true,
  webgl_fingerprint: true,
  onSuccess: function (message) {
    console.log("success", message);
  },
  onError: function (message) {
    console.log("error", message);
  },
});
</code>```

But this is giving an error that seon not found, I have also tried this.seon, but did not work.

Can someone please guide me how can solve this problem?

SEON documentation: https://docs.seon.io/api-reference#javascript-agent-v5

Body:
I am using SEON SDK in my vue project (https://cdn.getdeviceinf.com/js/v5/agent.js). This  i have called in the index.html file.

Now I want to use the functions of this script(like seon.config()...) on button click.
On button click I have tried calling a function which looks like this:

 seon.config({
  host: "seondf.com",
  session_id: "123456abc",
  audio_fingerprint: true,
  canvas_fingerprint: true,
  webgl_fingerprint: true,
  onSuccess: function (message) {
    console.log("success", message);
  },
  onError: function (message) {
    console.log("error", message);
  },
});

But this is giving an error that seon not found, I have also tried this.seon, but did not work.

Can someone please guide me how can solve this problem?

SEON documentation: https://docs.seon.io/api-reference#javascript-agent-v5


问:
how to create google map like layout notification in flutter
I have searched the internet to find a way to create a custom layout notification in a flutter.
I think there is the only way to do this is by going native.

If anyone have any useful resource to create such type of notification layout in a flutter that will be awesome, but any resource with native implementation will be also of help

here the notification layout -


问:
Does numpy have a function similar to pandas rank?
I have an array of 500 numbers and I'd like to calculate the percentile of each value:

```<code>import numpy as np
import pandas as pd

df = np.random.random(500)

desired_output = pd.DataFrame(df).rank(pct=True)
</code>```

Except without using pandas, since I have this in a long loop and it must be as fast as possible.

Body:
I have an array of 500 numbers and I'd like to calculate the percentile of each value:

import numpy as np
import pandas as pd

df = np.random.random(500)

desired_output = pd.DataFrame(df).rank(pct=True)

Except without using pandas, since I have this in a long loop and it must be as fast as possible.


问:
Why SignalR stateChanged callback function hitting multiple times
We have a signalR hub and JavaScript client. when state is changes from connected to disconnected or any state,then callback function hits more time,according to number of previous connections,
here is my code:</p>
```<code>        var promise = new Promise<SignalR.ConnectionStates>((resolve, reject) => {
            $.connection.hub.url =BASE_URL!;
            $.connection.hub.logging = process.env.REACT_APP_CONSOLE_LOGS == "true";
            $.connection.hub
                .start({
                    transport: ["webSockets", "longPolling"],
                    jsonp: true,
                    xdomain: true,
                    waitForPageLoad: false,
                } as any)
                .done(() => {
                    resolve($.connection.connectionState);
                    this.SubscribeBreakAlerts();
                })
                .fail(() => reject("Could not connect"));
        });

        await promise;

        $.connection.hub.stateChanged((e) => this.stateChanged(e));
        $.connection.hub.connectionSlow(() => this.connectionSlow());
</code>```
```<code>

i need to find the solution of this issue
</code>```

Body:
We have a signalR hub and JavaScript client. when state is changes from connected to disconnected or any state,then callback function hits more time,according to number of previous connections,
here is my code:

        var promise = new Promise<SignalR.ConnectionStates>((resolve, reject) => {
            $.connection.hub.url =BASE_URL!;
            $.connection.hub.logging = process.env.REACT_APP_CONSOLE_LOGS == "true";
            $.connection.hub
                .start({
                    transport: ["webSockets", "longPolling"],
                    jsonp: true,
                    xdomain: true,
                    waitForPageLoad: false,
                } as any)
                .done(() => {
                    resolve($.connection.connectionState);
                    this.SubscribeBreakAlerts();
                })
                .fail(() => reject("Could not connect"));
        });

        await promise;

        $.connection.hub.stateChanged((e) => this.stateChanged(e));
        $.connection.hub.connectionSlow(() => this.connectionSlow());

i need to find the solution of this issue


问:
Is there a way to use an image (png) of a QR code for logging into a desktop application using ADB?
I want to try to log into a desktop app, like Discord, using the QR-code log-in option.

The user would usually need to use his phone to scan the QR-code that is displayed on the desktop.

I want to try to automate this proceedure by saving this image in a png format, for example, and using it to log-in through the mobile Discord app using an ADB connection.

I'd like to do this without using the phone camera pointed to the screen, since this wouldn't be possible for my situation. I'd also prefer to avoid emulators.

I've been able to scan the QR-code using python. For example. I scanned the code below:

Log-in screen on the Discrod Desktop app

... and I got back the following link: https://discord.com/ra/fIUSUsnlPHThLkj5ghZtCATW5hxpc7qn00KYe1iJCNw

I know that this is a link that will probably be associated with some API communications in order to get me authenticated and allow the Desktop app to perform the log-in.

But I don't know how I could use this to communicate something with the app, such as "I have my side of the authentication and I need you to take this and allow me to log-in".

I've tried opening it with ADB as if it were a sort of browser link. It successfully opens the app and the camera screen for scanning the code opens quickly, but soon closes saying "Something went wrong when trying to scan."

Is something like this possible? Using an image of a QR-code or a link from this QR-code to "fool" the scanner?

This question is similar to "How can I pass a QR code image to a QR code scanning app, open in appium desktop?", which currently has no answer.


问:
Add Widgets from files automatically in pyQT
I would like to add widgets to my QT application App.py more or less dynamically by serving the widgets through a folder structure like so

```<code>App.py
plugins
-> plugin_A
   -> main.py
- plugins_B
   -> main.py
</code>```

Every main.py is representing a QT widget which is then shown in the main application.

```<code>+-------------------+
| PLUGIN A          |
| [Button]          |
| [Label]           |
+-------------------+
| PLUGIN B          |
| [Checkbox 1]      |
| [Checkbox 2]      |
| [Button]          |
+-------------------+
| ...               |
</code>```

I thought about simply scanning the plugins folder, creating and saving the Widgets in a list and adding them to a layout in a loop.

Upside I could easily propagate down common functionality to the constructor, like a COM port or something like that.

Downside The approach feels naiv and it would feel much better if the Widgets would register themselves actively somehow, but I don't know if and why this way is maybe preferable.

The whole situation seems to be so common, that I wonder if there is a general pattern to start with, maybe QT already has some functionality for such cases?

Body:
I would like to add widgets to my QT application App.py more or less dynamically by serving the widgets through a folder structure like so

App.py
plugins
-> plugin_A
   -> main.py
- plugins_B
   -> main.py

Every main.py is representing a QT widget which is then shown in the main application.

+-------------------+
| PLUGIN A          |
| [Button]          |
| [Label]           |
+-------------------+
| PLUGIN B          |
| [Checkbox 1]      |
| [Checkbox 2]      |
| [Button]          |
+-------------------+
| ...               |

I thought about simply scanning the plugins folder, creating and saving the Widgets in a list and adding them to a layout in a loop.

Upside I could easily propagate down common functionality to the constructor, like a COM port or something like that.

Downside The approach feels naiv and it would feel much better if the Widgets would register themselves actively somehow, but I don't know if and why this way is maybe preferable.

The whole situation seems to be so common, that I wonder if there is a general pattern to start with, maybe QT already has some functionality for such cases?


问:
Pointer metadata for sized, aligned storage
I am writing an allocator (for simplicity, let's assume nothing fails or throws):

struct AllocationHeader
{
  std::size_t size;
  std::size_t align;
};

void *aligned_allocate(std::size_t requested_size, std::size_t alignment)
{
  constexpr auto header_size = sizeof(AllocationHeader);
  const auto     total_size  = header_size + requested_size + alignment;
  auto           alloced_ptr = ::new unsigned char[total_size];

  ::new (alloced_ptr) AllocationHeader{requested_size, alignment};

  auto ret_ptr        = static_cast<void *>(alloced_ptr + header_size);
  auto remaining_size = total_size - header_size;
  return std::align(alignment, requested_size, ret_ptr, remaining_size);
}
```
<p>When I deallocate I want to recover the planted metadata</p>
<pre class="lang-cpp prettyprint-override"><code>void aligned_deallocate(void *ptr)
{
  constexpr auto header_size  = sizeof(AllocationHeader);
  // surely this is wrong
  auto           header_start = reinterpret_cast<unsigned char *>(ptr) - header_size;
  auto           header       = reinterpret_cast<AllocationHeader *>(header_start);

  do_something_with(header->size, header->align);
  // rest of deallocation...
}
</code>```

But surely the conversion back to AllocationHeader is wrong. The original align could in theory be anything (assuming power of 2) including > std::max_align_t.

So how do I portably recover how much std::align() shifted the pointer by? I'm limited to C++11.

EDIT:

I suppose I can do the shifting first:

void *aligned_allocate(std::size_t requested_size, std::size_t alignment)
{
  constexpr auto header_size    = sizeof(AllocationHeader);
  const auto     total_size     = header_size + requested_size + alignment;
  auto           alloced_ptr    = ::new unsigned char[total_size];
  auto           ret_ptr        = static_cast<void *>(alloced_ptr + header_size);
  auto           remaining_size = total_size - header_size;

  std::align(alignment, requested_size, ret_ptr, remaining_size);
  ::new (reinterpret_cast<unsigned char *>(ret_ptr) - header_size) AllocationHeader{requested_size, alignment};
  return ret_ptr;
}
```

But then AllocationHeader may constructed misaligned...

Body:
I am writing an allocator (for simplicity, let's assume nothing fails or throws):

struct AllocationHeader
{
  std::size_t size;
  std::size_t align;
};

void *aligned_allocate(std::size_t requested_size, std::size_t alignment)
{
  constexpr auto header_size = sizeof(AllocationHeader);
  const auto     total_size  = header_size + requested_size + alignment;
  auto           alloced_ptr = ::new unsigned char[total_size];

  ::new (alloced_ptr) AllocationHeader{requested_size, alignment};

  auto ret_ptr        = static_cast<void *>(alloced_ptr + header_size);
  auto remaining_size = total_size - header_size;
  return std::align(alignment, requested_size, ret_ptr, remaining_size);
}

When I deallocate I want to recover the planted metadata

void aligned_deallocate(void *ptr)
{
  constexpr auto header_size  = sizeof(AllocationHeader);
  // surely this is wrong
  auto           header_start = reinterpret_cast<unsigned char *>(ptr) - header_size;
  auto           header       = reinterpret_cast<AllocationHeader *>(header_start);

  do_something_with(header->size, header->align);
  // rest of deallocation...
}

But surely the conversion back to AllocationHeader is wrong. The original align could in theory be anything (assuming power of 2) including > std::max_align_t.

So how do I portably recover how much std::align() shifted the pointer by? I'm limited to C++11.

EDIT:

I suppose I can do the shifting first:

void *aligned_allocate(std::size_t requested_size, std::size_t alignment)
{
  constexpr auto header_size    = sizeof(AllocationHeader);
  const auto     total_size     = header_size + requested_size + alignment;
  auto           alloced_ptr    = ::new unsigned char[total_size];
  auto           ret_ptr        = static_cast<void *>(alloced_ptr + header_size);
  auto           remaining_size = total_size - header_size;

  std::align(alignment, requested_size, ret_ptr, remaining_size);
  ::new (reinterpret_cast<unsigned char *>(ret_ptr) - header_size) AllocationHeader{requested_size, alignment};
  return ret_ptr;
}

But then AllocationHeader may constructed misaligned...


问:
OSError: Unable to run gpg (gpg) - it may not be available
I am currently trying to decrypt a .gpg file in python using the package python-gnupg.

However, when I run my script:

```<code>file = input.xml.gpg

gpg = gnupg.GPG()

with open(file, 'rb') as f:
    status = gpg.decrypt_file(f, passphrase='***********', output='output.xml')

print(status.ok)
print(status.status)
print(status.stderr)
</code>```

I come across this error:

```<code>Traceback (most recent call last):
  File "C:\Users\D.Nahmias\Project\venv\lib\site-packages\gnupg.py", line 941, in __init__
    p = self._open_subprocess(['--version'])
  File "C:\Users\D.Nahmias\Project\venv\lib\site-packages\gnupg.py", line 1007, in _open_subprocess
    result = Popen(cmd, shell=False, stdin=PIPE, stdout=PIPE, stderr=PIPE, startupinfo=si, env=self.env)
  File "C:\Users\D.Nahmias\AppData\Local\Programs\Python\Python39\lib\subprocess.py", line 951, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "C:\Users\D.Nahmias\AppData\Local\Programs\Python\Python39\lib\subprocess.py", line 1420, in _execute_child
    hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2] The system cannot find the file specified

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\D.Nahmias\Project\decryption.py", line 35, in <module>
    main()
  File "C:\Users\D.Nahmias\Project\decryption.py", line 19, in main
    gpg = gnupg.GPG()
  File "C:\Users\D.Nahmias\Project\venv\lib\site-packages\gnupg.py", line 945, in __init__
    raise OSError(msg)
OSError: Unable to run gpg (gpg) - it may not be available.
</code>```

I tried multiple solution that I found on the web, I installed gpg4win and gnupg from the official website but it still didn't work.

If somebody could give me a hint, I would really appreciate it.

Thanks.

Body:
I am currently trying to decrypt a .gpg file in python using the package python-gnupg.

However, when I run my script:

file = input.xml.gpg

gpg = gnupg.GPG()

with open(file, 'rb') as f:
    status = gpg.decrypt_file(f, passphrase='***********', output='output.xml')

print(status.ok)
print(status.status)
print(status.stderr)

I come across this error:

Traceback (most recent call last):
  File "C:\Users\D.Nahmias\Project\venv\lib\site-packages\gnupg.py", line 941, in __init__
    p = self._open_subprocess(['--version'])
  File "C:\Users\D.Nahmias\Project\venv\lib\site-packages\gnupg.py", line 1007, in _open_subprocess
    result = Popen(cmd, shell=False, stdin=PIPE, stdout=PIPE, stderr=PIPE, startupinfo=si, env=self.env)
  File "C:\Users\D.Nahmias\AppData\Local\Programs\Python\Python39\lib\subprocess.py", line 951, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "C:\Users\D.Nahmias\AppData\Local\Programs\Python\Python39\lib\subprocess.py", line 1420, in _execute_child
    hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2] The system cannot find the file specified

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\D.Nahmias\Project\decryption.py", line 35, in <module>
    main()
  File "C:\Users\D.Nahmias\Project\decryption.py", line 19, in main
    gpg = gnupg.GPG()
  File "C:\Users\D.Nahmias\Project\venv\lib\site-packages\gnupg.py", line 945, in __init__
    raise OSError(msg)
OSError: Unable to run gpg (gpg) - it may not be available.

I tried multiple solution that I found on the web, I installed gpg4win and gnupg from the official website but it still didn't work.

If somebody could give me a hint, I would really appreciate it.

Thanks.


问:
cppcheck returns success in case of error
I have the following setting in my config for cppcheck to warn me if old API is used.

```<code><function name="strlen">
<warn severity="error"> DONT USE </warn>
<arg nr="1"/>
</function>
</code>```

When I run cppcheck, then I have 'error' in ourput as it should be

dummy.cc:3:5: error: DONT USE [strncpyCalled]
strncpy(dest, src, sizeof(dest));

But the result of the call is SUCCESS ( if I do 'echo $?').
In my CI the job is green as result.

What is the setting to make cppcheck to return 1 after the run in this case ?

Thanks!

Body:
I have the following setting in my config for cppcheck to warn me if old API is used.

<function name="strlen">
<warn severity="error"> DONT USE </warn>
<arg nr="1"/>
</function>

When I run cppcheck, then I have 'error' in ourput as it should be

dummy.cc:3:5: error: DONT USE [strncpyCalled]
strncpy(dest, src, sizeof(dest));

But the result of the call is SUCCESS ( if I do 'echo $?').
In my CI the job is green as result.

What is the setting to make cppcheck to return 1 after the run in this case ?

Thanks!


问:
Blazor MAUI app crashes on login page in Phone Device on TestFlight, but in the iPhone emulator it works
I have an application on Blazor Maui, version 7.0, it works fine on Android and Iphone emulators, it works fine on an Android device, but on an Iphone device it crashes after entering username and password in the Login page.

The error message that is generated when it crashes does not say what the problem is, please help me identify the error.

this is the crashlog.

Incident Identifier: 812F0B36-D84E-4116-BC13-8BF9D5DC0AC1
Hardware Model:      iPhone11,8
Process:             StrommarMember.Mobile7 [761]
Path:                /private/var/containers/Bundle/Application/60FBAE69-7982-4501-AB67-BB6819EC8990/StrommarMember.Mobile7.app/StrommarMember.Mobile7
Identifier:          com.strommar.strommarbase.test
Version:             1.0 (16)
AppStoreTools:       14C17
AppVariant:          1:iPhone11,8:16
Beta:                YES
Code Type:           ARM-64 (Native)
Role:                Foreground
Parent Process:      launchd [1]
Coalition:           com.strommar.strommarbase.test [505]

Date/Time:           2022-12-05 22:33:15.0430 -0400
Launch Time:         2022-12-05 22:32:49.3731 -0400
OS Version:          iPhone OS 16.1.1 (20B101)
Release Type:        User
Baseband Version:    5.01.01
Report Version:      104

Exception Type:  EXC_BAD_ACCESS (SIGSEGV)
Exception Subtype: KERN_PROTECTION_FAILURE at 0x000000016fa1bfb0
Exception Codes: 0x0000000000000002, 0x000000016fa1bfb0
VM Region Info: 0x16fa1bfb0 is in 0x16fa18000-0x16fa1c000;  bytes after start: 16304  bytes before end: 79
REGION TYPE                 START - END      [ VSIZE] PRT/MAX SHRMOD  REGION DETAIL
MALLOC_TINY              155b00000-155c00000 [ 1024K] rw-/rwx SM=PRV

GAP OF 0x19e18000 BYTES
--->  STACK GUARD              16fa18000-16fa1c000 [   16K] ---/rwx SM=NUL  ... for thread 0
Stack                    16fa1c000-16fb18000 [ 1008K] rw-/rwx SM=PRV  thread 0
Termination Reason: SIGNAL 11 Segmentation fault: 11
Terminating Process: exc handler [761]

Triggered by Thread:  0


问:
react-dev-tools Copy to Clipboard does not work
I am using react-dev-tools browser extension for Firefox. Version 4.27.0 of the extension, version 107 of Firefox.

When using the dev tools, you can view the state of each component. Right clicking on one of these entries gives the option to "Copy Value to Clipboard". Only problem is, nothing is ever actually copied to my clipboard. What am I doing wrong? Or is this feature just broken? OS is Windows 11, clipboard works fine otherwise.


问:
JPA update entire entity with all relations
I have the following Entities:

@Entity
public class MainEntity {

    @GeneratedValue(generator = "system-uuid")
    @GenericGenerator(name = "system-uuid", strategy = "org.hibernate.id.UUIDGenerator")
    @Id
    @Type(type="uuid-char")
    @Column(columnDefinition = "VARCHAR(255)", insertable = false, updatable = false, nullable = false)
    private UUID id;

    @OneToOne(cascade = CascadeType.ALL)
    private SubEntity sub;

    private String element;
}

@Entity
public class SubEntity{

    @GeneratedValue(generator = "system-uuid")
    @GenericGenerator(name = "system-uuid", strategy = "org.hibernate.id.UUIDGenerator")
    @Id
    @Type(type="uuid-char")
    @Column(columnDefinition = "VARCHAR(255)", insertable = false, updatable = false, nullable = false)
    private UUID id;

    private String element;
}
```
<p>These are coupled together using a <code>flyway</code> configuration</p>
<p>Bear in mind that this is only an example, I have multiple more Entities which are connected to MainEntity via <code>@OneToOne</code> or <code>@OneToMany</code>, all using <code>@CascadeType.ALL</code></p>
<p>And I want to update an existing entity - using the MainEntity ID and a new MainEntity Object. For this I have a JpaRepository with a custom @Query</p>
<pre class="lang-java prettyprint-override"><code>@Repository
public interface SalesOpportunityRepository extends JpaRepository<MainEntity, UUID> {

    @Modifying
    @Query("update MainEntity oldEntity set oldEntity = :updatedEntity where oldEntity.id = :id")
    void updateEntity(@Param("id") UUID id, @Param("updatedEntity") MainEntity updatedEntity);
}
</code>```

But running this, using either a h2 db locally, or a postgres db in test env. I get this error:

org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing:

I see many struggle with this, but everytime CascadeType.All is proposed, but as I already have it - this will not help.

Not sure if the update sql for updating the entire entity might be the problem her

Body:
I have the following Entities:

@Entity
public class MainEntity {

    @GeneratedValue(generator = "system-uuid")
    @GenericGenerator(name = "system-uuid", strategy = "org.hibernate.id.UUIDGenerator")
    @Id
    @Type(type="uuid-char")
    @Column(columnDefinition = "VARCHAR(255)", insertable = false, updatable = false, nullable = false)
    private UUID id;

    @OneToOne(cascade = CascadeType.ALL)
    private SubEntity sub;

    private String element;
}

@Entity
public class SubEntity{

    @GeneratedValue(generator = "system-uuid")
    @GenericGenerator(name = "system-uuid", strategy = "org.hibernate.id.UUIDGenerator")
    @Id
    @Type(type="uuid-char")
    @Column(columnDefinition = "VARCHAR(255)", insertable = false, updatable = false, nullable = false)
    private UUID id;

    private String element;
}

These are coupled together using a flyway configuration

Bear in mind that this is only an example, I have multiple more Entities which are connected to MainEntity via @OneToOne or @OneToMany, all using @CascadeType.ALL

And I want to update an existing entity - using the MainEntity ID and a new MainEntity Object. For this I have a JpaRepository with a custom @Query

@Repository
public interface SalesOpportunityRepository extends JpaRepository<MainEntity, UUID> {

    @Modifying
    @Query("update MainEntity oldEntity set oldEntity = :updatedEntity where oldEntity.id = :id")
    void updateEntity(@Param("id") UUID id, @Param("updatedEntity") MainEntity updatedEntity);
}

But running this, using either a h2 db locally, or a postgres db in test env. I get this error:

org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing:

I see many struggle with this, but everytime CascadeType.All is proposed, but as I already have it - this will not help.

Not sure if the update sql for updating the entire entity might be the problem her


问:
DownloadManger sends ACTION_DOWNLOAD_COMPLETE broadcast on no Wi-Fi
I have an android OS project and I am using the DownloadManger to perform some updates. Everything works fine with the download but I have an issue with the switching between Wi-Fi and mobile network.

The case is:
I am connected to Wi-Fi and start the download, 10 second later I cut the Wi-Fi so the phone switches instantly to mobile network. The problem is that the download stops and I have to restart it from the beginning.

From the logs I can see that the DownloadManger terminates everything but I can see why:

```<code>2022-12-06 11:07:07.847 2519-3467 DownloadManager com.android.providers.downloads W [18] Stop requested with status HTTP_DATA_ERROR: Failed reading response: java.net.SocketException: Software caused connection abort
2022-12-06 11:07:07.851 2519-3467 DownloadManager com.android.providers.downloads D [18] Finished with status CANNOT_RESUME
2022-12-06 11:07:07.947 2519-2519 DownloadManager com.android.providers.downloads D onStopJob id=18, reason=cancel() called by app, callingUid=10049 uid=10049 jobId=18
</code>```

Also, the reason the download cannot restart is that I receive a broadcast from the DownloadManager which states that the download finished but the status is failure so the code removes the temp file.

The broadcast I receive is DownloadManager.ACTION_DOWNLOAD_COMPLETE and I can't find any reason or documentation on why I receive this even the download failed.

I think the request should stay in PENDING or AWAITING_CONNECTION but non of this happens.

The config of the request:

```<code> Request request = new Request(Uri.parse(updateInfo.getDownloadUrl()));
    String userAgent = Utils.getUserAgentString(context);
    if (userAgent != null) {
        request.addRequestHeader("User-Agent", userAgent);
    }
    request.addRequestHeader("Cache-Control", "no-cache");

    request.setTitle(context.getString(R.string.app_name));
    request.setDestinationUri(Uri.parse(fullFilePath));
    request.setAllowedOverRoaming(true);
    request.setAllowedOverMetered(true);
    request.setVisibleInDownloadsUi(true);

 // Start the download
        final DownloadManager dm =
                (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);

        Utils.cancelNotification(context);

        long downloadId = dm.enqueue(request);
        updateInfo.setDownloadId(downloadId);
</code>```

Any suggestion will be quite helpful, thanks!

Body:
I have an android OS project and I am using the DownloadManger to perform some updates. Everything works fine with the download but I have an issue with the switching between Wi-Fi and mobile network.

The case is:
I am connected to Wi-Fi and start the download, 10 second later I cut the Wi-Fi so the phone switches instantly to mobile network. The problem is that the download stops and I have to restart it from the beginning.

From the logs I can see that the DownloadManger terminates everything but I can see why:

2022-12-06 11:07:07.847 2519-3467 DownloadManager com.android.providers.downloads W [18] Stop requested with status HTTP_DATA_ERROR: Failed reading response: java.net.SocketException: Software caused connection abort
2022-12-06 11:07:07.851 2519-3467 DownloadManager com.android.providers.downloads D [18] Finished with status CANNOT_RESUME
2022-12-06 11:07:07.947 2519-2519 DownloadManager com.android.providers.downloads D onStopJob id=18, reason=cancel() called by app, callingUid=10049 uid=10049 jobId=18

Also, the reason the download cannot restart is that I receive a broadcast from the DownloadManager which states that the download finished but the status is failure so the code removes the temp file.

The broadcast I receive is DownloadManager.ACTION_DOWNLOAD_COMPLETE and I can't find any reason or documentation on why I receive this even the download failed.

I think the request should stay in PENDING or AWAITING_CONNECTION but non of this happens.

The config of the request:

 Request request = new Request(Uri.parse(updateInfo.getDownloadUrl()));
    String userAgent = Utils.getUserAgentString(context);
    if (userAgent != null) {
        request.addRequestHeader("User-Agent", userAgent);
    }
    request.addRequestHeader("Cache-Control", "no-cache");

    request.setTitle(context.getString(R.string.app_name));
    request.setDestinationUri(Uri.parse(fullFilePath));
    request.setAllowedOverRoaming(true);
    request.setAllowedOverMetered(true);
    request.setVisibleInDownloadsUi(true);

 // Start the download
        final DownloadManager dm =
                (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);

        Utils.cancelNotification(context);

        long downloadId = dm.enqueue(request);
        updateInfo.setDownloadId(downloadId);

Any suggestion will be quite helpful, thanks!


问:
Is it possible to use KNN algorithm for bollean matrix?
I am trying to build a recommendation system just based on if the product was bought or not. I do not have the ratings data. So basically I have data about "who bought what" represented in bollean format - 1 meaning bought and 0 meaning not bought. Is it possible to use KNN with cosine similarity to cluster together similar users based on their purchase history. This will give me a list of products associated with every cluster and using that i can recommend individuals the products that they have not bought before. Basically using user based filtering

I am a newbie to recommendation systems. All the blogs and tutorials I came across are based on the collaborative filtering using the implicit and explicit data dervied from the item properties and user ratings. Though they were helpful in understanding how recommendation systems are build, it wasn't of much help for my specific use case. Any tutorial, code or blog will help.


问:
MapBox possible to override onDraw or Canvas of PolygonAnnotation?
I am using android MapBox and have multiple sorted polygon layers going. One of the polygons needs a fill-pattern which can be rotated.
I could not find a way to rotate the fill-pattern image (beside generating rotated bitmaps on the fly and updating the fill-pattern but that was awkward).

My latest approach was to override the dispatchDraw method of the MapView and draw the rotated pattern onto the mapview canvas:

```<code>    override fun dispatchDraw(canvas: Canvas) {
    super.dispatchDraw(canvas)

      canvas.save()
      drawPolygonPattern(canvas, getMapboxMap(), it.coordinates())
      canvas.restore()
    }
}
</code>```

Inside the canvas I map the polygon to pixel coordinates, create a polygon path, create the pattern and draw it into the path:

Works okayish. Major drawbacks are: dispatchDraw and map repaints are not synchronized so that the pattern "drag behind" when the user moves the map. The biggest issue is that canvas draw calls are always on-top of the map and thus hide elements of "lower" layers.

TLDR: Need rotatable fill-pattern within layer. Possibillity to overwrite canvas of polygon?

Thanks

Edit: There is an example of a custom layer ExampleCustomLayer within the Demo Project. It utilizes openGL so I guess there is an opening.

Body:
I am using android MapBox and have multiple sorted polygon layers going. One of the polygons needs a fill-pattern which can be rotated.
I could not find a way to rotate the fill-pattern image (beside generating rotated bitmaps on the fly and updating the fill-pattern but that was awkward).

My latest approach was to override the dispatchDraw method of the MapView and draw the rotated pattern onto the mapview canvas:

    override fun dispatchDraw(canvas: Canvas) {
    super.dispatchDraw(canvas)

      canvas.save()
      drawPolygonPattern(canvas, getMapboxMap(), it.coordinates())
      canvas.restore()
    }
}

Inside the canvas I map the polygon to pixel coordinates, create a polygon path, create the pattern and draw it into the path:

Works okayish. Major drawbacks are: dispatchDraw and map repaints are not synchronized so that the pattern "drag behind" when the user moves the map. The biggest issue is that canvas draw calls are always on-top of the map and thus hide elements of "lower" layers.

TLDR: Need rotatable fill-pattern within layer. Possibillity to overwrite canvas of polygon?

Thanks

Edit: There is an example of a custom layer ExampleCustomLayer within the Demo Project. It utilizes openGL so I guess there is an opening.


问:
get generation number in NEAT algorithm
I'm developing a game using PyGame and trying to show info on the screen while the AI is learning, one of the info I want to show is the generation number next to the genome number (i got the genome number already) but still I can't find a way to get the generation number.

I looked into the NEAT library files and found this function

```<code>def start_generation(self, generation):
        self.generation = generation
        print('\n ****** Running generation {0} ****** \n'.format(generation))
        self.generation_start_time = time.time()
</code>```

always have the output first when the algorithm starts, but i can't find a way to catch the generation number.

Also tried getting it from the console then format the string after the start_generation()  output is printed, but didn't work

Title: get generation number in NEAT algorithm

Body:
I'm developing a game using PyGame and trying to show info on the screen while the AI is learning, one of the info I want to show is the generation number next to the genome number (i got the genome number already) but still I can't find a way to get the generation number.

I looked into the NEAT library files and found this function

def start_generation(self, generation):
        self.generation = generation
        print('\n ****** Running generation {0} ****** \n'.format(generation))
        self.generation_start_time = time.time()

always have the output first when the algorithm starts, but i can't find a way to catch the generation number.

Also tried getting it from the console then format the string after the start_generation()  output is printed, but didn't work


问:
Combine fields with overlapping dates into one field (qlik sense)
Hello to the whole community!

There is a code that combine many field with overlapping dates into one field.

The code is below

```<code>Table_one:

load *

INLINE [

id_client | id_question| date_open | date_close

YZIYR00R | 14534534 | 05.10.2022 | 30.10.2022

YZIYR00R | 14786543 | 26.10.2022 | 27.10.2022

YZIYR00R | 87634957 | 27.10.2022 | 28.10.2022

YZIYR00R | 12398750 | 27.10.2022 | 28.10.2022

YZIYR00R | 57548555 | 27.10.2022 | 28.10.2022

YZIYR00R | 36485023 | 29.10.2022 | 30.10.2022

] (delimiter is '|');

Tmp:

LOAD *, if(previous(date_close) >= date_open and previous(id_client) = id_client,

peek(question_group), id_question) as question_group

Resident Table_one

ORDER BY id_client, date_open, date_close;

drop table Table_one;

SampleData:

LOAD id_client, question_group as id_question,

FirstSortedValue(date_open, recno()) as date_open,

FirstSortedValue(date_close, -recno()) as date_close

Resident Tmp

GROUP BY id_client, question_group;

drop table Tmp;
</code>```

So the last line doesn’t fall in the interval. The problem is that the code only checks the previous and next lines, if you add the filed (my last line in code), it will not fall into the interval because is compared to the previous one.
And I would like the intersecting intervals to join one, where the start date would be the minimum number of the intersecting group and the end date would be the maximum.
Than I wrote the next following code:

```<code>Table_one:

load *

INLINE [

id_client | id_question| date_open | date_close

YZIYR00R | 14534534 | 11.01.2022 | 11.01.2022

YZIYR00R | 14786543 | 11.01.2022 | 11.01.2022

YZIYR00R | 87634957 | 11.01.2022 | 11.01.2022

YZIYR00R | 12398750 | 11.01.2022 | 12.01.2022

YZIYR00R | 57548555 | 13.01.2022 | 13.01.2022

YZIYR00R | 36485023 | 13.01.2022 | 14.01.2022

YZIYR00R | 09748361 | 13.01.2022 | 13.01.2022

YZIYR00R | 56419453 | 13.01.2022 | 15.01.2022

] (delimiter is '|');

Tmp:

LOAD *, if(previous(date_close) >= date_open and previous(id_client) = id_client,

peek(question_group), id_question) as question_group

Resident Table_one

ORDER BY id_client,date_close,date_open;

drop table Table_one;

next:

load id_client, question_group as id_question, min(date_open) as date_open, max(date_close) as date_close

Resident Tmp

Group by id_client, question_group;

drop table Tmp;
</code>```

but with the data below it will no longer work correctly:

```<code>Table_one:

load *

INLINE [

id_client | id_question| date_open | date_close

YZIYR00R | 14534534 | 03.10.2022 | 03.10.2022

YZIYR00R | 14786543 | 04.10.2022 | 04.10.2022

YZIYR00R | 87634957 | 05.10.2022 | 02.12.2022

YZIYR00R | 12398750 | 06.10.2022 | 05.10.2022

YZIYR00R | 57548555 | 08.10.2022 | 06.10.2022

YZIYR00R | 36485023 | 17.10.2022 | 11.10.2022

YZIYR00R | 09748361 | 19.10.2022 | 18.10.2022

YZIYR00R | 56419453 | 20.10.2022 | 19.10.2022

YZIYR00R | 64324123 | 31.10.2022 | 26.10.2022

YZIYR00R | 53634322 | 01.11.2022 | 31.10.2022

YZIYR00R | 56787656 | 03.11.2022 | 03.11.2022

YZIYR00R | 78946487 | 09.11.2022 | 03.11.2022

YZIYR00R | 11111111 | 09.11.2022 | 09.11.2022

YZIYR00R | 98541484 | 10.11.2022 | 11.11.2022

YZIYR00R | 45487874 | 29.11.2022 | 23.11.2022

YZIYR00R | 26548459 | 02.12.2022 | 29.11.2022

] (delimiter is '|');
</code>```

Body:
Hello to the whole community!

There is a code that combine many field with overlapping dates into one field.

The code is below

Table_one:

load *

INLINE [

id_client | id_question| date_open | date_close

YZIYR00R | 14534534 | 05.10.2022 | 30.10.2022

YZIYR00R | 14786543 | 26.10.2022 | 27.10.2022

YZIYR00R | 87634957 | 27.10.2022 | 28.10.2022

YZIYR00R | 12398750 | 27.10.2022 | 28.10.2022

YZIYR00R | 57548555 | 27.10.2022 | 28.10.2022

YZIYR00R | 36485023 | 29.10.2022 | 30.10.2022

] (delimiter is '|');

Tmp:

LOAD *, if(previous(date_close) >= date_open and previous(id_client) = id_client,

peek(question_group), id_question) as question_group

Resident Table_one

ORDER BY id_client, date_open, date_close;

drop table Table_one;

SampleData:

LOAD id_client, question_group as id_question,

FirstSortedValue(date_open, recno()) as date_open,

FirstSortedValue(date_close, -recno()) as date_close

Resident Tmp

GROUP BY id_client, question_group;

drop table Tmp;

So the last line doesn’t fall in the interval. The problem is that the code only checks the previous and next lines, if you add the filed (my last line in code), it will not fall into the interval because is compared to the previous one.
And I would like the intersecting intervals to join one, where the start date would be the minimum number of the intersecting group and the end date would be the maximum.
Than I wrote the next following code:

Table_one:

load *

INLINE [

id_client | id_question| date_open | date_close

YZIYR00R | 14534534 | 11.01.2022 | 11.01.2022

YZIYR00R | 14786543 | 11.01.2022 | 11.01.2022

YZIYR00R | 87634957 | 11.01.2022 | 11.01.2022

YZIYR00R | 12398750 | 11.01.2022 | 12.01.2022

YZIYR00R | 57548555 | 13.01.2022 | 13.01.2022

YZIYR00R | 36485023 | 13.01.2022 | 14.01.2022

YZIYR00R | 09748361 | 13.01.2022 | 13.01.2022

YZIYR00R | 56419453 | 13.01.2022 | 15.01.2022

] (delimiter is '|');

Tmp:

LOAD *, if(previous(date_close) >= date_open and previous(id_client) = id_client,

peek(question_group), id_question) as question_group

Resident Table_one

ORDER BY id_client,date_close,date_open;

drop table Table_one;

next:

load id_client, question_group as id_question, min(date_open) as date_open, max(date_close) as date_close

Resident Tmp

Group by id_client, question_group;

drop table Tmp;

but with the data below it will no longer work correctly:

Table_one:

load *

INLINE [

id_client | id_question| date_open | date_close

YZIYR00R | 14534534 | 03.10.2022 | 03.10.2022

YZIYR00R | 14786543 | 04.10.2022 | 04.10.2022

YZIYR00R | 87634957 | 05.10.2022 | 02.12.2022

YZIYR00R | 12398750 | 06.10.2022 | 05.10.2022

YZIYR00R | 57548555 | 08.10.2022 | 06.10.2022

YZIYR00R | 36485023 | 17.10.2022 | 11.10.2022

YZIYR00R | 09748361 | 19.10.2022 | 18.10.2022

YZIYR00R | 56419453 | 20.10.2022 | 19.10.2022

YZIYR00R | 64324123 | 31.10.2022 | 26.10.2022

YZIYR00R | 53634322 | 01.11.2022 | 31.10.2022

YZIYR00R | 56787656 | 03.11.2022 | 03.11.2022

YZIYR00R | 78946487 | 09.11.2022 | 03.11.2022

YZIYR00R | 11111111 | 09.11.2022 | 09.11.2022

YZIYR00R | 98541484 | 10.11.2022 | 11.11.2022

YZIYR00R | 45487874 | 29.11.2022 | 23.11.2022

YZIYR00R | 26548459 | 02.12.2022 | 29.11.2022

] (delimiter is '|');


问:
how to convert binary voxelgrid (numpy 3d array) to open3d voxel format?
I have the 3d array np.zeros((24, 24, 100)), fill it with some '1's,
and can visualize it (in 3d) using pyplot:

open3d is more suitable to view this in 3d, and update it realtime, so I want to visualize this with open3d. But I don't understand how to visualize my binary voxelgrid using open3d.

This example is what I want (the voxel bunny); How can I convert my binary 3d array to the open3d voxelgrid format?

Converting to pointcloud is also an option, but there applies the same question.


问:
Nodejs: express does not keep req.query.id if we use listener
This is my code:

```<code>let observe = (obj: any, fn: any) => new Proxy(obj, {
    set: (obj, key, val) => {
      fn(obj)
      return obj[key] = val;
    }
});

router.use('/', async (req, res) => {
  const id = req.query.id

  arrs = observe([], (arr: any) => {
    console.log("current", id)
  });

  setTimeout(() => {
    arrs.push(id);
  }, 5000);
}
</code>```

Everything is ok, but console.log("current", id) does not work correct.

1- I open this url

```<code>http://localhost:9000/?id=a
</code>```

2- after one second, I open this url:

```<code>http://localhost:9000/?id=b
</code>```

3- after five seconds, id push to arrs and console.log("current", id) printed:

```<code>current b
current b
</code>```

why?!

The correct result most be:

```<code>current a
current b
</code>```

Body:
This is my code:

let observe = (obj: any, fn: any) => new Proxy(obj, {
    set: (obj, key, val) => {
      fn(obj)
      return obj[key] = val;
    }
});

router.use('/', async (req, res) => {
  const id = req.query.id

  arrs = observe([], (arr: any) => {
    console.log("current", id)
  });

  setTimeout(() => {
    arrs.push(id);
  }, 5000);
}

Everything is ok, but console.log("current", id) does not work correct.

1- I open this url

http://localhost:9000/?id=a

2- after one second, I open this url:

http://localhost:9000/?id=b

3- after five seconds, id push to arrs and console.log("current", id) printed:

current b
current b

why?!

The correct result most be:

current a
current b


问:
How to print to commandline in nmake?
Is there a command/function in nmake to print to the commandline similar to what is available in GNU make with $(info ...)?

I cannot use echo.

Title: How to print to commandline in nmake?


问:
matplotlib: group legend labels by category / multiple legend titles
Is it possible to group several legend entries into groups in pyplot? The following image visualizes what I try to achieve.

Of course, I could add the group name to each line label, but unfortunately, my group labels contain several words. I want to omit these duplicates to keep the legend clean.

Update:

After some tries, I got the following code:

```<code>import matplotlib.pyplot as plt

plt.plot([],[], linestyle="None", color="None", label="Group 1:") # linestyle=None --> nothing is shown, color="None" --> no impact on color cycle
plt.plot([],[], linestyle="None", color="None", label="Group 2:")
plt.plot([1,2],[4,5],linestyle="--",label="Line 1")
plt.plot([1,2],[4,6],label="Line 3")
plt.plot([1,2],[4,7],label="Line 2")
plt.plot([1,2],[4,8],label="Line 4")
leg = plt.legend(ncol=3)

for lH in leg.legendHandles:
  if lH.get_linestyle=="None":
     lH.set_visible=False # --> hide line marker from legend

plt.show()
</code>```

Result:

But now, there is some whitespace in front of the group labels. Adding handlelength=0 to plt.legend() doesn't work. It removes the empty space, but also the lines.

Body:
Is it possible to group several legend entries into groups in pyplot? The following image visualizes what I try to achieve.

Of course, I could add the group name to each line label, but unfortunately, my group labels contain several words. I want to omit these duplicates to keep the legend clean.

Update:

After some tries, I got the following code:

import matplotlib.pyplot as plt

plt.plot([],[], linestyle="None", color="None", label="Group 1:") # linestyle=None --> nothing is shown, color="None" --> no impact on color cycle
plt.plot([],[], linestyle="None", color="None", label="Group 2:")
plt.plot([1,2],[4,5],linestyle="--",label="Line 1")
plt.plot([1,2],[4,6],label="Line 3")
plt.plot([1,2],[4,7],label="Line 2")
plt.plot([1,2],[4,8],label="Line 4")
leg = plt.legend(ncol=3)

for lH in leg.legendHandles:
  if lH.get_linestyle=="None":
     lH.set_visible=False # --> hide line marker from legend

plt.show()

Result:

But now, there is some whitespace in front of the group labels. Adding handlelength=0 to plt.legend() doesn't work. It removes the empty space, but also the lines.


问:
how to import a tensorflow webmodel in python
I have a tensorflow "graph-model" consisting of a model.json and several .bin files. In javascript I am able to read those files using

```<code>const weights = browser.runtime.getURL("web_model/model.json");
tf.loadGraphModel(weights)
</code>```

However I would like to be able to use this model in python, in order to process the results better.

When I try to load the model in python with

```<code>new_model = keras.models.load_model('./web_model/model.json')
</code>```

I get the following error:

```<code>File "h5py/h5f.pyx", line 106, in h5py.h5f.open
OSError: Unable to open file (file signature not found)
</code>```

I don't understand, since the javascript code is able to run the model, I think python should be able to do the same as well. What am I doing wrong ?

Body:
I have a tensorflow "graph-model" consisting of a model.json and several .bin files. In javascript I am able to read those files using

const weights = browser.runtime.getURL("web_model/model.json");
tf.loadGraphModel(weights)

However I would like to be able to use this model in python, in order to process the results better.

When I try to load the model in python with

new_model = keras.models.load_model('./web_model/model.json')

I get the following error:

File "h5py/h5f.pyx", line 106, in h5py.h5f.open
OSError: Unable to open file (file signature not found)

I don't understand, since the javascript code is able to run the model, I think python should be able to do the same as well. What am I doing wrong ?


问:
How do I use different error messages using runtime_error? (C++)
I'm working in C++. I have a try...catch block, and the catch block catches runtime_error(error message). I want to do different things based on the different error messages. Here's some sample code:

```<code>#include <iostream>
#include <stdexcept>
#include <string>
using namespace std;

int main()
{
    string a = "hello";
    string b = "there";
    string c = "there";

    try{
        if(a == b){
            throw runtime_error("error 1");
        }
        if(b == c){
            throw runtime_error("error 2");
        }
    }
    catch(const runtime_error& error){
        cout << "error message: " << error.what();
        if(error.what() == "error 1"){
            // do thing a
        }
        else if(error.what() == "error 2"){
            // do thing b
        }
        else{
            // do thing c
        }
    }
}
</code>```

The type of error.what() is not a string, though, (apparently it's PKc, whatever that means), and so I was looking for a way to do different things based on the error message in error.what(). Help

I tried error.what() == "error 1", which did not return true when error.what() was "error 1" apparently. Not entirely sure why, not sure what's going on here. I expected it to return true, but it doesn't.

Body:
I'm working in C++. I have a try...catch block, and the catch block catches runtime_error(error message). I want to do different things based on the different error messages. Here's some sample code:

#include <iostream>
#include <stdexcept>
#include <string>
using namespace std;

int main()
{
    string a = "hello";
    string b = "there";
    string c = "there";

    try{
        if(a == b){
            throw runtime_error("error 1");
        }
        if(b == c){
            throw runtime_error("error 2");
        }
    }
    catch(const runtime_error& error){
        cout << "error message: " << error.what();
        if(error.what() == "error 1"){
            // do thing a
        }
        else if(error.what() == "error 2"){
            // do thing b
        }
        else{
            // do thing c
        }
    }
}

The type of error.what() is not a string, though, (apparently it's PKc, whatever that means), and so I was looking for a way to do different things based on the error message in error.what(). Help

I tried error.what() == "error 1", which did not return true when error.what() was "error 1" apparently. Not entirely sure why, not sure what's going on here. I expected it to return true, but it doesn't.


问:
Returning an array from a function in javascript (return value is not iterable error)
I'm trying to return 2 values from a function in javascript, to use them later. I found out this is possible using arrays.

So, I create an array with the values false(bool) and a string. When I use the console.log() command for my array inside the function right before it returns, I get exactly what I expect, an array with the two elements I put in it.

(2) [false, '']
0: false
1: ""
length: 2

[[Prototype]]: Array(0)

When I return the array, I try to put the values inside a new array (I will show code) and it throws this error:

```<code>Uncaught TypeError: validateUser is not a function or its return value is not iterable
    at HTMLFormElement.<anonymous> (login.js:8:31)
(anonymous) @ login.js:8

</code>```

Here is the code:
The function:

```<code>function validateUser(username, password){
    const loadRequest = new XMLHttpRequest();

    loadRequest.onload = function(){
        const info = new Array(2);
        if(this.responseText == ""){
            document.getElementById("login-error").innerHTML = "Incorrect username or password";
            info[0] = false;
            info[1] = "";
            console.log(info);
            return info;
        }
        info[0] = true;
        info[1] = this.responseText;
        return info;
    }
    loadRequest.open("GET", "validateUser.php?username="+username.value+"&password="+password.value, true);
    loadRequest.send();
}
</code>```

The data "transfer":

```<code>    const [valid, userInfo] = validateUser(username, password);

</code>```

I don't understand what the problem is. I searched for tutorials online, documentation, etc. I always see people using it like that with no problems. I searched it and all arrays are iterable so what gives. I tried changing the false into a string "false", thinking its inconsistent data types, but no. Still the same problem. I've thought of passing on a single string and using split, but that seems like such a bad solution. How would you guys solve this?

Body:
I'm trying to return 2 values from a function in javascript, to use them later. I found out this is possible using arrays.

So, I create an array with the values false(bool) and a string. When I use the console.log() command for my array inside the function right before it returns, I get exactly what I expect, an array with the two elements I put in it.

(2) [false, '']
0: false
1: ""
length: 2

[[Prototype]]: Array(0)

When I return the array, I try to put the values inside a new array (I will show code) and it throws this error:

Uncaught TypeError: validateUser is not a function or its return value is not iterable
    at HTMLFormElement.<anonymous> (login.js:8:31)
(anonymous) @ login.js:8

Here is the code:
The function:

function validateUser(username, password){
    const loadRequest = new XMLHttpRequest();

    loadRequest.onload = function(){
        const info = new Array(2);
        if(this.responseText == ""){
            document.getElementById("login-error").innerHTML = "Incorrect username or password";
            info[0] = false;
            info[1] = "";
            console.log(info);
            return info;
        }
        info[0] = true;
        info[1] = this.responseText;
        return info;
    }
    loadRequest.open("GET", "validateUser.php?username="+username.value+"&password="+password.value, true);
    loadRequest.send();
}

The data "transfer":

    const [valid, userInfo] = validateUser(username, password);

I don't understand what the problem is. I searched for tutorials online, documentation, etc. I always see people using it like that with no problems. I searched it and all arrays are iterable so what gives. I tried changing the false into a string "false", thinking its inconsistent data types, but no. Still the same problem. I've thought of passing on a single string and using split, but that seems like such a bad solution. How would you guys solve this?


问:
Create A URL Query String From cURL HTTP request
I want to transform a cURL HTTP request got from Datadog into a valid URL query string with the filters passed in as URL parameters. What would the resulting URL look like?</p>
```<code>curl -X GET "https://api.datadoghq.com/api/v2/rum/analytics/aggregate" -H "Content-Type: application/json" -H "DD-API-KEY: ${DD_API_KEY}" -H "DD-APPLICATION-KEY: ${DD_APP_KEY}" -d @- << EOF
{
  "compute": [
    {
      "metric": "count",
      "aggregation": "count",
      "type": "total"
    }
  ],
  "filter": {
    "query": "@type:session @application.id:e7fcce",
    "from": 1670252069041,
    "to": 1670338469041,
    "indexes": [
      "*"
    ]
  },
  "group_by": [
    {
      "facet": "@geo.country",
      "limit": 10,
      "sort": {
        "metric": "count",
        "aggregation": "count",
        "order": "desc",
        "type": "measure"
      }
    }
  ]
}
EOF
</code>```

Body:
I want to transform a cURL HTTP request got from Datadog into a valid URL query string with the filters passed in as URL parameters. What would the resulting URL look like?

curl -X GET "https://api.datadoghq.com/api/v2/rum/analytics/aggregate" -H "Content-Type: application/json" -H "DD-API-KEY: ${DD_API_KEY}" -H "DD-APPLICATION-KEY: ${DD_APP_KEY}" -d @- << EOF
{
  "compute": [
    {
      "metric": "count",
      "aggregation": "count",
      "type": "total"
    }
  ],
  "filter": {
    "query": "@type:session @application.id:e7fcce",
    "from": 1670252069041,
    "to": 1670338469041,
    "indexes": [
      "*"
    ]
  },
  "group_by": [
    {
      "facet": "@geo.country",
      "limit": 10,
      "sort": {
        "metric": "count",
        "aggregation": "count",
        "order": "desc",
        "type": "measure"
      }
    }
  ]
}
EOF


问:
.Net MAUI Shell navigating to the previous page is not working
I have a .Net MAUI app that uses Shell TabBar for navigating. Besides navigating to various pages, some tabs should just execute some code without showing any content. As TabBar does not provide such a functionality, I used OnAppearing() method of a dummy empty page, and after my code call

```<code>Shell.Current.GoToAsync("..");
</code>```

to return to the previous page. But for some reason, this does not work, and the empty page is still displayed. If I use some actual page, e.g.

```<code>Shell.Current.GoToAsync(nameof("SomePage"));
</code>```

the navigation works as expected, and SomePage is displayed.

Why doesn't ".." work for me?

Here is the code I use:

```<code>public class Page1 : ContentPage
{
    protected override void OnAppearing()
    {
        // Some code I need to execute

        Shell.Current.GoToAsync("..");
    }
}
</code>```

Body:
I have a .Net MAUI app that uses Shell TabBar for navigating. Besides navigating to various pages, some tabs should just execute some code without showing any content. As TabBar does not provide such a functionality, I used OnAppearing() method of a dummy empty page, and after my code call

Shell.Current.GoToAsync("..");

to return to the previous page. But for some reason, this does not work, and the empty page is still displayed. If I use some actual page, e.g.

Shell.Current.GoToAsync(nameof("SomePage"));

the navigation works as expected, and SomePage is displayed.

Why doesn't ".." work for me?

Here is the code I use:

public class Page1 : ContentPage
{
    protected override void OnAppearing()
    {
        // Some code I need to execute

        Shell.Current.GoToAsync("..");
    }
}


问:
Imported jar files (Swing Data Binding JXDatePicker Support ,jcalendar) not working. --> imported palletes look broken [Gradle Build] Netbeans IDE
Please help me with this issue. I need a date picker for my project so I'd tried to import Jcalendar but after import the jar file.It's seems to be broken in pallete manager.
Please look into the screenshots below,
pls look into the screenshot those icons with question mark are not working.

#Screenshot 2

Properties for datepickerformatter

I got this Exception ERR :

java.lang.UnsupportedOperationException: Project in C:\Users\Akilan P\Documents\NetBeansProjects\BillingManagementSystem\app of class org.netbeans.modules.gradle.NbGradleProjectImpl has neither a ProjectClassPathModifierImplementation nor a ProjectClassPathExtender in its lookup


问:
Flask dropdown options from CSV dataframe row
I need to create a dropdown menu with some options for user to choose that should come from randomly selected rows from the cvs file.

The user is supposed to choose one of those random options and then the option selected should be send to flask app.py to the neural network model to make a predictions based on the data in the selected row. The row is 47 columns long so I was not able to figure out how to better handle this.

I am stuck at the moment on how to get rows from csv file (there are several columns in the row) and pass it to the dropdown menu as options to choose.

Now I have the following code for Flask and HTML:

Flask part

```<code>
model = tf.keras.models.load_model(r"NNmodel_mlp")

# load dataset for random choice

df = pd.read_csv("test_ff.csv")
df.set_index('id', inplace=True)

# functions:

def get_prediction(protein):
    prediction = model.predict(protein)

def random_proteins(df = df):
    range_list = rand.sample(range(0, 1000), 3)
    protein_list = []
    i, j, k = range_list
    protein_option1 = df.iloc[i, :]
    protein_option2 = df.iloc[j, :]
    protein_option3 = df.iloc[k, :]
    protein_list.extend([protein_option1, protein_option2, protein_option3])
    return protein_list

@app.route('/', methods=['POST', 'GET'])

def get_input():
    if request.method =='GET':
        return render_template('main.html')
    if request.method=='POST':
        proteins_list = random_proteins()
        protein = request.form['protein']
        message = get_prediction(protein)
        return render_template('main.html', proteins_list_app=proteins_list, message = message)

if __name__ == '__main__':
    app.run(debug=True)
</code>```

and HTML part:

```<code>
    <form action="main.html" method="POST">
        <label for="protein">Choose one</label>
        <br>
        <br>
        <span><select type="select" name="protein" method="GET" action="/" placeholder="choose sequence of aminoacids">
            {% for protein in protein_list_app %}
            <option value="{{protein}}">{{protein}}</option>
            {% endfor %}
        </span>
        </select>
    </form>
</code>```

Would very appreciate your help/advice on how to move forward.

Body:
I need to create a dropdown menu with some options for user to choose that should come from randomly selected rows from the cvs file.

The user is supposed to choose one of those random options and then the option selected should be send to flask app.py to the neural network model to make a predictions based on the data in the selected row. The row is 47 columns long so I was not able to figure out how to better handle this.

I am stuck at the moment on how to get rows from csv file (there are several columns in the row) and pass it to the dropdown menu as options to choose.

Now I have the following code for Flask and HTML:

Flask part

model = tf.keras.models.load_model(r"NNmodel_mlp")

# load dataset for random choice

df = pd.read_csv("test_ff.csv")
df.set_index('id', inplace=True)

# functions:

def get_prediction(protein):
    prediction = model.predict(protein)

def random_proteins(df = df):
    range_list = rand.sample(range(0, 1000), 3)
    protein_list = []
    i, j, k = range_list
    protein_option1 = df.iloc[i, :]
    protein_option2 = df.iloc[j, :]
    protein_option3 = df.iloc[k, :]
    protein_list.extend([protein_option1, protein_option2, protein_option3])
    return protein_list

@app.route('/', methods=['POST', 'GET'])

def get_input():
    if request.method =='GET':
        return render_template('main.html')
    if request.method=='POST':
        proteins_list = random_proteins()
        protein = request.form['protein']
        message = get_prediction(protein)
        return render_template('main.html', proteins_list_app=proteins_list, message = message)

if __name__ == '__main__':
    app.run(debug=True)

and HTML part:

    <form action="main.html" method="POST">
        Choose one

        <select type="select" name="protein" method="GET" action="/" placeholder="choose sequence of aminoacids">
            {% for protein in protein_list_app %}
            <option value="{{protein}}">{{protein}}</option>
            {% endfor %}

        </select>
    </form>

Would very appreciate your help/advice on how to move forward.


问:
Autosize and scale WrapPannel
I would like to have a wrap panel (or similar) with a bunch of names scale the text size to

fill all available space (from left to right and top to bottom) the best it can

when i change the size of the window the font size or whatever should increase/decrease, so it always fills the page

the names should all have the same font size

Does anyone have any idea?

I tryed the following but i would manually have to set the size of the wrap pannel so it fits all the text.

<Viewbox x:Name="scaler" Stretch="UniformToFill" Width="{Binding ActualWidth, ElementName=window}">
    <WrapPanel HorizontalAlignment="Left"  x:Name="flpAnwesend" Orientation="Vertical" Height="309" Width="{Binding ActualWidth, ElementName=window}">

    </WrapPanel>
</Viewbox>
```

EDIT:
Here is what it looks like with the first comment.
image

And this is what I would like it to look like. (This was done by setting the size of the warplane but I haven’t figured out a good way to do this programmatically)
image

Title: Autosize and scale WrapPannel

Body:
I would like to have a wrap panel (or similar) with a bunch of names scale the text size to

fill all available space (from left to right and top to bottom) the best it can

when i change the size of the window the font size or whatever should increase/decrease, so it always fills the page

the names should all have the same font size

Does anyone have any idea?

I tryed the following but i would manually have to set the size of the wrap pannel so it fits all the text.

<Viewbox x:Name="scaler" Stretch="UniformToFill" Width="{Binding ActualWidth, ElementName=window}">
    <WrapPanel HorizontalAlignment="Left"  x:Name="flpAnwesend" Orientation="Vertical" Height="309" Width="{Binding ActualWidth, ElementName=window}">

    </WrapPanel>
</Viewbox>

EDIT:
Here is what it looks like with the first comment.
image

And this is what I would like it to look like. (This was done by setting the size of the warplane but I haven’t figured out a good way to do this programmatically)
image


问:
Create a new repository in OpenCmis In Memory
How can I create a new repository in Apache Chemistry Open CMIS Server In Memory ?
First one is already defined as below :
InMemoryServer.RepositoryId=A1

I'd like to create a second repo. Can't find the info online

Thanks!

I tried to add a new row as below but this is not working, it will take only the second row into account

In Memory Settings

InMemoryServer.RepositoryId=A1

InMemoryServer.RepositoryId=A2

Settings


问:
Top Left Highlight Ribbon Positioning
I'm trying to create a high-light ribbon that appears diagonally across the top-left of my grid.

I just can't seem to figure out the best way to get the layout - especially seeing our application can be resized.

As an example of what I'm trying to achive, see the top-left red highlight with "Best Choice" written in it: http://www.photoshopstar.com/wp-content/uploads/2009/11/stylish_advert_21.jpg

How can I get this sort of layout in WPF?

ContentLicense: CC BY-SA 3.0

Title: Top Left Highlight Ribbon Positioning


问:
Unable to resolve signature of class decorator when called as an expression when using class and method decorators
i have user class and im attempting to declare a class and method decorator. However im getting the following errors:

error TS1238: Unable to resolve signature of class decorator when
called as an expression.   This expression is not callable.
Type 'void' has no call signatures.

1 @OpenAPIPaths({ path: "Users" })

error TS1241: Unable to resolve signature of method decorator when
called as an expression.   This expression is not callable.
Type 'void' has no call signatures.

7     @OpenAPIFunction({ Request: {}, Response: {} })

user.controller.ts

```<code>@OpenAPIPaths({ path: "Users" })
export class UserController {
    constructor() {
        console.log("init");
    }

    @OpenAPIFunction({ Request: {}, Response: {} })
    getUser(id: string) {
        return id;
    }
}

function OpenAPIPaths(other: any): void {
    console.log("class", other);
}

function OpenAPIFunction(here: any): void {
    console.log("function", here);
}
</code>```

tsconfig.js

```<code>{
    "extends": "./tsconfig.paths.json",
    "compilerOptions": {
        "lib": ["ESNext"],
        "moduleResolution": "node",
        "noUnusedLocals": false,
        "noUnusedParameters": false,
        "removeComments": true,
        "sourceMap": true,
        "target": "ES2020",
        "outDir": "dist",
        "esModuleInterop": true,
        "strictNullChecks": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true
    },
    "include": ["./**/*.ts"],
    "exclude": ["node_modules/**/*", ".serverless/**/*", ".webpack/**/*", "_warmup/**/*", ".vscode/**/*"],
    "ts-node": {
        "require": ["tsconfig-paths/register"]
    }
}
</code>```

node:16
typescript: 4.9.3

Body:
i have user class and im attempting to declare a class and method decorator. However im getting the following errors:

error TS1238: Unable to resolve signature of class decorator when
called as an expression.   This expression is not callable.
Type 'void' has no call signatures.

1 @OpenAPIPaths({ path: "Users" })

error TS1241: Unable to resolve signature of method decorator when
called as an expression.   This expression is not callable.
Type 'void' has no call signatures.

7     @OpenAPIFunction({ Request: {}, Response: {} })

user.controller.ts

@OpenAPIPaths({ path: "Users" })
export class UserController {
    constructor() {
        console.log("init");
    }

    @OpenAPIFunction({ Request: {}, Response: {} })
    getUser(id: string) {
        return id;
    }
}

function OpenAPIPaths(other: any): void {
    console.log("class", other);
}

function OpenAPIFunction(here: any): void {
    console.log("function", here);
}

tsconfig.js

{
    "extends": "./tsconfig.paths.json",
    "compilerOptions": {
        "lib": ["ESNext"],
        "moduleResolution": "node",
        "noUnusedLocals": false,
        "noUnusedParameters": false,
        "removeComments": true,
        "sourceMap": true,
        "target": "ES2020",
        "outDir": "dist",
        "esModuleInterop": true,
        "strictNullChecks": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true
    },
    "include": ["./**/*.ts"],
    "exclude": ["node_modules/**/*", ".serverless/**/*", ".webpack/**/*", "_warmup/**/*", ".vscode/**/*"],
    "ts-node": {
        "require": ["tsconfig-paths/register"]
    }
}

node:16
typescript: 4.9.3


问:
The default component is not shown Angular
I need your help. I'm trying to write a small authorization, and I started by setting a default component to be shown first. To do this, I created a separate AppRoutingModule and installed the components in it, and then inserted it into the main AppMoudle. I have no errors, but none of the components show up. What is my mistake. Thank you very much

AppRoutingModule

```<code>import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import {LoginComponent} from "./components/login/login.component";
import {MainContentComponent} from "./components/main-content/main-content.component";
import {AuthGuard} from "./guards/auth.guard";

const routes: Routes = [
  {path: '', redirectTo: 'login', pathMatch: "full"},
  {path: 'login', component: LoginComponent},
  {path: 'content', component: MainContentComponent, canActivate: [AuthGuard]},
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
</code>```

AppModule

```<code>import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';
import { LoginComponent } from './components/login/login.component';
import { MainContentComponent } from './components/main-content/main-content.component';
import {HttpClientModule} from "@angular/common/http";
import {AppRoutingModule} from "./app-routing.module";
import {ReactiveFormsModule} from "@angular/forms";

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    MainContentComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    AppRoutingModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

AppComponentHtml

```<code><div class="all_content">
  <router-outlet></router-outlet>
</div>
</code>```

Body:
I need your help. I'm trying to write a small authorization, and I started by setting a default component to be shown first. To do this, I created a separate AppRoutingModule and installed the components in it, and then inserted it into the main AppMoudle. I have no errors, but none of the components show up. What is my mistake. Thank you very much

AppRoutingModule

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import {LoginComponent} from "./components/login/login.component";
import {MainContentComponent} from "./components/main-content/main-content.component";
import {AuthGuard} from "./guards/auth.guard";

const routes: Routes = [
  {path: '', redirectTo: 'login', pathMatch: "full"},
  {path: 'login', component: LoginComponent},
  {path: 'content', component: MainContentComponent, canActivate: [AuthGuard]},
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

AppModule

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';
import { LoginComponent } from './components/login/login.component';
import { MainContentComponent } from './components/main-content/main-content.component';
import {HttpClientModule} from "@angular/common/http";
import {AppRoutingModule} from "./app-routing.module";
import {ReactiveFormsModule} from "@angular/forms";

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    MainContentComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    AppRoutingModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

AppComponentHtml

  <router-outlet></router-outlet>