问:
Dask application has trouble scaling up, any suggestions?
I have a fairly straightforward Dask application (filter a large wavefield) that I am having trouble scaling up. My job function is:

```<code>def filter_wavefield(pos, butter_filter,wave):
    filtered = signal.sosfilt(butter_filter,wave[pos,:]).astype("float32")
    return filtered
</code>```

After loading the data to dask arrays (no problem scaling up here), I have tried three approaches to submit jobs:

Pre-scatter the data and pass the futures to the last argument of the job function

```<code>wave_future = client.scatter(wave_on_slice_channel,broadcast=True)

# I choose to parallelize over the coordinates, so I make several bags of those
coord_list = [i for i in range(nelem*ngll)]
coord_bag = db.from_sequence(coord_list,npartitions=500)
# Submit the tasks
filtered = coord_bag.map(filter_wavefield, butter_filter,wave_future)
filtered_waves = filtered.compute()

</code>```

This approach works very well for data size about up to 0.5 TiB. However, now my data size is 1.35 TiB, and even this ~3 fold increase breaks things down completely. When I run filtered_waves = filtered.compute() with the current dataset, everything freezes (i.e. dashboard useless) and the kernel simply dies.

Persist the large data

I then did some research on how people deal with > 1TiB data with dask and come across this page. In the video, the dask expert persist the data right away. I tried this:

```<code>wave = wave_on_slice_channel.persist()
wait(wave)

# Same stuff about coordinates
coord_list = [i for i in range(nelem*ngll)]
coord_bag = db.from_sequence(coord_list,npartitions=500)
# Submit the tasks
filtered = coord_bag.map(filter_wavefield, butter_filter,wave)
filtered_waves = filtered.compute()

</code>```

Note here, the last argument passed in to the job function is no longer a future, but I suppose it's actual data already persisted to the memory.

I am using 500 cores with a total of > 3.5 TiB memory, so after persisting, my dashboard looks like the following

This is all great, and I have my 1.35TiB in the distributed memory. However, everything still breaks once filtered_waves = filtered.compute() is called. The symptom is the same as before. Everything freezes and becomes unresponsive. Shortly after the python kernel dies.

Using for loop + submit rather than dask bags + map

After persisting the data, I tried to run one instance of the job function:

signal.sosfilt(butter_filter,wave[120,:])

and this can be ran in a split of a second, which means that accessing the large data wave is not causing problems. Then I tried the following:

```<code>filtered_futures = []
for pos in coord_list:
  filtered_futures.append(client.submit(filter_wavefield,pos,butter_filter,wave))
</code>```

Once the last line above is ran, I do see some response on the dashboard. Most importantly, my job function filter_wavefield is now listed as one of the tasks being processed (previous two methods won't even get the job function into the progress bars), and the number of tasks for filter_wavefiled is quickly increasing. However, after it increased to about 2700, everything freezes like before. The full size of the for loop, i.e. the coordinate list is 27482400.

I am fairly confident that Dask is built to handle this specific application I am attempting, but I am very lost now as to what else could I try. It seems the problem lies with how I am partitioning the tasks, but I thought this is exactly what Dask bag is supposed to handle (see here), yet the failure of this is what's letting me to try other methods.

Any suggestions would be hugely appreciated!

Body:
I have a fairly straightforward Dask application (filter a large wavefield) that I am having trouble scaling up. My job function is:

def filter_wavefield(pos, butter_filter,wave):
    filtered = signal.sosfilt(butter_filter,wave[pos,:]).astype("float32")
    return filtered

After loading the data to dask arrays (no problem scaling up here), I have tried three approaches to submit jobs:

Pre-scatter the data and pass the futures to the last argument of the job function

wave_future = client.scatter(wave_on_slice_channel,broadcast=True)

# I choose to parallelize over the coordinates, so I make several bags of those
coord_list = [i for i in range(nelem*ngll)]
coord_bag = db.from_sequence(coord_list,npartitions=500)
# Submit the tasks
filtered = coord_bag.map(filter_wavefield, butter_filter,wave_future)
filtered_waves = filtered.compute()

This approach works very well for data size about up to 0.5 TiB. However, now my data size is 1.35 TiB, and even this ~3 fold increase breaks things down completely. When I run filtered_waves = filtered.compute() with the current dataset, everything freezes (i.e. dashboard useless) and the kernel simply dies.

Persist the large data

I then did some research on how people deal with > 1TiB data with dask and come across this page. In the video, the dask expert persist the data right away. I tried this:

wave = wave_on_slice_channel.persist()
wait(wave)

# Same stuff about coordinates
coord_list = [i for i in range(nelem*ngll)]
coord_bag = db.from_sequence(coord_list,npartitions=500)
# Submit the tasks
filtered = coord_bag.map(filter_wavefield, butter_filter,wave)
filtered_waves = filtered.compute()

Note here, the last argument passed in to the job function is no longer a future, but I suppose it's actual data already persisted to the memory.

I am using 500 cores with a total of > 3.5 TiB memory, so after persisting, my dashboard looks like the following

This is all great, and I have my 1.35TiB in the distributed memory. However, everything still breaks once filtered_waves = filtered.compute() is called. The symptom is the same as before. Everything freezes and becomes unresponsive. Shortly after the python kernel dies.

Using for loop + submit rather than dask bags + map

After persisting the data, I tried to run one instance of the job function:

signal.sosfilt(butter_filter,wave[120,:])

and this can be ran in a split of a second, which means that accessing the large data wave is not causing problems. Then I tried the following:

filtered_futures = []
for pos in coord_list:
  filtered_futures.append(client.submit(filter_wavefield,pos,butter_filter,wave))

Once the last line above is ran, I do see some response on the dashboard. Most importantly, my job function filter_wavefield is now listed as one of the tasks being processed (previous two methods won't even get the job function into the progress bars), and the number of tasks for filter_wavefiled is quickly increasing. However, after it increased to about 2700, everything freezes like before. The full size of the for loop, i.e. the coordinate list is 27482400.

I am fairly confident that Dask is built to handle this specific application I am attempting, but I am very lost now as to what else could I try. It seems the problem lies with how I am partitioning the tasks, but I thought this is exactly what Dask bag is supposed to handle (see here), yet the failure of this is what's letting me to try other methods.

Any suggestions would be hugely appreciated!


来源: stackexchange

问:
Click to select a specific data point on the Visual Studio Chart Control
I used to use VB6.0 extensively years ago. Back then I used the BitsPerSecond Chart Control. The event in question looked like this

Bgraph_HotHit(hitset As Integer, hitpoint As Integer)
```

'Bgraph' being the given chart control name in the application and 'HotHit' being the event the event I could intercept to pickup the data point references of 'hitset' and 'hitpoint'.

With this readily available event I used it to easily capture by click, references to a specific data point on the chart so that I could for example, re-plot all points on the chart with reference to that specific selected data point.

I have looked high and low everywhere for the equivalent in C# Chart Control in Visual Studio. I get the impression that there is no such event for the VS Chart control or at least nothing as straight forward as in the above to carryout such a task. Is this right or am I missing something here?

ContentLicense: CC BY-SA 4.0

Body:
I used to use VB6.0 extensively years ago. Back then I used the BitsPerSecond Chart Control. The event in question looked like this

Bgraph_HotHit(hitset As Integer, hitpoint As Integer)

'Bgraph' being the given chart control name in the application and 'HotHit' being the event the event I could intercept to pickup the data point references of 'hitset' and 'hitpoint'.

With this readily available event I used it to easily capture by click, references to a specific data point on the chart so that I could for example, re-plot all points on the chart with reference to that specific selected data point.

I have looked high and low everywhere for the equivalent in C# Chart Control in Visual Studio. I get the impression that there is no such event for the VS Chart control or at least nothing as straight forward as in the above to carryout such a task. Is this right or am I missing something here?


问:
"expected ")" at line 17 got "="" and "expected identifier when parsing expression got "}" " all at line 47
i have problems with the line with the properties variable. it says at line 17 there was a ( in there but when i checked there wasnt. then at the end of the variable i put a } to close the table but it says it expected a identifier when parsing the expression (its a statement).
take a look at the entire script. there is no ( at line 17

`

```<code>local gui=script.Parent
local screengui=gui.Parent
local energy=100
local maxenergy=100
local shifton=0

local player=game.Players.LocalPlayer
local char=player.Character
local human=char:WaitForChild("Humanoid")
local userinput=game:GetService("UserInputService")

local function keystart(input,gameproccess)
    if not gameproccess then
        if input.UserInputType==Enum.UserInputType.Keyboard then
            local keycode=input.KeyCode
            if keycode==Enum.KeyCode.RightShift then
        shifton=1
            end
        end
    end
end
local function keyend(input,gameproccess)
    if not gameproccess then
        if input.UserInputType==Enum.UserInputType.Keyboard then
            local keycode=input.KeyCode
            if keycode==Enum.KeyCode.RightShift then
                    shifton=0
            end
        end
    end
end
userinput.InputBegan:Connect(keystart)
userinput.InputEnded:Connect(keyend)
while true do
    if shifton==1 and energy>0 then
        human.WalkSpeed=16
        energy-=0.1
    else
        human.WalkSpeed=10
        shifton=0
        if energy<maxenergy-1 then
            energy+=0.1
        else
            energy=100
        end
    end
    local property={gui.Size.X=UDim2.new(guienergy,0,0.05,0).X}
    local part=script.Parent
local TweenInf=TweenInfo.new(1,Enum.EasingStyle.Exponential,Enum.EasingDirection.InOut,-1,true,0)
    guienergy=((energy/maxenergy)*0.9)
    tween=game.TweenService:Create(part,TweenInf,property)

    tween:Play()

    wait(0)
end

</code>```

`

Body:
i have problems with the line with the properties variable. it says at line 17 there was a ( in there but when i checked there wasnt. then at the end of the variable i put a } to close the table but it says it expected a identifier when parsing the expression (its a statement).
take a look at the entire script. there is no ( at line 17

`

local gui=script.Parent
local screengui=gui.Parent
local energy=100
local maxenergy=100
local shifton=0

local player=game.Players.LocalPlayer
local char=player.Character
local human=char:WaitForChild("Humanoid")
local userinput=game:GetService("UserInputService")

local function keystart(input,gameproccess)
    if not gameproccess then
        if input.UserInputType==Enum.UserInputType.Keyboard then
            local keycode=input.KeyCode
            if keycode==Enum.KeyCode.RightShift then
        shifton=1
            end
        end
    end
end
local function keyend(input,gameproccess)
    if not gameproccess then
        if input.UserInputType==Enum.UserInputType.Keyboard then
            local keycode=input.KeyCode
            if keycode==Enum.KeyCode.RightShift then
                    shifton=0
            end
        end
    end
end
userinput.InputBegan:Connect(keystart)
userinput.InputEnded:Connect(keyend)
while true do
    if shifton==1 and energy>0 then
        human.WalkSpeed=16
        energy-=0.1
    else
        human.WalkSpeed=10
        shifton=0
        if energy<maxenergy-1 then
            energy+=0.1
        else
            energy=100
        end
    end
    local property={gui.Size.X=UDim2.new(guienergy,0,0.05,0).X}
    local part=script.Parent
local TweenInf=TweenInfo.new(1,Enum.EasingStyle.Exponential,Enum.EasingDirection.InOut,-1,true,0)
    guienergy=((energy/maxenergy)*0.9)
    tween=game.TweenService:Create(part,TweenInf,property)

    tween:Play()

    wait(0)
end

`


问:
Create array of attributes values from fetch entity of CoreData
In my coredata model I have an entity called "Player" which has an attribute called "name" (of type "String")
I would like to fetch the Player entity and then create an array with all the different "name".
I will then use that array to populate a "Picker"

my struct is something like that:

```<code>struct RamiStatistiquesUIView: View {
    @Environment(\.managedObjectContext) var moc

    @State private var player1 = ""
    @State private var player2 = ""
    let player_list : Array<Any>

    @FetchRequest
    private var players: FetchedResults<Player>

    init(){
        let sortDescriptors = [SortDescriptor(\Player.name)]
        _players = FetchRequest(sortDescriptors: sortDescriptors)

       // In the following line I would like to create an array of string with all the
       //  different "names" of the players (a list of unique value, because some names
       // may exist more than once)
       player_list = ...
     }

    var body: some View {
        Picker("player 1", selection: $player1) {
            ForEach(player_list, id: \.self) { player in
                Text(player)
            }
        }
        .padding()
        Picker("player 2", selection: $player2) {
            ForEach(player_list, id: \.self) { player in
                Text(player)
            }
        }
        .padding()
    }
}
</code>```

Body:
In my coredata model I have an entity called "Player" which has an attribute called "name" (of type "String")
I would like to fetch the Player entity and then create an array with all the different "name".
I will then use that array to populate a "Picker"

my struct is something like that:

struct RamiStatistiquesUIView: View {
    @Environment(\.managedObjectContext) var moc

    @State private var player1 = ""
    @State private var player2 = ""
    let player_list : Array<Any>

    @FetchRequest
    private var players: FetchedResults<Player>

    init(){
        let sortDescriptors = [SortDescriptor(\Player.name)]
        _players = FetchRequest(sortDescriptors: sortDescriptors)

       // In the following line I would like to create an array of string with all the
       //  different "names" of the players (a list of unique value, because some names
       // may exist more than once)
       player_list = ...
     }

    var body: some View {
        Picker("player 1", selection: $player1) {
            ForEach(player_list, id: \.self) { player in
                Text(player)
            }
        }
        .padding()
        Picker("player 2", selection: $player2) {
            ForEach(player_list, id: \.self) { player in
                Text(player)
            }
        }
        .padding()
    }
}


问:
Add metadata to image using node.js
I've been trying to create a node.js script that will allow me to upload 360 degree photo spheres to Google Maps. I'm thinking I'll need to attach some custom metadata to the image. I've already figured out the first 2 requests.

3rd request: POST https://streetviewpublish.googleapis.com/v1/photo?key=X with body:

```<code>                {
                  "uploadReference":
                  {
                    "uploadUrl": "https://streetviewpublish.googleapis.com/media/user/113033544511164xxxxxx/photo/6699853318082xxxxxx"
                  },
                  "pose":
                   {
                     "latLngPair":
                     {
                       "latitude": X,
                       "longitude": -Y
                     },
                     "heading": 0
                  }
                }
</code>```

I've censored some personal information

With the 3rd request, I am getting an error saying that it's not a 360 photo.

I'm assuming I will need to attach metadata to the image, however I can only find answers on VIEWING metadata, not writing it.

https://developers.google.com/streetview/spherical-metadata
Here is the metadata that is required. I would like to be able to add this metadata using Node.js, really just looking for the simplest way to add metadata, I'd prefer to be able to just copy and paste the metadata without having to change the format of it, and just editing the values to my values. Hopefully adding metadata will fix my issue, however if it's something else please let me know!

I've already figured out the first 2 requests.

POST https://streetviewpublish.googleapis.com/v1/photo:startUpload?key=X - I get uploadUrl from here

POST uploadUrl with image file as binary body. - No response, assuming it uploaded the file, because if I don't run this request I get a different error message, so the file is definitely uploaded.
The image is a 2:1 resolution, so it shouldn't be an issue with the aspect ratio. (13704x6852) The 360 image came from my DJI spark drone and stitched together using the DJI Media Maker, DJI doesn't make a full image so I increase the height of the image and add some color into the blind spot of the drone in order to make it 2:1 aspect ratio. These images worked in the Google Streetview android app, however, they are discontinuing the app, which is why I'm creating my own script (also because I'd like to be able to upload on computer and Google's new StreetView Studio only supports videos).

Title: Add metadata to image using node.js

Body:
I've been trying to create a node.js script that will allow me to upload 360 degree photo spheres to Google Maps. I'm thinking I'll need to attach some custom metadata to the image. I've already figured out the first 2 requests.

3rd request: POST https://streetviewpublish.googleapis.com/v1/photo?key=X with body:

                {
                  "uploadReference":
                  {
                    "uploadUrl": "https://streetviewpublish.googleapis.com/media/user/113033544511164xxxxxx/photo/6699853318082xxxxxx"
                  },
                  "pose":
                   {
                     "latLngPair":
                     {
                       "latitude": X,
                       "longitude": -Y
                     },
                     "heading": 0
                  }
                }

I've censored some personal information

With the 3rd request, I am getting an error saying that it's not a 360 photo.

I'm assuming I will need to attach metadata to the image, however I can only find answers on VIEWING metadata, not writing it.

https://developers.google.com/streetview/spherical-metadata
Here is the metadata that is required. I would like to be able to add this metadata using Node.js, really just looking for the simplest way to add metadata, I'd prefer to be able to just copy and paste the metadata without having to change the format of it, and just editing the values to my values. Hopefully adding metadata will fix my issue, however if it's something else please let me know!

I've already figured out the first 2 requests.

POST https://streetviewpublish.googleapis.com/v1/photo:startUpload?key=X - I get uploadUrl from here

POST uploadUrl with image file as binary body. - No response, assuming it uploaded the file, because if I don't run this request I get a different error message, so the file is definitely uploaded.
The image is a 2:1 resolution, so it shouldn't be an issue with the aspect ratio. (13704x6852) The 360 image came from my DJI spark drone and stitched together using the DJI Media Maker, DJI doesn't make a full image so I increase the height of the image and add some color into the blind spot of the drone in order to make it 2:1 aspect ratio. These images worked in the Google Streetview android app, however, they are discontinuing the app, which is why I'm creating my own script (also because I'd like to be able to upload on computer and Google's new StreetView Studio only supports videos).


问:
Why does paintComponent not erase past Objects?
Im trying to make a rectangle move on certain Input. Although the Input works, the rectangle is not being redrawn in the way I want it to. The former rectangles are not being erased.

`

```<code>public class MiniGame_Panel extends JPanel implements Runnable{

    /**
     *
     */
    private static final long serialVersionUID = 1L;
    Thread gameThread;
    public KeyHandler2 keyH = new KeyHandler2();
    public MGPlayer spieler = new MGPlayer(keyH, this);

    public MiniGame_Panel() {
        setBackground(new Color(222, 228, 128, 0));
        setBounds(0, 0, 16*16*3 + 300 + 3, 16*13*3);
        setVisible(true);
        setFocusable(true);
        requestFocus();

        this.addKeyListener(keyH);
    }

    public void startGameThread() {
        gameThread = new Thread((Runnable) this);
        gameThread.start();
    }

    public void run() {
        double drawInterval = 1000000000/60;
        double delta = 0;
        long lastTime = System.nanoTime();
        long currentTime;

        // GAME LOOP
        while(gameThread != null) {
            currentTime = System.nanoTime();
            delta += (currentTime - lastTime) / drawInterval;
            lastTime = currentTime;

            if(delta >= 1) {
                update();
                repaint();
                delta--;
            }
        }
    }

    public void update() {
        spieler.update();
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g;

        spieler.draw(g2);

        g2.dispose();
    }

}
</code>```
```<code>public class MGPlayer {

    private int x, y;
    private Rectangle rect;
    private int width, height;
    private int leben;
    private KeyHandler2 keyH;
    private MiniGame_Panel mGp;

    public MGPlayer(KeyHandler2 keyH, MiniGame_Panel miniGame_Panel) {
        x = 10;
        y = 100;
        width = 50;
        height = 100;
        leben = 3;
        this.keyH = keyH;
        this.mGp = miniGame_Panel;
    }

    boolean allowJump;
    public void update() {
        if(keyH.stats) {
            if(!allowJump) {
                this.y -= 8;
            }
            //System.out.println("Leertaste");
        }
        if(keyH.left == true) {
            this.x--;
            //System.out.println("links");
        }
        if(keyH.right == true) {
            this.x++;
            //System.out.println("rechts");
            }

        if(y <= 200) {
            this.y++;
            allowJump = true;
        }else {
            allowJump = false;
        }

    }
    public void draw(Graphics2D g2) {
        g2.setColor(Color.BLACK);
        g2.fillRect(x, y, width, height);
    }

}
</code>```

`

I just want to draw a rectangle that moves on certain input. This works but instead of redrawing the rectangle, they all stay in the panel.

Body:
Im trying to make a rectangle move on certain Input. Although the Input works, the rectangle is not being redrawn in the way I want it to. The former rectangles are not being erased.

`

public class MiniGame_Panel extends JPanel implements Runnable{

    /**
     *
     */
    private static final long serialVersionUID = 1L;
    Thread gameThread;
    public KeyHandler2 keyH = new KeyHandler2();
    public MGPlayer spieler = new MGPlayer(keyH, this);

    public MiniGame_Panel() {
        setBackground(new Color(222, 228, 128, 0));
        setBounds(0, 0, 16*16*3 + 300 + 3, 16*13*3);
        setVisible(true);
        setFocusable(true);
        requestFocus();

        this.addKeyListener(keyH);
    }

    public void startGameThread() {
        gameThread = new Thread((Runnable) this);
        gameThread.start();
    }

    public void run() {
        double drawInterval = 1000000000/60;
        double delta = 0;
        long lastTime = System.nanoTime();
        long currentTime;

        // GAME LOOP
        while(gameThread != null) {
            currentTime = System.nanoTime();
            delta += (currentTime - lastTime) / drawInterval;
            lastTime = currentTime;

            if(delta >= 1) {
                update();
                repaint();
                delta--;
            }
        }
    }

    public void update() {
        spieler.update();
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g;

        spieler.draw(g2);

        g2.dispose();
    }

}

public class MGPlayer {

    private int x, y;
    private Rectangle rect;
    private int width, height;
    private int leben;
    private KeyHandler2 keyH;
    private MiniGame_Panel mGp;

    public MGPlayer(KeyHandler2 keyH, MiniGame_Panel miniGame_Panel) {
        x = 10;
        y = 100;
        width = 50;
        height = 100;
        leben = 3;
        this.keyH = keyH;
        this.mGp = miniGame_Panel;
    }

    boolean allowJump;
    public void update() {
        if(keyH.stats) {
            if(!allowJump) {
                this.y -= 8;
            }
            //System.out.println("Leertaste");
        }
        if(keyH.left == true) {
            this.x--;
            //System.out.println("links");
        }
        if(keyH.right == true) {
            this.x++;
            //System.out.println("rechts");
            }

        if(y <= 200) {
            this.y++;
            allowJump = true;
        }else {
            allowJump = false;
        }

    }
    public void draw(Graphics2D g2) {
        g2.setColor(Color.BLACK);
        g2.fillRect(x, y, width, height);
    }

}

`

I just want to draw a rectangle that moves on certain input. This works but instead of redrawing the rectangle, they all stay in the panel.


问:
How to reflect custom font for Urdu (or other RTL language) in document with SCSS and Markdown?
I'm trying to add Urdu (right-to-left) content to my site, built using Zola (static site generator). Zola only reads/publishes .md files, so can't just publish html files directly, and so am trying to modify the markdown file to use the right font. It works great for English content (where I use the default fonts), but I'm having issues in extending its functionality to Urdu.

The default font reflects Urdu content in Arabic-style Naskh rather than Urdu/Persian-style Nastaliq. This makes it harder to read.

I've downloaded the google font Gulzar-Regular and added the following lines to my main.scss html file. I was expecting to be able to change the font variables for specific text, e.g., as we can make text right to left, or larger in size. I was expecting to be able to do the same for the font itself, i.e., telling the build to use this particular font in this context.

When this didn't work, I did a lot of googling to understand if other's had a similar problem. I found some material for converting right to left, and to use RTL languages for one-off words within mostly English content, but that did not address the usage of fonts. Some usage was also found re fonts but that was typically within a single html file, not within a separate SCSS and md file.

Here's what I've tried:

(in main.scss)

```<code>html { @font-face{
  font-family: {"Gulzar-Regular", serif;
  src: url(Gulzar-Regular.ttf);
}
</code>```

I've also tried:

```<code>html {
  font-family: Gulzar-Regular;
  src: url(Gulzar-Regular.ttf);
}
</code>```

Note, I downloaded the file (ttf) in the same directory as the main.scss file.

In my .md file, I've added:

```<code><div dir="rtl">
<span style="font-family:Gulzar-Regular;font-size:1em">

!CONTENT!

</span>
</div>
</code>```

In either case, I only get Naskh (i.e, default font). Would love to hear from anyone who has used additional fonts, especially for non-latin and right-to-left languages like Arabic, Hebrew, Persian, etc.

Body:
I'm trying to add Urdu (right-to-left) content to my site, built using Zola (static site generator). Zola only reads/publishes .md files, so can't just publish html files directly, and so am trying to modify the markdown file to use the right font. It works great for English content (where I use the default fonts), but I'm having issues in extending its functionality to Urdu.

The default font reflects Urdu content in Arabic-style Naskh rather than Urdu/Persian-style Nastaliq. This makes it harder to read.

I've downloaded the google font Gulzar-Regular and added the following lines to my main.scss html file. I was expecting to be able to change the font variables for specific text, e.g., as we can make text right to left, or larger in size. I was expecting to be able to do the same for the font itself, i.e., telling the build to use this particular font in this context.

When this didn't work, I did a lot of googling to understand if other's had a similar problem. I found some material for converting right to left, and to use RTL languages for one-off words within mostly English content, but that did not address the usage of fonts. Some usage was also found re fonts but that was typically within a single html file, not within a separate SCSS and md file.

Here's what I've tried:

(in main.scss)

html { @font-face{
  font-family: {"Gulzar-Regular", serif;
  src: url(Gulzar-Regular.ttf);
}

I've also tried:

html {
  font-family: Gulzar-Regular;
  src: url(Gulzar-Regular.ttf);
}

Note, I downloaded the file (ttf) in the same directory as the main.scss file.

In my .md file, I've added:

!CONTENT!

In either case, I only get Naskh (i.e, default font). Would love to hear from anyone who has used additional fonts, especially for non-latin and right-to-left languages like Arabic, Hebrew, Persian, etc.


问:
Construct simple 1D probability contours in r
I want to recreate an image like the attached for my own data in R.

Green and Theobald. Sexing birds by discriminant analysis: further considerations. 1989. IBIS

An example of my data:

```<code>df <- data.frame (sex  = c("M", "M", "F", "M", "F"),
                  wing = c(110,110,115,113,113),
                  bill = c(24,24,26,25,28)
)
</code>```

I've plotted my real data using the following code just fine, but want to add lines representing 0.01, 0.5, 0.99 probability of a bird being male given bill and wing.

```<code>Dunlin_abbrev %>%
  ggplot(
    aes(Bill, Wing, color = Sex))+
      geom_point()
</code>```

The attached graph is from a Green and Theobald (1989) paper that used a discriminant function analysis to predict bird gender by bill and wing length.

The paper said they constructed a graph with contours corresponding to specified probabilities a bird is a male. However, all my searches for "probability contours" give me 2D contour lines that completely encircle my data like mapping a mountain such as geom_contour(), rather than the simple 1D splitting line I desire.

Body:
I want to recreate an image like the attached for my own data in R.

Green and Theobald. Sexing birds by discriminant analysis: further considerations. 1989. IBIS

An example of my data:

df <- data.frame (sex  = c("M", "M", "F", "M", "F"),
                  wing = c(110,110,115,113,113),
                  bill = c(24,24,26,25,28)
)

I've plotted my real data using the following code just fine, but want to add lines representing 0.01, 0.5, 0.99 probability of a bird being male given bill and wing.

Dunlin_abbrev %>%
  ggplot(
    aes(Bill, Wing, color = Sex))+
      geom_point()

The attached graph is from a Green and Theobald (1989) paper that used a discriminant function analysis to predict bird gender by bill and wing length.

The paper said they constructed a graph with contours corresponding to specified probabilities a bird is a male. However, all my searches for "probability contours" give me 2D contour lines that completely encircle my data like mapping a mountain such as geom_contour(), rather than the simple 1D splitting line I desire.


问:
boostrap model throwing backdrop error and prevents showing modal
This is my error code

```<code>index.js:130 Uncaught (in promise) TypeError: BACKDROP: Option "rootElement" provided type "null" but expected type "element".
    at index.js:130:13
    at Array.forEach (<anonymous>)
    at l (index.js:124:28)
    at xe._getConfig (backdrop.js:92:5)
    at new xe (backdrop.js:33:25)
    at Ne._initializeBackDrop (modal.js:218:12)
    at new Ne (modal.js:84:27)
    at HTMLDivElement.<anonymous> (modal.js:412:47)
    at Function.each (jquery-3.6.0.min.js:2:3003)
    at S.fn.init.each (jquery-3.6.0.min.js:2:1481)
</code>```

I am trying to show bootstrap modal when server send the result as success.

This is my javascript code,

```<code> console.log(data);

                        if (data.result == 'success') {
                            $('.modal-body').html('Form submission was successful!');
                            $('#modal-dialog').modal('show');
                            addRoleForm.reset();
                        } else {
                            $('.modal-body').html('There was an error with the form submission.');
                            $('#modal-dialog').modal('show');
                        }
</code>```

console outputs result as success,

```<code>{result: 'success'}result: "success"[[Prototype]]: Object
</code>```

This is my modal code,

```<code>
<!-- close modal because I prevented default -->
<script>
    $(document).ready(function () {
        $('#close-modal').on('click', function () {
            $('#modal-dialog').modal('hide');
        });
    });
</script>

<!-- jason model dialog box -->
<div class="modal" tabindex="-1" role="dialog" id="modal-dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Feedback</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
            </div>
            <div class="modal-body">
                <!-- Modal content goes here -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" id="close-modal" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>
</code>```

Basically I want to show message based on result.

Body:
This is my error code

index.js:130 Uncaught (in promise) TypeError: BACKDROP: Option "rootElement" provided type "null" but expected type "element".
    at index.js:130:13
    at Array.forEach (<anonymous>)
    at l (index.js:124:28)
    at xe._getConfig (backdrop.js:92:5)
    at new xe (backdrop.js:33:25)
    at Ne._initializeBackDrop (modal.js:218:12)
    at new Ne (modal.js:84:27)
    at HTMLDivElement.<anonymous> (modal.js:412:47)
    at Function.each (jquery-3.6.0.min.js:2:3003)
    at S.fn.init.each (jquery-3.6.0.min.js:2:1481)

I am trying to show bootstrap modal when server send the result as success.

This is my javascript code,

 console.log(data);

                        if (data.result == 'success') {
                            $('.modal-body').html('Form submission was successful!');
                            $('#modal-dialog').modal('show');
                            addRoleForm.reset();
                        } else {
                            $('.modal-body').html('There was an error with the form submission.');
                            $('#modal-dialog').modal('show');
                        }

console outputs result as success,

{result: 'success'}result: "success"[[Prototype]]: Object

This is my modal code,

Feedback

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    ×
                </button>

                <button type="button" class="btn btn-secondary" id="close-modal" data-dismiss="modal">Close</button>

Basically I want to show message based on result.


问:
I need to change the output of a button click times
I know there's a way to do this. For whatever reason it's slipping and I can't figure this out... What I'm trying to do is get the text when you click 15 minutes button, to be green; when you click 60 minutes have it be yellow.

document.addEventListener('DOMContentLoaded', function() {
  let countdown;
  let overtime;
  const display = document.querySelector(".display");
  const timeDisplay = document.querySelector(".display-time");
  const hourDisplay = document.querySelector(".display-hour");
  const buttons = document.querySelectorAll("[data-time]");

  function time(seconds) {
    // Clear any existing timers
    timeDisplay.style.color = "white";
    clearInterval(countdown);
    clearInterval(overtime);
    const now = Date.now();
    const then = now + seconds * 1000;
    displayTimeLeft(seconds);
    displayEndHour(then);
    countdown = setInterval(() => {
      // Time left in seconds
      const secondsLeft = Math.round((then - Date.now()) / 1000);
      // Check if it should stop and go over
      if (secondsLeft <= 0) {
        timeDisplay.style.color = "white";
        hourDisplay.style.color = "white";
        display.style.backgroundColor = "black";
      }
      if (secondsLeft <= 0) {
        clearInterval(countdown);
        displayTimeOver();
        return;
      }
      // Display
      displayTimeLeft(secondsLeft);
      if (secondsLeft < 10) {
        timeDisplay.style.color = "red";
      }
    }, 1000);
  }

  function displayTimeOver() {
    let minutesOver = 0;
    let secondsOver = 0;
    timeDisplay.textContent = "0:00";
    overtime = setInterval(() => {
      secondsOver++;
      if (secondsOver === 60) {
        secondsOver = 0;
        minutesOver++;
      }
      console.log({
        minutesOver,
        secondsOver
      });
      let display = `-${minutesOver}:${((secondsOver < 10) ? "0" : "")}${secondsOver}`
      timeDisplay.textContent = display;
    }, 1000)
  }

  function displayTimeLeft(seconds) {
    const minutes = Math.floor(seconds / 60);
    const remainderSeconds = seconds % 60;
    console.log({
      minutes,
      remainderSeconds
    });
    let display = `${minutes}:${((remainderSeconds < 10 && remainderSeconds >= 0) ? "0" : "")}${remainderSeconds}`;
    document.title = display;
    timeDisplay.textContent = display;
    if (remainderSeconds <= 0) {
      timeDisplay.style.color = "darkorange";
      hourDisplay.style.color = "darkorange";
    }
  }

  function displayEndHour(timestamp) {
    const end = new Date(timestamp);
    const hour = end.getHours();
    const minutes = end.getMinutes();
    hourDisplay.textContent = `Break/Lunch End Time ${hour}:${minutes < 10 ? "0" : ""}${minutes}`;
  }

  function startTimer() {
    const seconds = parseInt(this.dataset.time);
    time(seconds);
    display.style.backgroundColor = "black";
    timeDisplay.style.color = "darkorange";
    hourDisplay.style.color = "darkorange";
  }
  buttons.forEach(button => button.addEventListener("click", startTimer));
  document.customForm.addEventListener("submit", function(e) {
    e.preventDefault();
    const minutes = this.minutes.value;
    time(minutes * 60);
    this.reset();
    display.style.backgroundColor = "black";
    timeDisplay.style.color = "darkorange";
    hourDisplay.style.color = "darkorange";
  })
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>p {
  background-color: black;
  border: darkorange;
  border-width: thick;
  border-style: solid;
  color: darkorange;
  padding: 10px10px;
  text-align: center;
  font-size: 50px;
  margin: 4px2px;
}
un {
  background-color: black;
  color: red;
  padding: 10px10px;
  text-align: center;
  font-size: 20px;
  margin: 4px2px;
}
body {
  background-color: black;
}

.container {
  background-color: black;
}

.choose-time {
  background-color: black;
  border: darkorange;
  border-width: medium;
  border-style: solid;
  color: darkorange;
  text-align: center;
  font-size: 50px;
  font-color: black;
}

.timer {
  -webkit-box-shadow: 10px 10px 42px -24px rgba(255, 140, 0, 0.25);
  -moz-box-shadow: 10px 10px 42px -24px rgba(255, 140, 0, 0.25);
  -box-shadow: 10px 10px 42px -24px rgba(255, 140, 0, 0.25);
  background-color: darkorange;
  border: darkorange;
  border-width: medium;
  border-style: solid;
  color: black;
  text-align: center;
  font-size: 50px;
}

.timerbutton15 {
  background-color: black;
  border: lime;
  border-width: medium;
  border-style: solid;
  color: lime;
  padding: 10px20px;
  text-align: center;
  font-size: 30px;
  margin: 4px2px;
  cursor: pointer;
}

.timerbutton60 {
  background-color: black;
  border: darkorange;
  border-width: medium;
  border-style: solid;
  color: darkorange;
  padding: 10px20px;
  text-align: center;
  font-size: 30px;
  margin: 4px2px;
  cursor: pointer;
}

.timer-form {
  background-color: black;
  border: black;
  border-width: medium;
  border-style: solid;
  color: darkorange;
  text-align: center;
  font-size: 25px;
  padding: 10px20px;
  cursor: pointer;
}

.timer-input {
  background-color: black;
  border: darkorange;
  border-width: medium;
  border-style: solid;
  color: darkorange;
  text-align: center;
  font-size: 25px;
  cursor: pointer;
}

.display {
  background-color: black;
  border: darkorange;
  border-width: medium;
  border-style: solid;
  color: darkorange;
  padding: 10px20px;
  text-align: center;
  font-size: 40px;
  margin: 4px2px;
  cursor: pointer;
}

.display-time {
  background-color: black;
  border: darkorange;
  border-width: thin;
  border-style: solid;
  color: darkorange;
  padding: 10px20px;
  text-align: center;
  font-size: 40px;
  margin: 4px2px;
}</code>```

Break/Lunch Timer

<display>

</display>

<un>Use Note: Please click either button for break or lunch timing. If you need a customer time, enter the time in minutes in the "Enter Custom Time" field and press return/enter. This will then run a timer for the time input. (ex. Entering 5 would run a 5 minute timer.)</un>

  <input type="button" button name="timerbutton15" class="timerbutton15 timer" value="15 Minutes (Break)" data-time="900"
  onclick="document.customForm.addEventListener("submit", function(e)">
  <input type="button" button name="timerbutton60" class="timerbutton60 timer" value="60 Minutes (Lunch)" data-time="3600"
  onclick="document.customForm.addEventListener("submit", function(e)">
    <form name="customForm" id="custom" class="timer-form">
      <input type="number" name="minutes" color="black" placeholder="Enter Custom Time" min="00.00" class="timer-input timer">
    </form>

```

As you can see I've got this figured out mostly, and I can change the text output color of a button. I just can't get it to sufficiently change both text outputs differently.

Body:
I know there's a way to do this. For whatever reason it's slipping and I can't figure this out... What I'm trying to do is get the text when you click 15 minutes button, to be green; when you click 60 minutes have it be yellow.

document.addEventListener('DOMContentLoaded', function() {
  let countdown;
  let overtime;
  const display = document.querySelector(".display");
  const timeDisplay = document.querySelector(".display-time");
  const hourDisplay = document.querySelector(".display-hour");
  const buttons = document.querySelectorAll("[data-time]");

  function time(seconds) {
    // Clear any existing timers
    timeDisplay.style.color = "white";
    clearInterval(countdown);
    clearInterval(overtime);
    const now = Date.now();
    const then = now + seconds * 1000;
    displayTimeLeft(seconds);
    displayEndHour(then);
    countdown = setInterval(() => {
      // Time left in seconds
      const secondsLeft = Math.round((then - Date.now()) / 1000);
      // Check if it should stop and go over
      if (secondsLeft <= 0) {
        timeDisplay.style.color = "white";
        hourDisplay.style.color = "white";
        display.style.backgroundColor = "black";
      }
      if (secondsLeft <= 0) {
        clearInterval(countdown);
        displayTimeOver();
        return;
      }
      // Display
      displayTimeLeft(secondsLeft);
      if (secondsLeft < 10) {
        timeDisplay.style.color = "red";
      }
    }, 1000);
  }

  function displayTimeOver() {
    let minutesOver = 0;
    let secondsOver = 0;
    timeDisplay.textContent = "0:00";
    overtime = setInterval(() => {
      secondsOver++;
      if (secondsOver === 60) {
        secondsOver = 0;
        minutesOver++;
      }
      console.log({
        minutesOver,
        secondsOver
      });
      let display = `-${minutesOver}:${((secondsOver < 10) ? "0" : "")}${secondsOver}`
      timeDisplay.textContent = display;
    }, 1000)
  }

  function displayTimeLeft(seconds) {
    const minutes = Math.floor(seconds / 60);
    const remainderSeconds = seconds % 60;
    console.log({
      minutes,
      remainderSeconds
    });
    let display = `${minutes}:${((remainderSeconds < 10 && remainderSeconds >= 0) ? "0" : "")}${remainderSeconds}`;
    document.title = display;
    timeDisplay.textContent = display;
    if (remainderSeconds <= 0) {
      timeDisplay.style.color = "darkorange";
      hourDisplay.style.color = "darkorange";
    }
  }

  function displayEndHour(timestamp) {
    const end = new Date(timestamp);
    const hour = end.getHours();
    const minutes = end.getMinutes();
    hourDisplay.textContent = `Break/Lunch End Time ${hour}:${minutes < 10 ? "0" : ""}${minutes}`;
  }

  function startTimer() {
    const seconds = parseInt(this.dataset.time);
    time(seconds);
    display.style.backgroundColor = "black";
    timeDisplay.style.color = "darkorange";
    hourDisplay.style.color = "darkorange";
  }
  buttons.forEach(button => button.addEventListener("click", startTimer));
  document.customForm.addEventListener("submit", function(e) {
    e.preventDefault();
    const minutes = this.minutes.value;
    time(minutes * 60);
    this.reset();
    display.style.backgroundColor = "black";
    timeDisplay.style.color = "darkorange";
    hourDisplay.style.color = "darkorange";
  })
});

p {
  background-color: black;
  border: darkorange;
  border-width: thick;
  border-style: solid;
  color: darkorange;
  padding: 10px10px;
  text-align: center;
  font-size: 50px;
  margin: 4px2px;
}
un {
  background-color: black;
  color: red;
  padding: 10px10px;
  text-align: center;
  font-size: 20px;
  margin: 4px2px;
}
body {
  background-color: black;
}

.container {
  background-color: black;
}

.choose-time {
  background-color: black;
  border: darkorange;
  border-width: medium;
  border-style: solid;
  color: darkorange;
  text-align: center;
  font-size: 50px;
  font-color: black;
}

.timer {
  -webkit-box-shadow: 10px 10px 42px -24px rgba(255, 140, 0, 0.25);
  -moz-box-shadow: 10px 10px 42px -24px rgba(255, 140, 0, 0.25);
  -box-shadow: 10px 10px 42px -24px rgba(255, 140, 0, 0.25);
  background-color: darkorange;
  border: darkorange;
  border-width: medium;
  border-style: solid;
  color: black;
  text-align: center;
  font-size: 50px;
}

.timerbutton15 {
  background-color: black;
  border: lime;
  border-width: medium;
  border-style: solid;
  color: lime;
  padding: 10px20px;
  text-align: center;
  font-size: 30px;
  margin: 4px2px;
  cursor: pointer;
}

.timerbutton60 {
  background-color: black;
  border: darkorange;
  border-width: medium;
  border-style: solid;
  color: darkorange;
  padding: 10px20px;
  text-align: center;
  font-size: 30px;
  margin: 4px2px;
  cursor: pointer;
}

.timer-form {
  background-color: black;
  border: black;
  border-width: medium;
  border-style: solid;
  color: darkorange;
  text-align: center;
  font-size: 25px;
  padding: 10px20px;
  cursor: pointer;
}

.timer-input {
  background-color: black;
  border: darkorange;
  border-width: medium;
  border-style: solid;
  color: darkorange;
  text-align: center;
  font-size: 25px;
  cursor: pointer;
}

.display {
  background-color: black;
  border: darkorange;
  border-width: medium;
  border-style: solid;
  color: darkorange;
  padding: 10px20px;
  text-align: center;
  font-size: 40px;
  margin: 4px2px;
  cursor: pointer;
}

.display-time {
  background-color: black;
  border: darkorange;
  border-width: thin;
  border-style: solid;
  color: darkorange;
  padding: 10px20px;
  text-align: center;
  font-size: 40px;
  margin: 4px2px;
}

Break/Lunch Timer

<display>

</display>

<un>Use Note: Please click either button for break or lunch timing. If you need a customer time, enter the time in minutes in the "Enter Custom Time" field and press return/enter. This will then run a timer for the time input. (ex. Entering 5 would run a 5 minute timer.)</un>

  <input type="button" button name="timerbutton15" class="timerbutton15 timer" value="15 Minutes (Break)" data-time="900"
  onclick="document.customForm.addEventListener("submit", function(e)">
  <input type="button" button name="timerbutton60" class="timerbutton60 timer" value="60 Minutes (Lunch)" data-time="3600"
  onclick="document.customForm.addEventListener("submit", function(e)">
    <form name="customForm" id="custom" class="timer-form">
      <input type="number" name="minutes" color="black" placeholder="Enter Custom Time" min="00.00" class="timer-input timer">
    </form>

As you can see I've got this figured out mostly, and I can change the text output color of a button. I just can't get it to sufficiently change both text outputs differently.


问:
Role.members only contains a single value when there are multiple
I have a slash command with this option definition:

.addRoleOption(option =>
    option.setName('role')
        .setRequired(true)
        .setDescription("The role associated with the game.")
)
```
<p>In <code>execute()</code> of the same file/command, I have this part where I want to collect and store all members who have the role.</p>
<pre class="lang-js prettyprint-override"><code>const existingParticipants = [];
interaction.options.getRole('role').members
    .each(member => existingParticipants.push(member.id));
console.log(`Import compiled a list of all role-having members: ${existingParticipants}`);
</code>```

And this is printed:

Import compiled a list of all role-having members: [userid redacted]

When I have other people do the command, their IDs are added to the list until I restart the bot, at which point the list goes back to just my ID. I have also tried to bypass the cache to see if that was the issue but it still persists:

await interaction.guild.roles.fetch(interaction.options.getRole('role').id, { force: true })
    .then(role => role.members
        .forEach(member => existingParticipants.push(member.id)))
```

Is it possible to get all of the guild members that have the role?

I have the GUILD_MEMBERS gateway intent enabled. Running Discord.js v14.7.1.

Body:
I have a slash command with this option definition:

.addRoleOption(option =>
    option.setName('role')
        .setRequired(true)
        .setDescription("The role associated with the game.")
)

In execute() of the same file/command, I have this part where I want to collect and store all members who have the role.

const existingParticipants = [];
interaction.options.getRole('role').members
    .each(member => existingParticipants.push(member.id));
console.log(`Import compiled a list of all role-having members: ${existingParticipants}`);

And this is printed:

Import compiled a list of all role-having members: [userid redacted]

When I have other people do the command, their IDs are added to the list until I restart the bot, at which point the list goes back to just my ID. I have also tried to bypass the cache to see if that was the issue but it still persists:

await interaction.guild.roles.fetch(interaction.options.getRole('role').id, { force: true })
    .then(role => role.members
        .forEach(member => existingParticipants.push(member.id)))

Is it possible to get all of the guild members that have the role?

I have the GUILD_MEMBERS gateway intent enabled. Running Discord.js v14.7.1.


问:
Read file which name contains hangul from console
code

using System;
using System.IO;

namespace letstest
{
    class Program
    {
        static void Main(string[] args)
        {
            string fileName = Console.ReadLine();
            File.OpenRead(Console.ReadLine());
        }
    }
}

```
<p>There is a.txt and 아.txt in same folder.
When I write a.txt, it works well.
But when I write 아.txt, it throws.</p>
<p>I have not checked what is the value of <code>fileName</code>, but I typed "아.txt" as shown in input/output below:</p>
```아.txt

Unhandled Exception: System.ArgumentException: Illegal characters in path.
   at System.Security.Permissions.FileIOPermission.EmulateFileIOPermissionChecks(String fullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)
   at System.IO.File.OpenRead(String path)
   at letstest.Program.Main(String[] args) in C:\Users\nasoo\source\repos\letstest\letstest\Program.cs:line 10
```

I want to make my program that can read file which name contains hangul. How to solve this?

Body:
code

using System;
using System.IO;

namespace letstest
{
    class Program
    {
        static void Main(string[] args)
        {
            string fileName = Console.ReadLine();
            File.OpenRead(Console.ReadLine());
        }
    }
}

There is a.txt and 아.txt in same folder.
When I write a.txt, it works well.
But when I write 아.txt, it throws.

I have not checked what is the value of fileName, but I typed "아.txt" as shown in input/output below:

아.txt

Unhandled Exception: System.ArgumentException: Illegal characters in path.
   at System.Security.Permissions.FileIOPermission.EmulateFileIOPermissionChecks(String fullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)
   at System.IO.File.OpenRead(String path)
   at letstest.Program.Main(String[] args) in C:\Users\nasoo\source\repos\letstest\letstest\Program.cs:line 10

I want to make my program that can read file which name contains hangul. How to solve this?


问:
Call login page only if the request comes from a specific URL
I'm using Spring Boot 2.7.6 and I would like to secure my application in this way:

a single URL is always permitted (eg. /student/login/<some code>)

all the others URLs from the same category must be redirected (eg. /student* to /student/loginPage)

and so on for all the other categories, eg:

/category1* > /category1/loginPage

/category2* > /category2/loginPage

I tried a lot using the SecurityFilterChain methods but the only thing I've achieved is to permit one single URL and lock all the others (there is no distinction between categories).

http
    .authorizeRequests()
        .antMatchers("/student/login/**").permitAll()
        .anyRequest().authenticated()
        .and()
    .formLogin()
        .loginPage("/generalLogin")
        .permitAll()
        .and()
    .httpBasic();
```

I found no way to substitute anyRequest() with the one I want.

Body:
I'm using Spring Boot 2.7.6 and I would like to secure my application in this way:

a single URL is always permitted (eg. /student/login/<some code>)

all the others URLs from the same category must be redirected (eg. /student* to /student/loginPage)

and so on for all the other categories, eg:

/category1* > /category1/loginPage

/category2* > /category2/loginPage

I tried a lot using the SecurityFilterChain methods but the only thing I've achieved is to permit one single URL and lock all the others (there is no distinction between categories).

http
    .authorizeRequests()
        .antMatchers("/student/login/**").permitAll()
        .anyRequest().authenticated()
        .and()
    .formLogin()
        .loginPage("/generalLogin")
        .permitAll()
        .and()
    .httpBasic();

I found no way to substitute anyRequest() with the one I want.


问:
React navigation params passing too slow
I am working on a screen which takes data through route.params.

```<code>const {
    prompt,
    isUpscaling,
    imageToBeUpscaled,
    useDefaultPrompts = true,
    isChallenge = false,
    challengeData = {},
    isCommunityPage,
  } = route.params;
</code>```

When navigating to this page, the params first being passed are actually the previous values. However, upon saving the file(thereby updating the state) the expected params load in.

I am using the params' data in a focusEffect function:

```<code> useFocusEffect(
    useCallback(() => {
      setIsLoading(true);
      setSafeAreaBackgroundColor("#1a1a1a");
      generateImage();
    }, [])
  );
</code>```

However, the original data being passed to this function are the old values. In short, the values being used are the previous route.params value from an old screen and not the new ones being passed in. The new params are being passed in but (I'm assuming) are not loading before the useFocusEffect is called. This results in the function using old data rather than new data.

How can I have the route.params data be updated when used in the useFocusEffect function?

Body:
I am working on a screen which takes data through route.params.

const {
    prompt,
    isUpscaling,
    imageToBeUpscaled,
    useDefaultPrompts = true,
    isChallenge = false,
    challengeData = {},
    isCommunityPage,
  } = route.params;

When navigating to this page, the params first being passed are actually the previous values. However, upon saving the file(thereby updating the state) the expected params load in.

I am using the params' data in a focusEffect function:

 useFocusEffect(
    useCallback(() => {
      setIsLoading(true);
      setSafeAreaBackgroundColor("#1a1a1a");
      generateImage();
    }, [])
  );

However, the original data being passed to this function are the old values. In short, the values being used are the previous route.params value from an old screen and not the new ones being passed in. The new params are being passed in but (I'm assuming) are not loading before the useFocusEffect is called. This results in the function using old data rather than new data.

How can I have the route.params data be updated when used in the useFocusEffect function?


问:
Send List from Angular to Spring
Iam trying to send an Object from angular to my spring to add a new product. The product has a list of prices and sizes. This is how it looks like in backend:

```<code>@Setter
@Getter
public class ProductDto {

    private Long id;

    private Long secondId;

    private String name;

    private String description;

    private MultipartFile img;

    private byte[] returnedImg;

    private Long categoryId;

    private String categoryName;

    private Long restaurantId;

    private Long userId;

    private List<SizePriceDto> sizePrices;

}
</code>```

Controller class:

```<code>   @PostMapping("product/{categoryId}/{restaurantId}/{userId}")
    public GeneralResponse addProduct(@PathVariable Long categoryId, @PathVariable Long restaurantId, @PathVariable Long userId, @ModelAttribute ProductDto productDto) {
        GeneralResponse response = new GeneralResponse();
        try {
            return restaurantService.addProduct(categoryId, restaurantId, userId, productDto);
        } catch (Exception ex) {
            response.setStatus(HttpStatus.BAD_REQUEST);
            response.setMessage("Sorry Something Wrong Happened.");
            return response;
        }
    }

</code>```

Frontend:

```<code>      this.sizes.controls.forEach((sizeGroup, index) => {
        sizesAndPrices.push({
          size: sizeGroup.get('size').value,
          price: sizeGroup.get('price').value
        });
      });
      formData.append('sizePrices', '[{"size":"30","price":343},{"size":"frefgv","price":343}]');

</code>```

And this is the error that i get when i submit the form in angular:

```<code>.w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors<EOL>Field error in object 'productDto' on field 'sizePrices': rejected value [[{"size":"34","price":2342},{"size":"f4ef","price":3434}]]; codes [typeMismatch.productDto.sizePrices,typeMismatch.sizePrices,typeMismatch.java.util.List,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [productDto.sizePrices,sizePrices]; arguments []; default message [sizePrices]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.List' for property 'sizePrices'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'com.restaurant.dto.SizePriceDto' for property 'sizePrices[0]': no matching editors or conversion strategy found]]

</code>```

SizePriceDto Class

```<code>@Getter
@Setter
public class SizePriceDto {
    private String size;
    private Long price;
}

</code>```

SizePrice Class:

```<code>@Entity
@Getter
@Setter
public class SizePrice {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String size;

    private Long price;

    @ManyToOne
    @JoinColumn(name = "product_id")
    private Product product;
}
</code>```

My request from angular:

https://i.postimg.cc/zfnXT4mT/image.png

I tried alot of methods but nothing works and i dont have any idea how to fix this error.

Title: Send List from Angular to Spring

Body:
Iam trying to send an Object from angular to my spring to add a new product. The product has a list of prices and sizes. This is how it looks like in backend:

@Setter
@Getter
public class ProductDto {

    private Long id;

    private Long secondId;

    private String name;

    private String description;

    private MultipartFile img;

    private byte[] returnedImg;

    private Long categoryId;

    private String categoryName;

    private Long restaurantId;

    private Long userId;

    private List<SizePriceDto> sizePrices;

}

Controller class:

   @PostMapping("product/{categoryId}/{restaurantId}/{userId}")
    public GeneralResponse addProduct(@PathVariable Long categoryId, @PathVariable Long restaurantId, @PathVariable Long userId, @ModelAttribute ProductDto productDto) {
        GeneralResponse response = new GeneralResponse();
        try {
            return restaurantService.addProduct(categoryId, restaurantId, userId, productDto);
        } catch (Exception ex) {
            response.setStatus(HttpStatus.BAD_REQUEST);
            response.setMessage("Sorry Something Wrong Happened.");
            return response;
        }
    }

Frontend:

      this.sizes.controls.forEach((sizeGroup, index) => {
        sizesAndPrices.push({
          size: sizeGroup.get('size').value,
          price: sizeGroup.get('price').value
        });
      });
      formData.append('sizePrices', '[{"size":"30","price":343},{"size":"frefgv","price":343}]');

And this is the error that i get when i submit the form in angular:

.w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors<EOL>Field error in object 'productDto' on field 'sizePrices': rejected value [[{"size":"34","price":2342},{"size":"f4ef","price":3434}]]; codes [typeMismatch.productDto.sizePrices,typeMismatch.sizePrices,typeMismatch.java.util.List,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [productDto.sizePrices,sizePrices]; arguments []; default message [sizePrices]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.List' for property 'sizePrices'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'com.restaurant.dto.SizePriceDto' for property 'sizePrices[0]': no matching editors or conversion strategy found]]

SizePriceDto Class

@Getter
@Setter
public class SizePriceDto {
    private String size;
    private Long price;
}

SizePrice Class:

@Entity
@Getter
@Setter
public class SizePrice {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String size;

    private Long price;

    @ManyToOne
    @JoinColumn(name = "product_id")
    private Product product;
}

My request from angular:

https://i.postimg.cc/zfnXT4mT/image.png

I tried alot of methods but nothing works and i dont have any idea how to fix this error.


问:
Indicating a candle before a reversal
I would like to see the candle before the reversal to trigger a long or short command there. Since Tradingview can only trigger an alarm in the next candle, there are a lot of bad trades even when the right candle is hit. All attempts to hit a candle before the reversal have failed. does anyone have an approach? Also, is there a way to filter out any double short and long signals between reversals?</p>
```<code>condition = close >= open

long_beding7 = condition
short_beding7 = not condition

plotshape(long_beding7, color = color.lime, style = shape.arrowup, text = "Buy", location = location.belowbar)
plotshape(short_beding7, color = color.red, style = shape.arrowdown, text = "Sell", location = location.abovebar)

</code>```

Title: Indicating a candle before a reversal

Body:
I would like to see the candle before the reversal to trigger a long or short command there. Since Tradingview can only trigger an alarm in the next candle, there are a lot of bad trades even when the right candle is hit. All attempts to hit a candle before the reversal have failed. does anyone have an approach? Also, is there a way to filter out any double short and long signals between reversals?

condition = close >= open

long_beding7 = condition
short_beding7 = not condition

plotshape(long_beding7, color = color.lime, style = shape.arrowup, text = "Buy", location = location.belowbar)
plotshape(short_beding7, color = color.red, style = shape.arrowdown, text = "Sell", location = location.abovebar)


问:
After updating Windows and Python to version 11, I started to have a problem stopping the driver after turning off the code
The problem is that if you turn off the code during the 10 seconds of sleep, the driver will not turn off. All of this happens if you add this line:</p>
```<code>(options.add_experimental_option('excludeSwitches', ['enable-logging']))
</code>```
```<code>from selenium import webdriver
from time import sleep
options= webdriver.ChromeOptions()
options.add_experimental_option('excludeSwitches', ['enable-logging'])
driver = webdriver.Chrome('chromedriver.exe', options=options)
driver.get ('https://www.google.com')
sleep(10)````
</code>```

Body:
The problem is that if you turn off the code during the 10 seconds of sleep, the driver will not turn off. All of this happens if you add this line:

(options.add_experimental_option('excludeSwitches', ['enable-logging']))

from selenium import webdriver
from time import sleep
options= webdriver.ChromeOptions()
options.add_experimental_option('excludeSwitches', ['enable-logging'])
driver = webdriver.Chrome('chromedriver.exe', options=options)
driver.get ('https://www.google.com')
sleep(10)````


问:
Passport authentication not finding local strategy
I am currently using passport to authenticate users for my application, however passport.authenticate does not call my local Passport Strategy.

Here is my auth.js which is where my endpoint is for the user to login.

auth.js

Here is Passport.js where my LocalStrategy is located.

passport.js pt1
passport.js pt2

The endpoint always returns the status 400 with the message "Hold up somethings off." because the User is always returned as false
Any help would be greatly appreciated!

I have tried deleting the code completely off of my local and redownloading it off of GitHub. This was a nuclear option but I couldn't think of anything else to do.


问:
ray.tune.error.TuneError: The Ray Tune run failed
This is from the ray package official code, it works well on Linux systems but appears some errors on windows. All of the ray version is 2.2.0.

import numpy as np

import ray
from ray import air, tune
from ray.air import session
from ray.air.integrations.wandb import setup_wandb
from ray.air.integrations.wandb import WandbLoggerCallback

def train_function(config):
    for i in range(30):
        loss = config["mean"] + config["sd"] * np.random.randn()
        session.report({"loss": loss})

def tune_with_callback():
    """Example for using a WandbLoggerCallback with the function API"""
    tuner = tune.Tuner(
        train_function,
        tune_config=tune.TuneConfig(
            metric="loss",
            mode="min"
        ),
        run_config=air.RunConfig(
            callbacks=[
                WandbLoggerCallback(project="Wandb_example")
            ]
        ),
        param_space={
            "mean": tune.grid_search([1, 2, 3, 4, 5]),
            "sd": tune.uniform(0.2, 0.8),
        },
    )
    tuner.fit()

if __name__ == '__main__':
    tune_with_callback()
```
<p>And this is printed log with running above python code:</p>
<p>2022-12-30 11:50:41,732 INFO worker.py:1538 -- Started a local Ray instance.<br />
2022-12-30 11:50:46,508 INFO wandb.py:250 -- Already logged into W&B.</p>
```Traceback (most recent call last):
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\site-packages\ray\tune\execution\trial_runner.py", line 928, in _wait_and_handle_event
    self._on_pg_ready(next_trial)
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\site-packages\ray\tune\execution\trial_runner.py", line 1018, in _on_pg_ready
    if not _start_trial(next_trial) and next_trial.status != Trial.ERROR:
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\site-packages\ray\tune\execution\trial_runner.py", line 1010, in _start_trial
    self._callbacks.on_trial_start(
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\site-packages\ray\tune\callback.py", line 317, in on_trial_start
    callback.on_trial_start(**info)
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\site-packages\ray\tune\logger\logger.py", line 135, in on_trial_start
    self.log_trial_start(trial)
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\site-packages\ray\air\integrations\wandb.py", line 527, in log_trial_start
    self._trial_processes[trial].start()
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\multiprocessing\process.py", line 121, in start
    self._popen = self._Popen(self)
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\multiprocessing\context.py", line 224, in _Popen
    return _default_context.get_context().Process._Popen(process_obj)
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\multiprocessing\context.py", line 327, in _Popen
    return Popen(process_obj)
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\multiprocessing\popen_spawn_win32.py", line 93, in __init__
    reduction.dump(process_obj, to_child)
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\multiprocessing\reduction.py", line 60, in dump
    ForkingPickler(file, protocol).dump(obj)
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\site-packages\ray\air\integrations\wandb.py", line 367, in __reduce__
    raise RuntimeError("_WandbLoggingProcess is not pickleable.")
RuntimeError: _WandbLoggingProcess is not pickleable.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\site-packages\ray\tune\tuner.py", line 272, in fit
    return self._local_tuner.fit()
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\site-packages\ray\tune\impl\tuner_internal.py", line 420, in fit
    analysis = self._fit_internal(trainable, param_space)
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\site-packages\ray\tune\impl\tuner_internal.py", line 532, in _fit_internal
    analysis = run(
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\site-packages\ray\tune\tune.py", line
726, in run
    runner.step()
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\site-packages\ray\tune\execution\trial_runner.py", line 981, in step
    self._wait_and_handle_event(next_trial)
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\site-packages\ray\tune\execution\trial_runner.py", line 960, in _wait_and_handle_event
    raise TuneError(traceback.format_exc())
ray.tune.error.TuneError: Traceback (most recent call last):
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\site-packages\ray\tune\execution\trial_runner.py", line 928, in _wait_and_handle_event
    self._on_pg_ready(next_trial)
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\site-packages\ray\tune\execution\trial_runner.py", line 1018, in _on_pg_ready
    if not _start_trial(next_trial) and next_trial.status != Trial.ERROR:
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\site-packages\ray\tune\execution\trial_runner.py", line 1010, in _start_trial
    self._callbacks.on_trial_start(
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\site-packages\ray\tune\callback.py", line 317, in on_trial_start
    callback.on_trial_start(**info)
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\site-packages\ray\tune\logger\logger.py", line 135, in on_trial_start
    self.log_trial_start(trial)
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\site-packages\ray\air\integrations\wandb.py", line 527, in log_trial_start
    self._trial_processes[trial].start()
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\multiprocessing\process.py", line 121, in start
    self._popen = self._Popen(self)
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\multiprocessing\context.py", line 224, in _Popen
    return _default_context.get_context().Process._Popen(process_obj)
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\multiprocessing\context.py", line 327, in _Popen
    return Popen(process_obj)
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\multiprocessing\popen_spawn_win32.py", line 93, in __init__
    reduction.dump(process_obj, to_child)
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\multiprocessing\reduction.py", line 60, in dump
    ForkingPickler(file, protocol).dump(obj)
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\site-packages\ray\air\integrations\wandb.py", line 367, in __reduce__
    raise RuntimeError("_WandbLoggingProcess is not pickleable.")
RuntimeError: _WandbLoggingProcess is not pickleable.

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\shaohan.tian\Desktop\laptop_python_run\wandb_test.py", line 36, in <module>
    tune_with_callback()
  File "C:\Users\shaohan.tian\Desktop\laptop_python_run\wandb_test.py", line 33, in tune_with_callback
    tuner.fit()
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\site-packages\ray\tune\tuner.py", line 274, in fit
    raise TuneError(
ray.tune.error.TuneError: The Ray Tune run failed. Please inspect the previous error messages for a cause. After
fixing the issue, you can restart the run from scratch or continue this run. To continue this run, you can use `tuner = Tuner.restore("C:\Users\shaohan.tian\ray_results\train_function_2022-12-30_11-50-36")`.
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\multiprocessing\spawn.py", line 116, in spawn_main
    exitcode = _main(fd, parent_sentinel)
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\multiprocessing\spawn.py", line 126, in _main
    self = reduction.pickle.load(from_parent)
EOFError: Ran out of input
```

I tried modifying versions of ray and wandb, but it was of no use. Could you help me to solve it?

Body:
This is from the ray package official code, it works well on Linux systems but appears some errors on windows. All of the ray version is 2.2.0.

import numpy as np

import ray
from ray import air, tune
from ray.air import session
from ray.air.integrations.wandb import setup_wandb
from ray.air.integrations.wandb import WandbLoggerCallback

def train_function(config):
    for i in range(30):
        loss = config["mean"] + config["sd"] * np.random.randn()
        session.report({"loss": loss})

def tune_with_callback():
    """Example for using a WandbLoggerCallback with the function API"""
    tuner = tune.Tuner(
        train_function,
        tune_config=tune.TuneConfig(
            metric="loss",
            mode="min"
        ),
        run_config=air.RunConfig(
            callbacks=[
                WandbLoggerCallback(project="Wandb_example")
            ]
        ),
        param_space={
            "mean": tune.grid_search([1, 2, 3, 4, 5]),
            "sd": tune.uniform(0.2, 0.8),
        },
    )
    tuner.fit()

if __name__ == '__main__':
    tune_with_callback()

And this is printed log with running above python code:

2022-12-30 11:50:41,732 INFO worker.py:1538 -- Started a local Ray instance.

2022-12-30 11:50:46,508 INFO wandb.py:250 -- Already logged into W&B.

Traceback (most recent call last):
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\site-packages\ray\tune\execution\trial_runner.py", line 928, in _wait_and_handle_event
    self._on_pg_ready(next_trial)
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\site-packages\ray\tune\execution\trial_runner.py", line 1018, in _on_pg_ready
    if not _start_trial(next_trial) and next_trial.status != Trial.ERROR:
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\site-packages\ray\tune\execution\trial_runner.py", line 1010, in _start_trial
    self._callbacks.on_trial_start(
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\site-packages\ray\tune\callback.py", line 317, in on_trial_start
    callback.on_trial_start(**info)
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\site-packages\ray\tune\logger\logger.py", line 135, in on_trial_start
    self.log_trial_start(trial)
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\site-packages\ray\air\integrations\wandb.py", line 527, in log_trial_start
    self._trial_processes[trial].start()
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\multiprocessing\process.py", line 121, in start
    self._popen = self._Popen(self)
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\multiprocessing\context.py", line 224, in _Popen
    return _default_context.get_context().Process._Popen(process_obj)
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\multiprocessing\context.py", line 327, in _Popen
    return Popen(process_obj)
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\multiprocessing\popen_spawn_win32.py", line 93, in __init__
    reduction.dump(process_obj, to_child)
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\multiprocessing\reduction.py", line 60, in dump
    ForkingPickler(file, protocol).dump(obj)
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\site-packages\ray\air\integrations\wandb.py", line 367, in __reduce__
    raise RuntimeError("_WandbLoggingProcess is not pickleable.")
RuntimeError: _WandbLoggingProcess is not pickleable.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\site-packages\ray\tune\tuner.py", line 272, in fit
    return self._local_tuner.fit()
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\site-packages\ray\tune\impl\tuner_internal.py", line 420, in fit
    analysis = self._fit_internal(trainable, param_space)
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\site-packages\ray\tune\impl\tuner_internal.py", line 532, in _fit_internal
    analysis = run(
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\site-packages\ray\tune\tune.py", line
726, in run
    runner.step()
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\site-packages\ray\tune\execution\trial_runner.py", line 981, in step
    self._wait_and_handle_event(next_trial)
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\site-packages\ray\tune\execution\trial_runner.py", line 960, in _wait_and_handle_event
    raise TuneError(traceback.format_exc())
ray.tune.error.TuneError: Traceback (most recent call last):
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\site-packages\ray\tune\execution\trial_runner.py", line 928, in _wait_and_handle_event
    self._on_pg_ready(next_trial)
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\site-packages\ray\tune\execution\trial_runner.py", line 1018, in _on_pg_ready
    if not _start_trial(next_trial) and next_trial.status != Trial.ERROR:
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\site-packages\ray\tune\execution\trial_runner.py", line 1010, in _start_trial
    self._callbacks.on_trial_start(
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\site-packages\ray\tune\callback.py", line 317, in on_trial_start
    callback.on_trial_start(**info)
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\site-packages\ray\tune\logger\logger.py", line 135, in on_trial_start
    self.log_trial_start(trial)
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\site-packages\ray\air\integrations\wandb.py", line 527, in log_trial_start
    self._trial_processes[trial].start()
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\multiprocessing\process.py", line 121, in start
    self._popen = self._Popen(self)
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\multiprocessing\context.py", line 224, in _Popen
    return _default_context.get_context().Process._Popen(process_obj)
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\multiprocessing\context.py", line 327, in _Popen
    return Popen(process_obj)
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\multiprocessing\popen_spawn_win32.py", line 93, in __init__
    reduction.dump(process_obj, to_child)
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\multiprocessing\reduction.py", line 60, in dump
    ForkingPickler(file, protocol).dump(obj)
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\site-packages\ray\air\integrations\wandb.py", line 367, in __reduce__
    raise RuntimeError("_WandbLoggingProcess is not pickleable.")
RuntimeError: _WandbLoggingProcess is not pickleable.

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\shaohan.tian\Desktop\laptop_python_run\wandb_test.py", line 36, in <module>
    tune_with_callback()
  File "C:\Users\shaohan.tian\Desktop\laptop_python_run\wandb_test.py", line 33, in tune_with_callback
    tuner.fit()
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\site-packages\ray\tune\tuner.py", line 274, in fit
    raise TuneError(
ray.tune.error.TuneError: The Ray Tune run failed. Please inspect the previous error messages for a cause. After
fixing the issue, you can restart the run from scratch or continue this run. To continue this run, you can use `tuner = Tuner.restore("C:\Users\shaohan.tian\ray_results\train_function_2022-12-30_11-50-36")`.
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\multiprocessing\spawn.py", line 116, in spawn_main
    exitcode = _main(fd, parent_sentinel)
  File "C:\Users\shaohan.tian\scoop\apps\miniconda3\current\envs\steel\lib\multiprocessing\spawn.py", line 126, in _main
    self = reduction.pickle.load(from_parent)
EOFError: Ran out of input

I tried modifying versions of ray and wandb, but it was of no use. Could you help me to solve it?


问:
How to do calculations with decimal separators in real time Kotlin
I'm making a program to calculate taxes, and I want to make the numbers typed in editText be separated in real time with decimal places (commas). Separate in decimal places both the numbers to be typed in the editText and the result that will be obtained after the calculations. Thanks!!!

Here is the code that does the respective calculations. KOTLIN...

```<code>package com.marianomuendane.contabiliadadeVocacional

import android.content.Intent
import android.content.res.Configuration
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import java.text.DecimalFormat
import java.text.DecimalFormatSymbols
import java.util.*

class IRPCFragment : Fragment() {

//variables for the respective calculations

    private lateinit var proveitos: EditText
    private lateinit var custos: EditText
    private lateinit var amortizacoes: EditText
    private lateinit var juros: EditText

    private lateinit var format: String
    private lateinit var decimal: DecimalFormat
    private lateinit var decimalSymbols: DecimalFormatSymbols

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        val view = inflater.inflate(R.layout.fragment_i_r_p_c, container, false)

        proveitos = view.findViewById(R.id.proveitos)

        proveitos.setRawInputType(Configuration.KEYBOARD_12KEY)

//decimal number attempt
        //proveitos.addTextChangedListener(editText1())

        decimalSymbols = DecimalFormatSymbols(Locale("pt", "Brazil"))
        decimalSymbols.setDecimalSeparator(',')
        decimalSymbols.setGroupingSeparator('.')

        format = "###,###,###,###.####"

        decimal = DecimalFormat(format)

        // EditText necessarios

        //==========================================================

        custos = view.findViewById<EditText>(R.id.custos)

        custos.setRawInputType(Configuration.KEYBOARD_12KEY)

        //==========================================================

        amortizacoes = view.findViewById<EditText>(R.id.amortizacoes)

        amortizacoes.setRawInputType(Configuration.KEYBOARD_12KEY)

        //==========================================================

        juros = view.findViewById(R.id.juros)

        juros.setRawInputType(Configuration.KEYBOARD_12KEY)

        //==========================================================

        val imposto = view.findViewById<TextView>(R.id.imposto)
        imposto.setTextIsSelectable(true)

        val bt4 = view.findViewById<Button>(R.id.res_final)
        val resolucao = view.findViewById<Button>(R.id.resolucao_Irpc)

        //======================================================================================

//function of calculations
        fun iRPC() =
            if (proveitos.text.isEmpty() && custos.text.isEmpty() && amortizacoes.text.isEmpty()
                && juros.text.isEmpty()
            ) {
                Toast.makeText(requireContext(), "Preencha os valores ", Toast.LENGTH_SHORT).show()

            } else if (proveitos.text.isEmpty()) {
                Toast.makeText(requireContext(), "Preencha proveitos", Toast.LENGTH_SHORT).show()

            } else if (custos.text.isEmpty()) {
                Toast.makeText(requireContext(), "Preencha custos", Toast.LENGTH_SHORT).show()

            } else if (amortizacoes.text.isEmpty()) {
                Toast.makeText(requireContext(), "Preencha amortizacoes", Toast.LENGTH_SHORT).show()

            } else if (juros.text.isEmpty()) {
                Toast.makeText(requireContext(), "Preencha juros", Toast.LENGTH_SHORT).show()

            } else {

                val prov = proveitos.text.toString().toFloat()
                val cust = custos.text.toString().toFloat()
                val amort = amortizacoes.text.toString().toFloat()
                val jur = juros.text.toString().toFloat()

                val result = (prov - cust - amort - jur) * 0.32
                val formatResult = decimal.format(result)

                imposto.setText(result.toString())
            }

        //======================================================================================

        bt4.setOnClickListener {
            iRPC()
        }

        return view
    }

}

</code>```

Body:
I'm making a program to calculate taxes, and I want to make the numbers typed in editText be separated in real time with decimal places (commas). Separate in decimal places both the numbers to be typed in the editText and the result that will be obtained after the calculations. Thanks!!!

Here is the code that does the respective calculations. KOTLIN...

package com.marianomuendane.contabiliadadeVocacional

import android.content.Intent
import android.content.res.Configuration
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import java.text.DecimalFormat
import java.text.DecimalFormatSymbols
import java.util.*

class IRPCFragment : Fragment() {

//variables for the respective calculations

    private lateinit var proveitos: EditText
    private lateinit var custos: EditText
    private lateinit var amortizacoes: EditText
    private lateinit var juros: EditText

    private lateinit var format: String
    private lateinit var decimal: DecimalFormat
    private lateinit var decimalSymbols: DecimalFormatSymbols

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        val view = inflater.inflate(R.layout.fragment_i_r_p_c, container, false)

        proveitos = view.findViewById(R.id.proveitos)

        proveitos.setRawInputType(Configuration.KEYBOARD_12KEY)

//decimal number attempt
        //proveitos.addTextChangedListener(editText1())

        decimalSymbols = DecimalFormatSymbols(Locale("pt", "Brazil"))
        decimalSymbols.setDecimalSeparator(',')
        decimalSymbols.setGroupingSeparator('.')

        format = "###,###,###,###.####"

        decimal = DecimalFormat(format)

        // EditText necessarios

        //==========================================================

        custos = view.findViewById<EditText>(R.id.custos)

        custos.setRawInputType(Configuration.KEYBOARD_12KEY)

        //==========================================================

        amortizacoes = view.findViewById<EditText>(R.id.amortizacoes)

        amortizacoes.setRawInputType(Configuration.KEYBOARD_12KEY)

        //==========================================================

        juros = view.findViewById(R.id.juros)

        juros.setRawInputType(Configuration.KEYBOARD_12KEY)

        //==========================================================

        val imposto = view.findViewById<TextView>(R.id.imposto)
        imposto.setTextIsSelectable(true)

        val bt4 = view.findViewById<Button>(R.id.res_final)
        val resolucao = view.findViewById<Button>(R.id.resolucao_Irpc)

        //======================================================================================

//function of calculations
        fun iRPC() =
            if (proveitos.text.isEmpty() && custos.text.isEmpty() && amortizacoes.text.isEmpty()
                && juros.text.isEmpty()
            ) {
                Toast.makeText(requireContext(), "Preencha os valores ", Toast.LENGTH_SHORT).show()

            } else if (proveitos.text.isEmpty()) {
                Toast.makeText(requireContext(), "Preencha proveitos", Toast.LENGTH_SHORT).show()

            } else if (custos.text.isEmpty()) {
                Toast.makeText(requireContext(), "Preencha custos", Toast.LENGTH_SHORT).show()

            } else if (amortizacoes.text.isEmpty()) {
                Toast.makeText(requireContext(), "Preencha amortizacoes", Toast.LENGTH_SHORT).show()

            } else if (juros.text.isEmpty()) {
                Toast.makeText(requireContext(), "Preencha juros", Toast.LENGTH_SHORT).show()

            } else {

                val prov = proveitos.text.toString().toFloat()
                val cust = custos.text.toString().toFloat()
                val amort = amortizacoes.text.toString().toFloat()
                val jur = juros.text.toString().toFloat()

                val result = (prov - cust - amort - jur) * 0.32
                val formatResult = decimal.format(result)

                imposto.setText(result.toString())
            }

        //======================================================================================

        bt4.setOnClickListener {
            iRPC()
        }

        return view
    }

}


问:
Text being cut off in jsPDF
I'm using the current code:

```<code>const generatePDF = () => {
  const input = document.getElementById("content");

  const pdf = new jspdf("p", "pt", "a4");

  var canvas = pdf.canvas;
  canvas.width = document.body.clientWidth;

  pdf.html(input, {
    callback: function (pdf) {
      pdf.save("mypdf.pdf");
    },
  });
};
</code>```

that's what's happening to my pdf

I would like my text to be rightly placed on the pdf

Title: Text being cut off in jsPDF

Body:
I'm using the current code:

const generatePDF = () => {
  const input = document.getElementById("content");

  const pdf = new jspdf("p", "pt", "a4");

  var canvas = pdf.canvas;
  canvas.width = document.body.clientWidth;

  pdf.html(input, {
    callback: function (pdf) {
      pdf.save("mypdf.pdf");
    },
  });
};

that's what's happening to my pdf

I would like my text to be rightly placed on the pdf


问:
why choosing http.createServer(app).listen(3000) over app.listen(3000)?
I start learning nodeJs and Express as a framework and I encounter that there are two way to create a server (as far as I know) that listen on a given port .The first one :

```<code>//assume that I already import the needed modules
var app = express();
//..
app.listen(3000);
</code>```

The second way is :

```<code>var app = express()
//..
http.createServer(app).listen(3000);
</code>```

My question is : is there any difference in term of performance between the two methods ?

Body:
I start learning nodeJs and Express as a framework and I encounter that there are two way to create a server (as far as I know) that listen on a given port .The first one :

//assume that I already import the needed modules
var app = express();
//..
app.listen(3000);

The second way is :

var app = express()
//..
http.createServer(app).listen(3000);

My question is : is there any difference in term of performance between the two methods ?


问:
Setting excel created date with your local time, instead of utc time via win32com in python
I'm trying to set the datetime via win32com, but it would keep setting it in UTC time, not in the local time zone that I would have set the time object(?) to.

import win32com.client as win32com
from win32com.client import constants as c
book = r'pathToExcel'
excel = win32com.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open(book, Local=True)
wb.BuiltinDocumentProperties["Creation date"] = pywintypes.Time(time.localtime())
wb.Close(SaveChanges=1)
```


问:
Necessity of importing <ios> header file in C++
I declared a float variable, say a, then I assigned 57.00 to it. When I wanted to print the 'a' using cout object, the stream seemed to print only 57 without the decimal point.

So, the solution to making the decimal point printed is adding showpoint manipulator after cout. Example: cout << showpoint << fixed << setprecision(2) << a << endl;

The function setprecision here is used together with fixed to specify the number of digits to be printed after the decimal point. After googling for a while, I found that showpoint and fixed are a part of <ios> header file.

So, why don't we have to import this header? Without importing it, the code worked just fine.
And importing <iostream> is all I need to make these stream manipulators worked as intended.

Is <ios> header automatically imported whenever and wherever the <iostream> header is imported?