问:
Starling / ActionScript 3 signaling events up to Main
Hi I have a little design Issue with Starling/ActionScript 3.

What I want to do is simple

```<code> dispatchEvent( new flash.events.Event("CloseApp",true)); //send closing bubble events
</code>```

while i have following methods in Main.as (main extends flash.display.Sprite)

```<code> public Main():void //constructor
 {
     addEventListener( "CloseApp" , onCloseApp);
     _starling = new Starling(Game, stage); //everythings work ok
     _starling.start(); //nice 3d stuff and interactive menu ok.
 }

 //closing event handling: close the APP
 public function onCloseApp( e:flash.events.Event): void
 {
     NativeApplication.nativeApplication.exit();
 }
</code>```

seems there's no way to send events to "Main" while all other classes are correctly catching events. basically the "exit" button is the only thing that does not work in my application.

答:
@Boris already explained that.

I have resolved problem.

Example I made File from flash.filesystem.File in App.as (My application was created by Moonshine) and TextInput from feathers.controls.TextInput; in Main.as with Starling's events

Like that:

```<code>package
{
    import Main;
    import feathers.utils.ScreenDensityScaleFactorManager;

    import flash.display.Loader;
    import flash.display.Sprite;
    import flash.display.StageAlign;
    import flash.display.StageOrientation;
    import flash.display.StageScaleMode;
    import flash.display3D.Context3DProfile;
    import flash.display3D.Context3DRenderMode;
    import flash.events.Event;
    import flash.filesystem.File;
    import flash.filesystem.FileMode;
    import flash.filesystem.FileStream;
    import flash.system.Capabilities;
    import flash.utils.ByteArray;

    import starling.core.Starling;
    import flash.net.FileFilter;

    [SWF(width="640",height="480",frameRate="60",backgroundColor="#4a4137")]
    public class NewFeathersSDKDesktopProject extends Sprite
    {
        public function NewFeathersSDKDesktopProject()
        {
            if(this.stage)
            {
                this.stage.scaleMode = StageScaleMode.NO_SCALE;
                this.stage.align = StageAlign.TOP_LEFT;
            }
            this.mouseEnabled = this.mouseChildren = false;
            this.showLaunchImage();
            this.loaderInfo.addEventListener(Event.COMPLETE, loaderInfo_completeHandler);
        }

        private var _starling:Starling;
        private var _scaler:ScreenDensityScaleFactorManager;
        private var _launchImage:Loader;
        private var _savedAutoOrients:Boolean;

        ...

        private function loaderInfo_completeHandler(event:Event):void
        {
            Starling.multitouchEnabled = true;
            this._starling = new Starling(Main, this.stage, null, null, Context3DRenderMode.AUTO, Context3DProfile.BASELINE);
            this._starling.supportHighResolutions = true;
            this._starling.skipUnchangedFrames = true;
            this._starling.start();
            if(this._launchImage)
            {
                this._starling.addEventListener("rootCreated", starling_rootCreatedHandler);
            }

            this._scaler = new ScreenDensityScaleFactorManager(this._starling);
            this.stage.addEventListener(Event.DEACTIVATE, stage_deactivateHandler, false, 0, true);

            // dispatch from Main.as dispatchEventWith();
            this._starling.addEventListener("trigger", button_triggeredHandler)
        }

        ...

        private var fileopen:File;
        public function button_triggeredHandler(event:Object):void
        {
            fileopen = new File();
            var txtFilter:FileFilter = new FileFilter("Text", "*.as;*.css;*.html;*.txt;*.xml");
            try
            {
                fileopen.browseForOpen("Open", [txtFilter]);
                fileopen.addEventListener(Event.SELECT, fileSelected)
            }
            catch (error:Error)
            {
                trace("Failed:", error.message);
            }
        }

        public function fileSelected(event:Event):void
        {
            Main.textinput.text = fileopen.nativePath;
        }

    }
}
</code>```

And Main.as

```<code>package
{
    import feathers.controls.Button;
    import feathers.controls.TextCallout;
    import feathers.themes.MetalWorksDesktopTheme;

    import starling.display.Sprite;
    import starling.core.Starling;
    import starling.events.Event;
    import feathers.core.Application;
    import feathers.controls.TextInput;

    public class Main extends Application
    {
        public function Main()
        {
            new MetalWorksDesktopTheme();
            super();

            this.addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
        }

        protected var button:Button;
        public static  var textinput:TextInput;

        protected function addedToStageHandler(event:Event):void
        {
            this.removeEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);

            this.button = new Button();
            this.button.label = "Choose";

            textinput = new TextInput();

            //an event that tells us when the user has tapped the button.
            this.button.addEventListener(Event.TRIGGERED, button_triggeredHandler);

            this.addChild(this.button);
            this.addChild(textinput);

            this.button.x = this.button.y = 10;
            textinput.x = 90;
            textinput.y = 10;
            textinput.width = 400;
        }

        private function button_triggeredHandler(event:Event):void
        {
            // Call to Application's class ( App or created by Moonshine IDE )
            Starling.current.dispatchEventWith("trigger");
        }
    }
}
</code>```

I hope you know how do you get like your air app works fine like charm :D

PS: I am really surprised why do Actionscript 3 developers continue until now?
I thought Flash Player is died. Since I exchange to Net developer - I don't expect there AS3 developers skip with Harman Air. I checked news - I am shocking why does company Harman continue and works hardly. I don't understand why does Harman release Linux with Commincial version :(. And successor Moonshine IDE. I find okay. but I wish dark mode on Moonshine IDE. Becuase my eyes are sensitive.

Body:
Hi I have a little design Issue with Starling/ActionScript 3.

What I want to do is simple

 dispatchEvent( new flash.events.Event("CloseApp",true)); //send closing bubble events

while i have following methods in Main.as (main extends flash.display.Sprite)

 public Main():void //constructor
 {
     addEventListener( "CloseApp" , onCloseApp);
     _starling = new Starling(Game, stage); //everythings work ok
     _starling.start(); //nice 3d stuff and interactive menu ok.
 }

 //closing event handling: close the APP
 public function onCloseApp( e:flash.events.Event): void
 {
     NativeApplication.nativeApplication.exit();
 }

seems there's no way to send events to "Main" while all other classes are correctly catching events. basically the "exit" button is the only thing that does not work in my application.

Body:
@Boris already explained that.

I have resolved problem.

Example I made File from flash.filesystem.File in App.as (My application was created by Moonshine) and TextInput from feathers.controls.TextInput; in Main.as with Starling's events

Like that:

package
{
    import Main;
    import feathers.utils.ScreenDensityScaleFactorManager;

    import flash.display.Loader;
    import flash.display.Sprite;
    import flash.display.StageAlign;
    import flash.display.StageOrientation;
    import flash.display.StageScaleMode;
    import flash.display3D.Context3DProfile;
    import flash.display3D.Context3DRenderMode;
    import flash.events.Event;
    import flash.filesystem.File;
    import flash.filesystem.FileMode;
    import flash.filesystem.FileStream;
    import flash.system.Capabilities;
    import flash.utils.ByteArray;

    import starling.core.Starling;
    import flash.net.FileFilter;

    [SWF(width="640",height="480",frameRate="60",backgroundColor="#4a4137")]
    public class NewFeathersSDKDesktopProject extends Sprite
    {
        public function NewFeathersSDKDesktopProject()
        {
            if(this.stage)
            {
                this.stage.scaleMode = StageScaleMode.NO_SCALE;
                this.stage.align = StageAlign.TOP_LEFT;
            }
            this.mouseEnabled = this.mouseChildren = false;
            this.showLaunchImage();
            this.loaderInfo.addEventListener(Event.COMPLETE, loaderInfo_completeHandler);
        }

        private var _starling:Starling;
        private var _scaler:ScreenDensityScaleFactorManager;
        private var _launchImage:Loader;
        private var _savedAutoOrients:Boolean;

        ...

        private function loaderInfo_completeHandler(event:Event):void
        {
            Starling.multitouchEnabled = true;
            this._starling = new Starling(Main, this.stage, null, null, Context3DRenderMode.AUTO, Context3DProfile.BASELINE);
            this._starling.supportHighResolutions = true;
            this._starling.skipUnchangedFrames = true;
            this._starling.start();
            if(this._launchImage)
            {
                this._starling.addEventListener("rootCreated", starling_rootCreatedHandler);
            }

            this._scaler = new ScreenDensityScaleFactorManager(this._starling);
            this.stage.addEventListener(Event.DEACTIVATE, stage_deactivateHandler, false, 0, true);

            // dispatch from Main.as dispatchEventWith();
            this._starling.addEventListener("trigger", button_triggeredHandler)
        }

        ...

        private var fileopen:File;
        public function button_triggeredHandler(event:Object):void
        {
            fileopen = new File();
            var txtFilter:FileFilter = new FileFilter("Text", "*.as;*.css;*.html;*.txt;*.xml");
            try
            {
                fileopen.browseForOpen("Open", [txtFilter]);
                fileopen.addEventListener(Event.SELECT, fileSelected)
            }
            catch (error:Error)
            {
                trace("Failed:", error.message);
            }
        }

        public function fileSelected(event:Event):void
        {
            Main.textinput.text = fileopen.nativePath;
        }

    }
}

And Main.as

package
{
    import feathers.controls.Button;
    import feathers.controls.TextCallout;
    import feathers.themes.MetalWorksDesktopTheme;

    import starling.display.Sprite;
    import starling.core.Starling;
    import starling.events.Event;
    import feathers.core.Application;
    import feathers.controls.TextInput;

    public class Main extends Application
    {
        public function Main()
        {
            new MetalWorksDesktopTheme();
            super();

            this.addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
        }

        protected var button:Button;
        public static  var textinput:TextInput;

        protected function addedToStageHandler(event:Event):void
        {
            this.removeEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);

            this.button = new Button();
            this.button.label = "Choose";

            textinput = new TextInput();

            //an event that tells us when the user has tapped the button.
            this.button.addEventListener(Event.TRIGGERED, button_triggeredHandler);

            this.addChild(this.button);
            this.addChild(textinput);

            this.button.x = this.button.y = 10;
            textinput.x = 90;
            textinput.y = 10;
            textinput.width = 400;
        }

        private function button_triggeredHandler(event:Event):void
        {
            // Call to Application's class ( App or created by Moonshine IDE )
            Starling.current.dispatchEventWith("trigger");
        }
    }
}

I hope you know how do you get like your air app works fine like charm :D

PS: I am really surprised why do Actionscript 3 developers continue until now?
I thought Flash Player is died. Since I exchange to Net developer - I don't expect there AS3 developers skip with Harman Air. I checked news - I am shocking why does company Harman continue and works hardly. I don't understand why does Harman release Linux with Commincial version :(. And successor Moonshine IDE. I find okay. but I wish dark mode on Moonshine IDE. Becuase my eyes are sensitive.


来源: stackexchange

问:
cumulative frequency column but resetting under a condition
I have a dataframe (on Python) with columns that contains the time and the number of products associated to an specific order.

I created a column that splits the time in intervals of 30 minutes (block of time) and then I counted the number of products on that specific Block of Time (using groupby).

Now I would like to add a cummulative frequency that restarts on every single block.

On this example, my new columns should be [2,3,3,5,7,...]

答:
You can calculate the cumsum for each group like this:

df.groupby('Block of Time')['N Products'].cumsum()
```
<p>Which yields the following result:</p>
```0    2
1    3
2    3
3    5
4    7
Name: N Products, dtype: int64
```

ContentLicense: CC BY-SA 4.0

Body:
You can calculate the cumsum for each group like this:

df.groupby('Block of Time')['N Products'].cumsum()

Which yields the following result:

0    2
1    3
2    3
3    5
4    7
Name: N Products, dtype: int64


问:
Comparing Dates with optional "comparison values"
I would like to compare the current date with the following optional variables which will be provided (multiple can be used): Year, Month, Day, Hours, Minutes, Seconds.

Possible comparison operators would be "before", "after" or "equals" - for single-variable comparisons a beforeOrEquals, afterOrEquals operator would be helpful as well.

Here are two examples how it would work:

If only the year is set, it would only check if the year is before/after the current year. If both the year and the month is set, it would consider both year and month in the comparisons.

The special thing with this comparison is if, for example, only the month is set, but not the year. In that case, the 21. February 2020 should be before the 21. March 2020 but AFTER the 21. January 2021.

For the current date, a LocalDateTime will be used. The comparison values (year, month etc.) are Integers. If they are -1, they should not be compared (= they are not provided).

This is how I'm currently doing the comparison:

    public final boolean compare(){
        //These values will need to be changed accordingly before the comparison. I have my own way of letting the user provide them as input.
        int year = -1;
        int month = -1;
        int day = -1;
        int hours = -1;
        int minutes = -1;
        int seconds = -1;
        String operation = "";
        String timeZone = null;

        final LocalDateTime currentTime = timeZone == null ? LocalDateTime.now() : LocalDateTime.now(timeZone.toZoneId());

        final LocalDateTime timeToCompare = LocalDateTime.of(
                year > -1 ? year  : currentTime.getYear(),
                month > -1 ? month : currentTime.getMonthValue(),
                day > -1 ? day : currentTime.getDayOfMonth(),
                hours > -1 ? hours : currentTime.getHour(),
                minutes > -1 ? minutes : currentTime.getMinute(),
                seconds > -1 ? seconds : currentTime.getSecond()
        );

        if(operation.equals("before")){
            if(!currentTime.isBefore(timeToCompare)){
                return false;
            }
        } else if(operation.equals("after")){
            if(!currentTime.isAfter(timeToCompare)){
                return false;
            }
        }
        return true;
    }
```

Is this a good way of implementing it, or is there a more performant way, since not every variable needs to be compared at all?

答:
I would apply the KISS principle:</p>
```<code>record PartialDateTime (Integer year, Integer month, Integer day, Integer hour, Integer minute, Integer second)
        implements Comparable<PartialDateTime> {

    public int compareTo(PartialDateTime other) {
        // your impl here
    }

    public boolean isBefore(PartialDateTime other) {
        return compareTo(other) < 0;
    }

    // etc for other truthy comparison methods
}
</code>```

Body:
I would like to compare the current date with the following optional variables which will be provided (multiple can be used): Year, Month, Day, Hours, Minutes, Seconds.

Possible comparison operators would be "before", "after" or "equals" - for single-variable comparisons a beforeOrEquals, afterOrEquals operator would be helpful as well.

Here are two examples how it would work:

If only the year is set, it would only check if the year is before/after the current year. If both the year and the month is set, it would consider both year and month in the comparisons.

The special thing with this comparison is if, for example, only the month is set, but not the year. In that case, the 21. February 2020 should be before the 21. March 2020 but AFTER the 21. January 2021.

For the current date, a LocalDateTime will be used. The comparison values (year, month etc.) are Integers. If they are -1, they should not be compared (= they are not provided).

This is how I'm currently doing the comparison:

    public final boolean compare(){
        //These values will need to be changed accordingly before the comparison. I have my own way of letting the user provide them as input.
        int year = -1;
        int month = -1;
        int day = -1;
        int hours = -1;
        int minutes = -1;
        int seconds = -1;
        String operation = "";
        String timeZone = null;

        final LocalDateTime currentTime = timeZone == null ? LocalDateTime.now() : LocalDateTime.now(timeZone.toZoneId());

        final LocalDateTime timeToCompare = LocalDateTime.of(
                year > -1 ? year  : currentTime.getYear(),
                month > -1 ? month : currentTime.getMonthValue(),
                day > -1 ? day : currentTime.getDayOfMonth(),
                hours > -1 ? hours : currentTime.getHour(),
                minutes > -1 ? minutes : currentTime.getMinute(),
                seconds > -1 ? seconds : currentTime.getSecond()
        );

        if(operation.equals("before")){
            if(!currentTime.isBefore(timeToCompare)){
                return false;
            }
        } else if(operation.equals("after")){
            if(!currentTime.isAfter(timeToCompare)){
                return false;
            }
        }
        return true;
    }

Is this a good way of implementing it, or is there a more performant way, since not every variable needs to be compared at all?

Body:
I would apply the KISS principle:

record PartialDateTime (Integer year, Integer month, Integer day, Integer hour, Integer minute, Integer second)
        implements Comparable<PartialDateTime> {

    public int compareTo(PartialDateTime other) {
        // your impl here
    }

    public boolean isBefore(PartialDateTime other) {
        return compareTo(other) < 0;
    }

    // etc for other truthy comparison methods
}


问:
SwiftUI View to NSImage in AppKit
SwiftUI 2.0 | Swift 5.4 | Xcode 12.4 | macOS Big Sur 11.4

In iOS there is a way to render SwiftUI views to a UIImage that doesn't work in AppKit, only UIKit:

```<code>extension View {
    func snapshot() -> UIImage {
        let controller = UIHostingController(rootView: self)
        let view = controller.view

        let targetSize = controller.view.intrinsicContentSize
        view?.bounds = CGRect(origin: .zero, size: targetSize)
        view?.backgroundColor = .clear

        let renderer = UIGraphicsImageRenderer(size: targetSize)

        return renderer.image { _ in
            view?.drawHierarchy(in: controller.view.bounds, afterScreenUpdates: true)
        }
    }
}
</code>```

Is there any workaround to get that working on AppKit? The method UIGraphicsImageRenderer(size:) doesn't work on AppKit and there is no equivalent.

答:
If I'm understanding your question correctly, you should be able to use an NSBitmapImageRef to do the trick!

Here's a simple example of generating an NSImage from SwiftUI view (Note: your host view must be visible!):

let view = MyView() // some SwiftUI view
let host = NSHostingView(rootView: view)

// Note: the host must be visible on screen, which I am guessing you already have it that way. If not, do that here.

let bitmapRep = host.bitmapImageRepForCachingDisplay(in: host.bounds)
host.cacheDisplay(in: host.bounds, to: bitmapRep!)

let image = NSImage(size: host.frame.size)
image.addRepresentation(bitmapRep!)
```
<p>Here's an extension to <code>NSHostingView</code> that should safely make snapshots:</p>
<pre class="lang-swift prettyprint-override"><code>extension NSHostingView {
    func snapshot() -> NSImage? {
        // Make sure the view is visible:
        guard self.window != nil else { return nil }

        // Get bitmap data:
        let bitmapRep = self.bitmapImageRepForCachingDisplay(in:
        self.bounds)
        self.cacheDisplay(in: self.bounds, to: bitmapRep!)

        // Create NSImage from NSBitmapImageRep:
        let image = NSImage(size: self.frame.size)
        image.addRepresentation(bitmapRep!)

        return image
    }
}
</code>```

I hope this helps. Let me know if you have any questions!

Title: SwiftUI View to NSImage in AppKit

Body:
SwiftUI 2.0 | Swift 5.4 | Xcode 12.4 | macOS Big Sur 11.4

In iOS there is a way to render SwiftUI views to a UIImage that doesn't work in AppKit, only UIKit:

extension View {
    func snapshot() -> UIImage {
        let controller = UIHostingController(rootView: self)
        let view = controller.view

        let targetSize = controller.view.intrinsicContentSize
        view?.bounds = CGRect(origin: .zero, size: targetSize)
        view?.backgroundColor = .clear

        let renderer = UIGraphicsImageRenderer(size: targetSize)

        return renderer.image { _ in
            view?.drawHierarchy(in: controller.view.bounds, afterScreenUpdates: true)
        }
    }
}

Is there any workaround to get that working on AppKit? The method UIGraphicsImageRenderer(size:) doesn't work on AppKit and there is no equivalent.

Body:
If I'm understanding your question correctly, you should be able to use an NSBitmapImageRef to do the trick!

Here's a simple example of generating an NSImage from SwiftUI view (Note: your host view must be visible!):

let view = MyView() // some SwiftUI view
let host = NSHostingView(rootView: view)

// Note: the host must be visible on screen, which I am guessing you already have it that way. If not, do that here.

let bitmapRep = host.bitmapImageRepForCachingDisplay(in: host.bounds)
host.cacheDisplay(in: host.bounds, to: bitmapRep!)

let image = NSImage(size: host.frame.size)
image.addRepresentation(bitmapRep!)

Here's an extension to NSHostingView that should safely make snapshots:

extension NSHostingView {
    func snapshot() -> NSImage? {
        // Make sure the view is visible:
        guard self.window != nil else { return nil }

        // Get bitmap data:
        let bitmapRep = self.bitmapImageRepForCachingDisplay(in:
        self.bounds)
        self.cacheDisplay(in: self.bounds, to: bitmapRep!)

        // Create NSImage from NSBitmapImageRep:
        let image = NSImage(size: self.frame.size)
        image.addRepresentation(bitmapRep!)

        return image
    }
}

I hope this helps. Let me know if you have any questions!


问:
How would I split a string by number of characters using getline?
Is there a way to take in a specified number of characters using cin or getline from a txt file and stop reading once the character limit is reached? I would like to read exactly 15 characters from a text file without stopping at any blank spaces or other delimiting characters.

```<code>ifstream inFile;

inFile.open("file.txt");

string sname;

//this is what I put at the moment but I don't believe it serves the purpose of what I'm looking for
cin >> setw(15) >> sname;
</code>```

I went through previously posted questions but I couldn't find a clear answer.

答:
I don't think you can do that with getline() or cin,
but this should works:

#include <fstream>
#include <string>

int main()
{
    std::ifstream inFile;
    inFile.open("file.txt");

    std::string sname;
    sname.resize(15);
    inFile.read(&sname[0], 15 * sizeof(char));
}
```

Body:
Is there a way to take in a specified number of characters using cin or getline from a txt file and stop reading once the character limit is reached? I would like to read exactly 15 characters from a text file without stopping at any blank spaces or other delimiting characters.

ifstream inFile;

inFile.open("file.txt");

string sname;

//this is what I put at the moment but I don't believe it serves the purpose of what I'm looking for
cin >> setw(15) >> sname;

I went through previously posted questions but I couldn't find a clear answer.


问:
efficient way to change values in existing golang slice?
I have a slice of a struct like:

```<code>type Car struct {
    name  string
    price int
    color string
}

cars := make([]Car, 0)
</code>```

The slice gets filled with values and later I want to loop over the the slice and change one specific value (price) again. Currently I do it like:

```<code>for i := range cars {
        cars[i].price = 10
}
</code>```

I've read that the performance of accessing a slice over it's index isn't great, when dealing with big slices. Would it (performance wise) be better to create a secound slice and copy the values like:

```<code>newCars := make([]Car, 0)

for _, car := range cars {
    newCar := car
    newCar.price = 10

    newCars = append(newCars, newCar)
}
</code>```

答:
I've read that the performance of accessing a slice over it's index isn't great, when dealing with big slices. Would it (performance wise) be better to create a [second] slice and copy the values...

NO.

A slice is a [thin] window on top of an underlying array. An array is a contiguous block of member. The cost of accessing an array element by index is trivial. It's just a bit of multiplication and 1 addition under the covers.

To copy the slice to a new empty slice requires at least one memory allocation (and possible more), plus copying memory.

Body:
I have a slice of a struct like:

type Car struct {
    name  string
    price int
    color string
}

cars := make([]Car, 0)

The slice gets filled with values and later I want to loop over the the slice and change one specific value (price) again. Currently I do it like:

for i := range cars {
        cars[i].price = 10
}

I've read that the performance of accessing a slice over it's index isn't great, when dealing with big slices. Would it (performance wise) be better to create a secound slice and copy the values like:

newCars := make([]Car, 0)

for _, car := range cars {
    newCar := car
    newCar.price = 10

    newCars = append(newCars, newCar)
}


问:
Spring boot application is not getting installed when 2 jvm are running on Unix server
I have 2 application both are connected to DB2 using jndi and are installed on same jboss location but on different JVM. both are having different jndi name as well but it's connected to same db and same user.

While starting server if one app is up, we are unable to install 2nd application.

Can this be spring boot DB2 connectivity issue? Or configuration of servers are not proper.

My question may not be properly understandable as I am posting anything for the first time here.

答:
Was able to fixed this issue cause,
Issue was we were not mentioning any initialSize in Jndi datasource and it was taking by Default value which is 10.
And at Db side we have restriction that only 30 connection can be established, since we were able to bring 4th appliup which means we were trying to create 10 more connections (30 already created by other 3 application) db was getting locked and it wasn't allowing us to deploy the code.</p>


问:
Cookies sent from backend but not set correctly on frontend
I'm running into this issue:

localhost:3000 (React App)

localhost:9000 (Nodejs Backend)

I was able to send the request from postman and receive the cookies there, however in the frontend when I check for the cookies in the browser there is nothing.

The cookies are not visible under the Application > Cookies tab.

The code I use for handing signups and sending the cookie:

```<code>// requirements
const User = require('../models/User');
const jwt = require('jsonwebtoken');

// handle errors
const handleErrors = (err) => {
    console.log(err.message, err.code);
    let errors = { first_name: '', last_name: '', email: '', password: '' };

    // duplicate error code
    if (err.code === 11000) {
        errors.email = 'That email is already registered';
        return errors;
    }

    // validation errors
    if (err.message.includes('User validation failed')) {
        Object.values(err.errors).forEach(({ properties }) => {
            errors[properties.path] = properties.message;
        });
    }
    return errors;
}

const maxAge = 3 * 24 * 60 * 60;
const createToken = (id) => {
    return jwt.sign({ id }, 'Dummy Secret', {
        expiresIn: maxAge
    });
}

// module exporting

module.exports.signup_post = async (req, res) => {
    const { first_name, last_name, email, password } = req.body;

    try {
        const user = await User.create({ first_name, last_name, email, password });
        const token = createToken(user._id);
        res.cookie('jwt', token, { httpOnly: true, maxAge: maxAge * 1000 });
        res.status(201).json({ user: user._id });
    }
    catch (err) {
        const errors = handleErrors(err);
        res.status(400).json({ errors });
    }
};
</code>```

If anyone could guide me on what to do I'd be grateful

UPDATE:
I did some testing and the results were as follows:
when I ran this code in the main app.js on the backend and send a request from the front end, the cookies were still messed up, so it might very well be the frontend.

```<code>app.get('/set-cookies', (req, res) => {
    res.cookie('newUesr', false);
    res.cookie('isEmployee', true, { maxAge: 1000 * 60 * 60 * 24, httpOnly: true});

    res.send('you got the cookies!');
});

app.get('/read-cookies', (req, res) => {
const

});
</code>```

But when I do it through my controllers in the previously shown code it gets stuck in set cookies as shown in this picture

答:
I was able to solve the issue by doing those steps:

Making sure the fetch request has the withCredntials: true and credentials: 'include', so the fetch request would be like this:

```<code>    fetch("http://localhost:9000/testAPI", {
                withCredntials: true,
                credentials: 'include'
    })
</code>```

Keep in mind this is only working with GET requests not POST requests without the 2nd step.

For POST requests being blocked by cors, just make sure you have this line in your backend after you've required cors of course app.use(cors({credentials: true, origin: true}));
using * or http://localhost:3000 (regardless of port number) instead of true seems to give the error.

NOTE:
According to @ikhvjs the withCredntials: true is not required, however I'm yet to try this so try at your own risk.

Thank you all for the help :D

Body:
I'm running into this issue:

localhost:3000 (React App)

localhost:9000 (Nodejs Backend)

I was able to send the request from postman and receive the cookies there, however in the frontend when I check for the cookies in the browser there is nothing.

The cookies are not visible under the Application > Cookies tab.

The code I use for handing signups and sending the cookie:

// requirements
const User = require('../models/User');
const jwt = require('jsonwebtoken');

// handle errors
const handleErrors = (err) => {
    console.log(err.message, err.code);
    let errors = { first_name: '', last_name: '', email: '', password: '' };

    // duplicate error code
    if (err.code === 11000) {
        errors.email = 'That email is already registered';
        return errors;
    }

    // validation errors
    if (err.message.includes('User validation failed')) {
        Object.values(err.errors).forEach(({ properties }) => {
            errors[properties.path] = properties.message;
        });
    }
    return errors;
}

const maxAge = 3 * 24 * 60 * 60;
const createToken = (id) => {
    return jwt.sign({ id }, 'Dummy Secret', {
        expiresIn: maxAge
    });
}

// module exporting

module.exports.signup_post = async (req, res) => {
    const { first_name, last_name, email, password } = req.body;

    try {
        const user = await User.create({ first_name, last_name, email, password });
        const token = createToken(user._id);
        res.cookie('jwt', token, { httpOnly: true, maxAge: maxAge * 1000 });
        res.status(201).json({ user: user._id });
    }
    catch (err) {
        const errors = handleErrors(err);
        res.status(400).json({ errors });
    }
};

If anyone could guide me on what to do I'd be grateful

UPDATE:
I did some testing and the results were as follows:
when I ran this code in the main app.js on the backend and send a request from the front end, the cookies were still messed up, so it might very well be the frontend.

app.get('/set-cookies', (req, res) => {
    res.cookie('newUesr', false);
    res.cookie('isEmployee', true, { maxAge: 1000 * 60 * 60 * 24, httpOnly: true});

    res.send('you got the cookies!');
});

app.get('/read-cookies', (req, res) => {
const

});

But when I do it through my controllers in the previously shown code it gets stuck in set cookies as shown in this picture

Body:
I was able to solve the issue by doing those steps:

Making sure the fetch request has the withCredntials: true and credentials: 'include', so the fetch request would be like this:

    fetch("http://localhost:9000/testAPI", {
                withCredntials: true,
                credentials: 'include'
    })

Keep in mind this is only working with GET requests not POST requests without the 2nd step.

For POST requests being blocked by cors, just make sure you have this line in your backend after you've required cors of course app.use(cors({credentials: true, origin: true}));
using * or http://localhost:3000 (regardless of port number) instead of true seems to give the error.

NOTE:
According to @ikhvjs the withCredntials: true is not required, however I'm yet to try this so try at your own risk.

Thank you all for the help :D


问:
Buttons are not spaced with css present
I'm having a problem with buttons in CSS.

Between the first two I get the right distance, but between the second and the third I get two buttons joined (attached) (as in the picture).

How can I solve this problem?

.buttons {
  display: flex;
}

.buttons form {
  margin: 0 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="buttons">
  <form action="createArt.html">
    <input type="submit" value="ADD" />
  </form>
  <input type="button" value="EDIT" onclick="confirmation_edit()" />
  <input type="button" value="DELETE" onclick="confirmation_delete()" />
</div></code>```

答:
As an option it is suitable for small projects, but for a larger project I recommend using classes.
To add styles to an element you can use: element Selector, id Selector, class Selector.
More information can be found here

.buttons {
  display: flex;
}

.buttons form {
  margin: 0 10px;
}
input:nth-child(2){
  margin: 0 10px 0 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="buttons">
  <form action="createArt.html">
    <input type="submit" value="ADD" />
  </form>

  <input type="button" value="EDIT" onclick="confirmation_edit()" />
  <input type="button" value="DELETE" onclick="confirmation_delete()" />
</div></code>```

Title: Buttons are not spaced with css present

Body:
I'm having a problem with buttons in CSS.

Between the first two I get the right distance, but between the second and the third I get two buttons joined (attached) (as in the picture).

How can I solve this problem?

.buttons {
  display: flex;
}

.buttons form {
  margin: 0 10px;
}

  <form action="createArt.html">
    <input type="submit" value="ADD" />
  </form>
  <input type="button" value="EDIT" onclick="confirmation_edit()" />
  <input type="button" value="DELETE" onclick="confirmation_delete()" />

Body:
As an option it is suitable for small projects, but for a larger project I recommend using classes.
To add styles to an element you can use: element Selector, id Selector, class Selector.
More information can be found here

.buttons {
  display: flex;
}

.buttons form {
  margin: 0 10px;
}
input:nth-child(2){
  margin: 0 10px 0 0;
}

<div class="buttons">
  <form action="createArt.html">
    <input type="submit" value="ADD" />
  </form>

  <input type="button" value="EDIT" onclick="confirmation_edit()" />
  <input type="button" value="DELETE" onclick="confirmation_delete()" />
</div>


问:
Data Formatting and Fixing
I am trying to clean user reviews which they are crawled in the web. When I try to read on the pandas. There is no warning or error. Then print the lenght of the dataframe.

Then I would like to apply normalization step. But I am focusing on Turkish language,so I cannot use python library. I will use third party software.

For this purpose, I am trying to write reviews columns to text file. When I write to these data text file lenght of the sample is

and target size:

Basically I do this:

Note: As I mentioned these are the customer reviews, as we expected they are dirty and noisy. Some of the samples contains many enter characters such as approximately 56 of the sample contains "\n\n\n\n". I have tried solve this problem in python by cleaning data but every time I am losing sample. Also I tried to fix it on Excel, it did not work.

Question: Do you have any suggestion for fixing data?

答:
It seems that you are producing two CSVs files from your df and then read them back as reviews and targets.

If you use pd.read_csv to read them back, pd.read_csv has this argument skip_blank_lines=True by default which skips blank lines. If some rows of your original df contains only a number of '\n', then it will end up with an empty line in your new CSVs which will be skipped the next time they get read.

You can verify this by setting up two counter variables for the total number of empty lines and see if that matches with the 'loss'.

```<code>num_empty_review = 0
num_empty_target = 0

for ..., ... in df.iterrows():
    review = ...replace('\n', '')
    target = ...replace('\n', '')
    if review.replace(' ', '') == '':
        num_empty_review += 1
    if target.replace(' ', '') == '':
        num_empty_target += 1
    ...
    ...
print(num_empty_review, num_empty_target)
</code>```

Lastly, next time, please paste your code here in text form like what I did in above :)

Title: Data Formatting and Fixing

Body:
It seems that you are producing two CSVs files from your df and then read them back as reviews and targets.

If you use pd.read_csv to read them back, pd.read_csv has this argument skip_blank_lines=True by default which skips blank lines. If some rows of your original df contains only a number of '\n', then it will end up with an empty line in your new CSVs which will be skipped the next time they get read.

You can verify this by setting up two counter variables for the total number of empty lines and see if that matches with the 'loss'.

num_empty_review = 0
num_empty_target = 0

for ..., ... in df.iterrows():
    review = ...replace('\n', '')
    target = ...replace('\n', '')
    if review.replace(' ', '') == '':
        num_empty_review += 1
    if target.replace(' ', '') == '':
        num_empty_target += 1
    ...
    ...
print(num_empty_review, num_empty_target)

Lastly, next time, please paste your code here in text form like what I did in above :)


问:
How to compare pandas data frames and then "fill in" any missing rows with the other data frame
I have the following two arrays: Data and Baseline

```<code>Data
   Phase  ENSO  EJO
0      1    -1    2
1      1     0    2
2      1     1    2
3      2    -1    7
4      2     1    1

Baseline
   Phase  ENSO  EJO
0      1    -1    0.0
1      1     0    0.0
2      1     1    0.0
3      2    -1    0.0
4      2     0    0.0
5      2     1    0.0
</code>```

I want to alter the 'Data' data frame such that the "missing row" gets filled in by the Baseline data. Final result would look like this

```<code>Data
   Phase  ENSO  EJO
0      1    -1    2
1      1     0    2
2      1     1    2
3      2    -1    7
4      2     0    0
5      2     1    1
</code>```

答:
I made the assumption that you want to decide which rows need to be filled based on the values of Phase and ENSO columns. Here is my solution based on that.

import os
import pandas as pd
import numpy as np
from io import StringIO

x_str = """Phase  ENSO  EJO
0      1    -1    2
1      1     0    2
2      1     1    2
3      2    -1    7
4      2     1    1"""

y_str = """Phase  ENSO  EJO
0      1    -1    0.0
1      1     0    0.0
2      1     1    0.0
3      2    -1    0.0
4      2     0    0.0
5      2     1    0.0"""

x = pd.read_csv(StringIO(x_str), sep="\s+")
y = pd.read_csv(StringIO(y_str), sep="\s+")

# Outer merge with indicator on
z = pd.merge(x, y, how='outer', on=['Phase', 'ENSO'], indicator=True)
rows_to_be_filled = z['_merge'].isin(['right_only'])
z.loc[rows_to_be_filled, 'EJO_x'] = z.loc[rows_to_be_filled, 'EJO_y']

# Cleanup
z = z.rename({'EJO_x': 'EJO'}, axis=1).drop(['EJO_y', '_merge'], axis=1)
z
#    Phase  ENSO  EJO
# 0      1    -1  2.0
# 1      1     0  2.0
# 2      1     1  2.0
# 3      2    -1  7.0
# 4      2     1  1.0
# 5      2     0  0.0
```

Body:
I have the following two arrays: Data and Baseline

Data
   Phase  ENSO  EJO
0      1    -1    2
1      1     0    2
2      1     1    2
3      2    -1    7
4      2     1    1

Baseline
   Phase  ENSO  EJO
0      1    -1    0.0
1      1     0    0.0
2      1     1    0.0
3      2    -1    0.0
4      2     0    0.0
5      2     1    0.0

I want to alter the 'Data' data frame such that the "missing row" gets filled in by the Baseline data. Final result would look like this

Data
   Phase  ENSO  EJO
0      1    -1    2
1      1     0    2
2      1     1    2
3      2    -1    7
4      2     0    0
5      2     1    1


问:
Apache: how to limit virtual dir to local network
On my Apache 2.x server at home, I have a number of virtual directories.  I've set up my router so that I can access Apache from the internet.  I need to keep one of those virtual dirs (/private) from being accessed outside my home network LAN.  So given /private,  how do I configure Apache to only serve requests to /private from 192.168.4.x?</p>

答:
```<code><Directory /users/me/private>
    Order deny,allow
    Allow from 192.168.4
    Deny from all
</Directory>
</code>```

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: chaos

OwnerDisplayName: chaos


问:
How to read thread dump?

Possible Duplicate:

  Thread Dump Analysis Tool / Method

I have a java aplication deployed in WAS 7.0.0.15. I want to analyze that the application which i have deployed is having some threads in hung state or not. So i want to take thread dump of server with and without application deployed. I used wsadmin for taking dump but not able to interpret the dump file.

Can any one help here ? also, let me know other methods of taking thread dump.

答:
I use the IBM Support Assistant (ISA), which is IBM:s tool. From it, you can download plugins for a bunch of different analysis activities. I use the plugin called "IBM Thread and Monitor Dump Analyzer for Java (TMDA)" for thread dump analysis.

Note: I'm using it for WAS 6.1 but AFAIK it should work for WAS 7 just as fine.

ContentLicense: CC BY-SA 3.0

Title: How to read thread dump?


问:
Postgresql: No connection could be made because the target machine actively refused it
Running Postgresql 9.5 on a windows server 2012 R2 in Azure

While running some loadtests on my application, I get errors on not being able to connect to the postgres server. In the logs of postgres I get the following message:

could not receive data from client: No connection could be made
  because the target machine actively refused it.

This only happens when the loadtest goes to the next scenario, hitting a different part of the code. So new connections to the database are required. But after 10-20 seconds the rest of the scenario works flawlessly without hitting any other hiccups. So the problem seems to be the tcp connections. (My code retries a couple of times but it is not feasible to let it retry for 20 seconds)

I'm using the following settings in the config files

postgresql.conf

```<code>listen_addresses = '*'
max_connections = 500
shared_buffers = 1024MB
temp_buffers = 2MB
work_mem = 2MB
maintenance_work_mem = 128MB
</code>```

pg_hba.conf

```<code>host    all             all             0.0.0.0/0               trust
host    all             all             ::/0                    trust
</code>```

I know, I know.. It is not save to accept connections from everyone, but this is just for testing purposes and to make sure these settings are not blocking any connection. So this answer is void

I've been monitoring the number of connection on the server and under the load it is stable at 75. Postgres is using around 350mb of RAM. So given the config and the vm specs (7gb ram) there should be plenty of space to create more connections. However when the next scenario is spinning up the number of connections does not increase, it stays level and starts giving these log messages about no connection could be made.

What could be the problem here?

答:
I came across a similar issue whilst trying to beast my api, where I was seeing Npgsql.NpgsqlException No connection could be made because the target machine actively refused it..

However my issue was was down to the fact that I was re-creating my NpgsqlConnection for each query rather than re-using and keeping it alive.

Body:
Running Postgresql 9.5 on a windows server 2012 R2 in Azure

While running some loadtests on my application, I get errors on not being able to connect to the postgres server. In the logs of postgres I get the following message:

could not receive data from client: No connection could be made
  because the target machine actively refused it.

This only happens when the loadtest goes to the next scenario, hitting a different part of the code. So new connections to the database are required. But after 10-20 seconds the rest of the scenario works flawlessly without hitting any other hiccups. So the problem seems to be the tcp connections. (My code retries a couple of times but it is not feasible to let it retry for 20 seconds)

I'm using the following settings in the config files

postgresql.conf

listen_addresses = '*'
max_connections = 500
shared_buffers = 1024MB
temp_buffers = 2MB
work_mem = 2MB
maintenance_work_mem = 128MB

pg_hba.conf

host    all             all             0.0.0.0/0               trust
host    all             all             ::/0                    trust

I know, I know.. It is not save to accept connections from everyone, but this is just for testing purposes and to make sure these settings are not blocking any connection. So this answer is void

I've been monitoring the number of connection on the server and under the load it is stable at 75. Postgres is using around 350mb of RAM. So given the config and the vm specs (7gb ram) there should be plenty of space to create more connections. However when the next scenario is spinning up the number of connections does not increase, it stays level and starts giving these log messages about no connection could be made.

What could be the problem here?


问:
How to get all the subviews of a window or view in latest SwiftUI App?
Is there any way to get all the subviews of an UIView, like [view subviews] in SwiftUI app ?

When I try to query, Its giving me "_TtCOCV7SwiftUI11DisplayList11ViewUpdater8Platform13CGDrawingView....". I am trying to get all textfields, labels etc.

答:
In most cases, you should prefer not thinking about “getting” the views in SwiftUI. In SwiftUI your views are structs, and you should structure your data model to “drive” changes to the views.

For example, if you were thinking about disabling all text fields, you should consider having a bool value in your data model that “drives” your SwiftUI views to become disabled or enabled. If you were thinking about styling all text fields a certain way, you should consider storing that styling information in your data model, and use different view modifiers on the text fields when the data model’s value changes.

With that said, you can use UIKit methods to get all the views in your SwiftUI hierarchy, by wrapping your top-most SwiftUI view in a UIHostingController. This way, you can query some UIKit views rendered under the hood. You might not always get the views you you want, because only some views in SwiftUI are rendered using native views like UIView and NSView, and some others are not. You can use the View Debugger to inspect your view hierarchy in more details to see which views you can query.


问:
How to mark as outdated an ActiveRecord object attribute?
I have a database trigger that modifies a field on INSERT. Then when I run object.my_attribute it returns nil instead of lets say 42.

If I do object.reload.my_attribute, this is fine. But I don't want to reload the whole object or part of it unless it is necessary. And I believe code shouldn't be concerned when and how an object was created. It should just be correct.

Is it possible to mark that particular attribute as outdated and any attempt to get its value to result in a query that fetches it from database?

For example:

after_save :forget_my_attribute

def forget_my_attribute
  forget_field :my_attribute
end
```

答:
I think it's better to make some service object where field is modified and call it when create the record. CreateModel.call(args) instead of   Model.create(args). It will be more clear than database trigger I think

But you can do something like this

```<code>after_create_commit :fetch_my_attribute

def fetch_my_attribute
  self[:my_attribute] = self.class.find_by(id: id)[:my_attribute]
end
</code>```

Or more flexible fetch attribute you need dynamically

```<code>def fetch_attribute(atr)
  self[atr] = self.class.find_by(id: id)[atr]
end

object.fetch_attribute(:my_attribute)
</code>```

Body:
I think it's better to make some service object where field is modified and call it when create the record. CreateModel.call(args) instead of   Model.create(args). It will be more clear than database trigger I think

But you can do something like this

after_create_commit :fetch_my_attribute

def fetch_my_attribute
  self[:my_attribute] = self.class.find_by(id: id)[:my_attribute]
end

Or more flexible fetch attribute you need dynamically

def fetch_attribute(atr)
  self[atr] = self.class.find_by(id: id)[atr]
end

object.fetch_attribute(:my_attribute)


问:
Get nearest position with Haversine Formula in Spring
I have an entitiy which has two columns in the database like this:

```<code>@Column(name = "latitude", nullable = false)
private float currentPositionLatitude;

@Column(name = "longitude", nullable = false)
private float currentPositionLongitude;
</code>```

And I have multiple entrys in my database(PostgresQl) for the entity with different latitudes and longitudes for all of them. Now I want to give a point (lat,lon) and a radius and show all entitys which are near the point.
I first tried it with the Harversine formula like this in Spring Jpa :

```<code>   String HAVERSINE_PART = "(6371 * acos(cos(radians(:latitude)) * cos(radians(s.latitude)) *" +
        " cos(radians(s.longitude) - radians(:longitude)) + sin(radians(:latitude)) * sin(radians(s.latitude))))";

    @Query("SELECT currentPositionLatitude,currentPositionLongitude FROM Entity WHERE  '%:HAVERSINE_PART%' < :distance ORDER BY '%:HAVERSINE_PART%' DESC")
      public List<Entity> findEntiryWithLocation(
      @Param("currentPositionLatitude") final float latitude,
      @Param("currentPositionLongitude") final float longitude, @Param("distance") final double distance )
</code>```

this didnt work so I tried:

```<code>    @Query("SELECT s FROM Entity s WHERE " + HAVERSINE_PART + " < :distance ORDER BY "+ HAVERSINE_PART + " DESC")
List<Entity> findEntityWithInDistance(
@Param("latitude") double latitude,
 @Param("longitude") double longitude,
 @Param("distance") double distanceWithInKM );
</code>```

this also didnt work so then I tried:

```<code>@Query(value = "SELECT *, earth_distance(ll_to_earth(:latitude, :longitude), ll_to_earth(latitude, longitude)) as distance FROM Car WHERE  (earth_box(ll_to_earth(:latitude, :longitude), :radiusInMeters) @> ll_to_earth(latitude, longitude))ORDER BY distance ASC",
nativeQuery = true)
List<Entity> getPlacesNear ( @Param("latitude") float latitude,
                             @Param("longitude")float longitude,
                             @Param("radiusInMeters") float radiusInMeters);
</code>```

This compiled but when I tried to put in values in my controller I got the error: jdbc error :2022 no dialect mapping

Here my methods for the service and the controller(the datatypes have changed maybe):

```<code>public List<Entity>showNearestEntityByDistances(float latitude, float longitude, float distance){
        return EntityRepository.getPlacesNear(latitude,longitude,distance);
    }
</code>```

and the endpoint:

```<code>@GetMapping("/location")
public List<Entity>showEntityNearby(@RequestParam float latitude,@RequestParam float longitude,@RequestParam float distance){

    return carService.showNearestEntitysByDistances(latitude,longitude,distance);
}
</code>```

I already looked at :
https://www.postgresql.org/docs/current/earthdistance.html
and
postgresql jpa earth_distance query

but it didnt worked. Has anyone an idea what Im doing wrong ?
Thanks in regard.

答:
The following worked for me:

first, run:

```<code> create extension cube;

 create extension earthdistance;
</code>```

This installs extensions that enable, among other things, location-based queries without installing PostGIS

Then, Instead of storing your lat and long in separate columns, store them together in a 'point' type column, keeping in mind that the longitude comes first, not the latitude as you would expect, e.g.

```<code>  create table Entity (city varchar(100), location point);
</code>```

and store your data, e.g.

```<code>insert into places(name, location) values ('lambertville', point((74.9429,40.3659)));

insert into places(name, location) values ('ny', point(74.0060, 40.7128));

insert into places(name, location) values ('phila', point( 75.1652, 39.9526));
</code>```

(note that Lambertville, NJ is somewhere around half-way between Philly and New York).

Then, if, for example, you want to select Entities that are less than a certain distance from another entity, you can do something like:

```<code>select * from places
 where
location <@> (select location from places where name = 'ny') < 70
  and name != 'ny';
</code>```

or, if you have the coordinates already, and want to find entities withing a certain distance,

```<code>select * from places
 where
location <@> point(74.0060, 40.7128) < 70
  and name != 'ny';
</code>```

I have not checked whether these queries can be adapted to work with JPA @Query annotations, YMMV.

Body:
I have an entitiy which has two columns in the database like this:

@Column(name = "latitude", nullable = false)
private float currentPositionLatitude;

@Column(name = "longitude", nullable = false)
private float currentPositionLongitude;

And I have multiple entrys in my database(PostgresQl) for the entity with different latitudes and longitudes for all of them. Now I want to give a point (lat,lon) and a radius and show all entitys which are near the point.
I first tried it with the Harversine formula like this in Spring Jpa :

   String HAVERSINE_PART = "(6371 * acos(cos(radians(:latitude)) * cos(radians(s.latitude)) *" +
        " cos(radians(s.longitude) - radians(:longitude)) + sin(radians(:latitude)) * sin(radians(s.latitude))))";

    @Query("SELECT currentPositionLatitude,currentPositionLongitude FROM Entity WHERE  '%:HAVERSINE_PART%' < :distance ORDER BY '%:HAVERSINE_PART%' DESC")
      public List<Entity> findEntiryWithLocation(
      @Param("currentPositionLatitude") final float latitude,
      @Param("currentPositionLongitude") final float longitude, @Param("distance") final double distance )

this didnt work so I tried:

    @Query("SELECT s FROM Entity s WHERE " + HAVERSINE_PART + " < :distance ORDER BY "+ HAVERSINE_PART + " DESC")
List<Entity> findEntityWithInDistance(
@Param("latitude") double latitude,
 @Param("longitude") double longitude,
 @Param("distance") double distanceWithInKM );

this also didnt work so then I tried:

@Query(value = "SELECT *, earth_distance(ll_to_earth(:latitude, :longitude), ll_to_earth(latitude, longitude)) as distance FROM Car WHERE  (earth_box(ll_to_earth(:latitude, :longitude), :radiusInMeters) @> ll_to_earth(latitude, longitude))ORDER BY distance ASC",
nativeQuery = true)
List<Entity> getPlacesNear ( @Param("latitude") float latitude,
                             @Param("longitude")float longitude,
                             @Param("radiusInMeters") float radiusInMeters);

This compiled but when I tried to put in values in my controller I got the error: jdbc error :2022 no dialect mapping

Here my methods for the service and the controller(the datatypes have changed maybe):

public List<Entity>showNearestEntityByDistances(float latitude, float longitude, float distance){
        return EntityRepository.getPlacesNear(latitude,longitude,distance);
    }

and the endpoint:

@GetMapping("/location")
public List<Entity>showEntityNearby(@RequestParam float latitude,@RequestParam float longitude,@RequestParam float distance){

    return carService.showNearestEntitysByDistances(latitude,longitude,distance);
}

I already looked at :
https://www.postgresql.org/docs/current/earthdistance.html
and
postgresql jpa earth_distance query

but it didnt worked. Has anyone an idea what Im doing wrong ?
Thanks in regard.

Body:
The following worked for me:

first, run:

 create extension cube;

 create extension earthdistance;

This installs extensions that enable, among other things, location-based queries without installing PostGIS

Then, Instead of storing your lat and long in separate columns, store them together in a 'point' type column, keeping in mind that the longitude comes first, not the latitude as you would expect, e.g.

  create table Entity (city varchar(100), location point);

and store your data, e.g.

insert into places(name, location) values ('lambertville', point((74.9429,40.3659)));

insert into places(name, location) values ('ny', point(74.0060, 40.7128));

insert into places(name, location) values ('phila', point( 75.1652, 39.9526));

(note that Lambertville, NJ is somewhere around half-way between Philly and New York).

Then, if, for example, you want to select Entities that are less than a certain distance from another entity, you can do something like:

select * from places
 where
location <@> (select location from places where name = 'ny') < 70
  and name != 'ny';

or, if you have the coordinates already, and want to find entities withing a certain distance,

select * from places
 where
location <@> point(74.0060, 40.7128) < 70
  and name != 'ny';

I have not checked whether these queries can be adapted to work with JPA @Query annotations, YMMV.


问:
Bash Shell variable substitution issue
I've defined a variable to be substituted in BASH which looks like this

```<code>EXPORT_FLT_2="<ngc_filter_configuration><ngc_filters><ngc_filter>ngc_filter_operator   operator='and'><ngc_filter_term type='ip' value='192.168.175.99'/><ngc_filter_term type='ip' value='72.32.127.138'/></ngc_filter_operator></ngc_filter></ngc_filters></ngc_filter_configuration>";
</code>```

I now want to use this variable in my shell script which looks like

```<code>. /mnt/.kumara/automation/exportcli.cfg
${PA_HOME}/exportcli -v -1:-1:-1:-1 0x1A2B3C4D $TFA_TRACE_FILE $TFA_ip $TFA_ifn   $TFA_ST $TFA_ET "$1" &> /dev/null
md5sum ${TFA_TRACE_FILE}1.cap | cut -d' ' -f1
rm ${TFA_TRACE_FILE}1.cap
</code>```

All the variables being used except for "$1" are defined in the exportcli.cfg file
Now after executing the script like

```<code>$./export.sh "$EXPORT_FLT_2"
</code>```

Insted of the actual substitution of the variable I see no parameters being passed. Am I missing something here ?

答:
I can't immediately spot the error here, but here's what I'd try.

1: run echo $EXPORT_FLT_2 in your shell to confirm that the variable you've defined is actually defined.

2: Stick echo $1 at various points in your export.sh script in turn, starting at the top.  See if the variable gets mangled somewhere.

3: run sh -x export.sh "$EXPORT_FLT_2" to see what the script actually executes on each step.

This should help pinpont more accurately what's happening and where the error originates.

Update

It seems the EXPORT_FLT_2 variable is defined in you config file, not in your shell.  Try changing $1 in your script to ${!1} and calling your script as

```<code>$ ./export.sh EXPORT_FLT_2
</code>```

(note, no $ decoration on the variable name).

Title: Bash Shell variable substitution issue

Body:
I've defined a variable to be substituted in BASH which looks like this

EXPORT_FLT_2="<ngc_filter_configuration><ngc_filters><ngc_filter>ngc_filter_operator   operator='and'><ngc_filter_term type='ip' value='192.168.175.99'/><ngc_filter_term type='ip' value='72.32.127.138'/></ngc_filter_operator></ngc_filter></ngc_filters></ngc_filter_configuration>";

I now want to use this variable in my shell script which looks like

. /mnt/.kumara/automation/exportcli.cfg
${PA_HOME}/exportcli -v -1:-1:-1:-1 0x1A2B3C4D $TFA_TRACE_FILE $TFA_ip $TFA_ifn   $TFA_ST $TFA_ET "$1" &> /dev/null
md5sum ${TFA_TRACE_FILE}1.cap | cut -d' ' -f1
rm ${TFA_TRACE_FILE}1.cap

All the variables being used except for "$1" are defined in the exportcli.cfg file
Now after executing the script like

$./export.sh "$EXPORT_FLT_2"

Insted of the actual substitution of the variable I see no parameters being passed. Am I missing something here ?

Body:
I can't immediately spot the error here, but here's what I'd try.

1: run echo $EXPORT_FLT_2 in your shell to confirm that the variable you've defined is actually defined.

2: Stick echo $1 at various points in your export.sh script in turn, starting at the top.  See if the variable gets mangled somewhere.

3: run sh -x export.sh "$EXPORT_FLT_2" to see what the script actually executes on each step.

This should help pinpont more accurately what's happening and where the error originates.

Update

It seems the EXPORT_FLT_2 variable is defined in you config file, not in your shell.  Try changing $1 in your script to ${!1} and calling your script as

$ ./export.sh EXPORT_FLT_2

(note, no $ decoration on the variable name).


问:
"No source code is available for type... did you forget to inherit", same module, just sibling source-directory (migrating the gwt-maven-plugin)
I am getting "No source code is available for type net.jzaruba.theapp.data.ColorFormResource; did you forget to inherit a required module?" error(s) in a class (net.jzaruba.theapp.client.TheEntryPoint) that is sitting in the same maven module, just in a sibling directory/package next to the allegedly missing types.

TheApp/Web/src/main/module.gwt.xml:

<module>
    <inherits name='com.google.gwt.user.User' />
    <inherits name='net.sf.gilead.Adapter4Gwt15'/>
    <inherits name="com.smartgwt.SmartGwt"/>
    <inherits name="com.smartgwt.tools.SmartGwtTools"/>
    <inherits name="com.googlecode.gwt.math.Math"/>

    <inherits name="net.jzaruba.theapp.Core" />
    <inherits name="net.jzaruba.theapp.Domain" />

    <source path='net/jzaruba/theapp/client'/>
    <source path='net/jzaruba/theapp/data'/>

    <entry-point class='net.jzaruba.theapp.client.TheEntryPoint' />
</module>
```
<p>TheApp/Web/pom.xml:</p>
<pre class="lang-xml prettyprint-override"><code><project>
  ...
  <packaging>gwt-app</packaging>
  ...
  <build>
    <plugins>

      <plugin>
        <groupId>net.ltgt.gwt.maven</groupId>
        <artifactId>gwt-maven-plugin</artifactId>
        <version>1.0.0</version>
        <extensions>true</extensions>

        <configuration>
          <moduleName>net.jzaruba.theapp.TheApp</moduleName>
          <jvmArgs>-javaagent:${org.projectlombok:lombok:jar}=ECJ</jvmArgs>
        </configuration>

        <executions>
          <execution>
            <goals>
              <goal>compile</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>
</code>```

答:
The source paths should be relative to the root of the GWT module, which in your case is  net/jzaruba/theapp.  So you should have this:

```<code><source path='client'/>
<source path='data'/>
</code>```

I think it was finding the class in client because that is a GWT default if no other paths exist.

Body:
I am getting "No source code is available for type net.jzaruba.theapp.data.ColorFormResource; did you forget to inherit a required module?" error(s) in a class (net.jzaruba.theapp.client.TheEntryPoint) that is sitting in the same maven module, just in a sibling directory/package next to the allegedly missing types.

TheApp/Web/src/main/module.gwt.xml:

<module>
    <inherits name='com.google.gwt.user.User' />
    <inherits name='net.sf.gilead.Adapter4Gwt15'/>
    <inherits name="com.smartgwt.SmartGwt"/>
    <inherits name="com.smartgwt.tools.SmartGwtTools"/>
    <inherits name="com.googlecode.gwt.math.Math"/>

    <inherits name="net.jzaruba.theapp.Core" />
    <inherits name="net.jzaruba.theapp.Domain" />

    <source path='net/jzaruba/theapp/client'/>
    <source path='net/jzaruba/theapp/data'/>

    <entry-point class='net.jzaruba.theapp.client.TheEntryPoint' />
</module>

TheApp/Web/pom.xml:

<project>
  ...
  <packaging>gwt-app</packaging>
  ...
  <build>
    <plugins>

      <plugin>
        <groupId>net.ltgt.gwt.maven</groupId>
        <artifactId>gwt-maven-plugin</artifactId>
        <version>1.0.0</version>
        <extensions>true</extensions>

        <configuration>
          <moduleName>net.jzaruba.theapp.TheApp</moduleName>
          <jvmArgs>-javaagent:${org.projectlombok:lombok:jar}=ECJ</jvmArgs>
        </configuration>

        <executions>
          <execution>
            <goals>
              <goal>compile</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>

Body:
The source paths should be relative to the root of the GWT module, which in your case is  net/jzaruba/theapp.  So you should have this:

<source path='client'/>
<source path='data'/>

I think it was finding the class in client because that is a GWT default if no other paths exist.


问:
Is there a way to do load balancing in a foreach loop on windows system
I am running a foreach loop that does some costly computations--takes about 24 hrs. What I noted is that after 21 hours the cpu usage drops from 100% to 50% with about 50% cores/threads still running while 50% are complete, which suggests that load balancing is not correctly taking place. I know how this can be fixed in linux but have no clue with a windows system. I am using the Snow package along with foreach in R. Your help is greatly appreciated.

答: You can use the doFuture adaptor, which gives you options to control the amount of "chunking". See Section 'Load balancing ("chunking")' in help("doFuture", package = "doFuture") for details.


问:
Zoom (panZoom) not working when switching plots in R shiny
I am able to use zoom on a single image, and that works well. However, in a more complex app, I have a dynamic UI that the plotting depends on a selectInput() like this:

```<code>output$all <- renderUI({

    if (input$choice == 'two nodes') {
        uiOutput("two")
    }else{
        uiOutput("three")
    }
})

</code>```

The problem is that when the user switches to the new visualisation, the zooming function stops working. (I have tried changing the 100ms but that's not the issue)

Here is a reproducible example:

```<code>library(shiny)
library(DiagrammeR)
library(magrittr)

js <- '
$(document).ready(function(){
  var instance;
  var myinterval = setInterval(function(){
    var element = document.getElementById("grr");
    if(element !== null){
      clearInterval(myinterval);
      instance = panzoom(element);
    }
  }, 100);
});
'

js2 <- '
$(document).ready(function(){
  var instance;
  var myinterval = setInterval(function(){
    var element = document.getElementById("grr2");
    if(element !== null){
      clearInterval(myinterval);
      instance = panzoom(element);
    }
  }, 100);
});
'

ui <- fluidPage(

    selectInput('choice',
                'choices:',choices = c('two nodes','three nodes')),
    tags$head(
        tags$script(src = "https://unpkg.com/panzoom@9.4.0/dist/panzoom.min.js"),
        tags$script(HTML(js)),
        tags$script(HTML(js2))
    ),

    uiOutput("all")

)

server <- function(input, output) {

    output$two_nodes <- renderUI({
        div(
            grVizOutput("grr", width = "100%", height = "90vh")
        )

    })

    output$three_nodes <- renderUI({
        div(
            grVizOutput("grr2", width = "100%", height = "90vh")
        )

    })

    output$all <- renderUI({

        if (input$choice == 'two nodes') {
            uiOutput("two_nodes")
        }else{
            uiOutput("three_nodes")
        }
    })

    output$grr <- renderGrViz(render_graph(
        create_graph() %>%
            add_n_nodes(n = 2) %>%
            add_edge(
                from = 1,
                to = 2,
                edge_data = edge_data(
                    value = 4.3
                )
            )
    ))

    output$grr2 <- renderGrViz(render_graph(
        create_graph() %>%
            add_n_nodes(n = 3) %>%
            add_edge(
                from = 1,
                to = 2,
                edge_data = edge_data(
                    value = 4.3
                )
            )
    ))

}

shinyApp(ui, server)

</code>```

答:
Since you used renderUI, we can add panzoom after grVizoutput, like this

library(shiny)
library(DiagrammeR)
library(magrittr)
library(shinyWidgets)

ui <- fluidPage(

    selectInput('choice',
                'choices:',choices = c('two nodes','three nodes')),
    tags$head(
        tags$script(src = "https://unpkg.com/panzoom@9.4.0/dist/panzoom.min.js"),
        # tags$script(HTML(js))
    ),

    uiOutput("all")

)

server <- function(input, output) {

    output$two_nodes <- renderUI({
        div(
            grVizOutput("grr", width = "100%", height = "90vh"),
            tags$script(HTML('panzoom($(".grViz").get(0))')),
            actionGroupButtons(
                inputIds = c("zoomout", "zoomin", "reset"),
                labels = list(icon("minus"), icon("plus"), "Reset"),
                status = "primary"
            )
        )

    })

    output$three_nodes <- renderUI({
        div(
            grVizOutput("grr2", width = "100%", height = "90vh"),
            tags$script(HTML('panzoom($(".grViz").get(0))')),
            actionGroupButtons(
                inputIds = c("zoomout", "zoomin", "reset"),
                labels = list(icon("minus"), icon("plus"), "Reset"),
                status = "primary"
            )
        )

    })

    output$all <- renderUI({

        if (input$choice == 'two nodes') {
            uiOutput("two_nodes")
        }else{
            uiOutput("three_nodes")
        }
    })

    output$grr <- renderGrViz(render_graph(
        create_graph() %>%
            add_n_nodes(n = 2) %>%
            add_edge(
                from = 1,
                to = 2,
                edge_data = edge_data(
                    value = 4.3
                )
            )
    ))

    output$grr2 <- renderGrViz(render_graph(
        create_graph() %>%
            add_n_nodes(n = 3) %>%
            add_edge(
                from = 1,
                to = 2,
                edge_data = edge_data(
                    value = 4.3
                )
            )
    ))

}

shinyApp(ui, server)

```

Body:
I am able to use zoom on a single image, and that works well. However, in a more complex app, I have a dynamic UI that the plotting depends on a selectInput() like this:

output$all <- renderUI({

    if (input$choice == 'two nodes') {
        uiOutput("two")
    }else{
        uiOutput("three")
    }
})

The problem is that when the user switches to the new visualisation, the zooming function stops working. (I have tried changing the 100ms but that's not the issue)

Here is a reproducible example:

library(shiny)
library(DiagrammeR)
library(magrittr)

js <- '
$(document).ready(function(){
  var instance;
  var myinterval = setInterval(function(){
    var element = document.getElementById("grr");
    if(element !== null){
      clearInterval(myinterval);
      instance = panzoom(element);
    }
  }, 100);
});
'

js2 <- '
$(document).ready(function(){
  var instance;
  var myinterval = setInterval(function(){
    var element = document.getElementById("grr2");
    if(element !== null){
      clearInterval(myinterval);
      instance = panzoom(element);
    }
  }, 100);
});
'

ui <- fluidPage(

    selectInput('choice',
                'choices:',choices = c('two nodes','three nodes')),
    tags$head(
        tags$script(src = "https://unpkg.com/panzoom@9.4.0/dist/panzoom.min.js"),
        tags$script(HTML(js)),
        tags$script(HTML(js2))
    ),

    uiOutput("all")

)

server <- function(input, output) {

    output$two_nodes <- renderUI({
        div(
            grVizOutput("grr", width = "100%", height = "90vh")
        )

    })

    output$three_nodes <- renderUI({
        div(
            grVizOutput("grr2", width = "100%", height = "90vh")
        )

    })

    output$all <- renderUI({

        if (input$choice == 'two nodes') {
            uiOutput("two_nodes")
        }else{
            uiOutput("three_nodes")
        }
    })

    output$grr <- renderGrViz(render_graph(
        create_graph() %>%
            add_n_nodes(n = 2) %>%
            add_edge(
                from = 1,
                to = 2,
                edge_data = edge_data(
                    value = 4.3
                )
            )
    ))

    output$grr2 <- renderGrViz(render_graph(
        create_graph() %>%
            add_n_nodes(n = 3) %>%
            add_edge(
                from = 1,
                to = 2,
                edge_data = edge_data(
                    value = 4.3
                )
            )
    ))

}

shinyApp(ui, server)


问:
QLabel click event using Qt?
I'm new in Qt and have a question.

I have QLabel and QLineEdit objects, and when QLabel text is clicked on, I want to set this text in QLineEdit.

Also I have read that QLabel has not clicked signal.

Can you explain how can I do this and write code for me ?!

答:
In the above example the header needs Q_OBJECT:

class YourLabelClass : public QLabel{

Q_OBJECT

signals:

Title: QLabel click event using Qt?


问:
Extra pixels left and top of canvas python turtle
I'm not sure why but on the left and top of a canvas I'm getting weird behaviour while creating my snake game using turtle. There's a border of 10 pixels on the left and on the top.

Main Code

```<code>import functools
from turtle import Screen
import time
from Snake import Snake

# initialize screen
win = Screen()
WIDTH = HEIGHT = 800
win.setup(width=WIDTH, height=HEIGHT)
win.bgcolor("black")
canvas = win.getcanvas()
root = canvas.winfo_toplevel()
root.overrideredirect(1)
win.tracer(0)

s = Snake()

def main():
    segments = s.init_segments()
    win.update()
    move_keys = ["Right", "Up", "Left", "Down"]
    running = True
    inc = 0

    for k in move_keys:
        win.onkeypress(functools.partial(s.move, segments, inc, k), key=k)
        inc += 90

    win.listen()

    while running:
        win.update()
        time.sleep(0.1)
        s.move(segments, segments[0].heading(), "none")

        if s.crashed(win.window_width(), win.window_height(), segments):
            running = False
            break

    win.exitonclick()

main()

</code>```

Snake Code

```<code>from turtle import Turtle
class Snake:

    def init_segments(self):
        segs = []
        x_pos = 0
        for i in range(3):
            t = Turtle(shape="square")
            t.color("white")
            t.penup()
            t.speed(1)
            segs.append(t)
            if t != segs[0]:
                x_pos -= 20
                t.goto(x_pos, 0)
        return segs

    def __no_turn(self, h, d):
        if h - d == -180 or h - d == 180:
            return True
        else:
            return False

    def __no_skip(self, k, dir):
        if (k == "Right" and dir == 0 or k == "Up" and dir == 90
                or k == "Left" and dir == 180 or k == "Down" and dir == 270):
            return False
        else:
            return True

    def move(self, t_list , dir, k):
        for seg_num in range(len(t_list) - 1, -1, -1):
            if self.__no_turn(t_list[0].heading(), dir):
                continue
            elif seg_num > 0:
                if self.__no_skip(k, dir):
                    t_list[seg_num].goto(t_list[seg_num - 1].position())
            else:
                t_list[seg_num].setheading(dir)
                if self.__no_skip(k, dir):
                    t_list[seg_num].forward(20)

    def crashed(self, window_width, window_height, t_list):
        head_position = t_list[0].position()
        body_positions = []
        hw = window_width/2
        hh = window_height/2
        for i in range(len(t_list)):
            body_positions.append(t_list[i].position())

        body_positions.pop(0)
        for i in range(len(body_positions)):
            if head_position == body_positions[i]:
                return True

        if head_position[0] >= hw:
            print(f"Head Position: {head_position[0]} ... Wall Position: {hw}")
            return True

        elif head_position[0] <= -hw:
            print(f"Head Position: {head_position[0]} ... Wall Position: {-hw}")
            return True

        elif head_position[1] >= hh:
            print(f"Head Position: {head_position[1]} ... Wall Position: {hh}")
            return True

        elif head_position[1] <= -hh:
            print(f"Head Position: {head_position[1]} ... Wall Position: {-hh}")
            return True
</code>```

The print lines in this file were added to try and figure out what was going on.

Please help me understand what's going on.

Thanks.

Edit:
Also I didn't notice it earlier, but there's a 1px border on the bottom and right hand sides.

Second Edit to illustrate the problem further.

I added the code for the pills a while ago. What I do is, I spawn every pill in all at once and hide them because you can't destroy a turtle without clearing the screen and it would be weird to get the turtle position every single time and redraw the turtle on the screen where it had been 0.1 seconds previously. Then I got this result.

As you can see the pills are spawning off screen.

The following is the code that I used in order to spawn in all pills and is similar to the code that I use for determining the edges of the screen.

```<code>hw = int(WIDTH/2)
hh = int(HEIGHT/2)
p_list = []
for i in range(-hw, hw, 20):
    for j in range(-hh, hh, 20):
        p = Pill((i, j))
        p.show_pill(segments)
        p_list.append(p)
</code>```

What happens when I reorder the win.update()

As you can see here, the right side now crashes one whole segment in. If you look closely, you'll see in this picture that the white of the snake, covers the extra pixel of space that is not covered in the previous picture where it stops on the last pixel of the circle.
You'll also see in the second picture and this one that there is a row of circles on the bottom that are peeking over the edge of the window's border.

答:
I've finally figured out why this happens.

First problem: I was previously led to believe that all turtle shapes are created equal. No they're not. While the default size for a turtle might be 20px by 20px, a square and circle are both defaulted to 21px as they need a center point that is not an even number so that it can divide evenly between the 4 quadrants of turtle's co-ordinate system (which has a single pixel serving as the x and y axes).

How to solve:

Make the canvas a multiple of 21px.

Remember that the canvas, when split into 2 parts has half of a turtle on each edge, which counts as a full turtle but the turtle only completes over the canvas, so we're sitting with an extra column and row of turtles.

Remove the last column and row of turtles and move the entire grid over by one turtle.

If done correctly you'll end up with the result below. Unfortunately, 2px at the right and bottom will be cut off as it's used for Turtle's UI. The top and left face a similar problem in that a single row of pixels are used for Turtle's UI

The snake itself is done in a similar manner in that instead of shifting the starting segment 20px I shift it 11px first and then I appended the other parts of the snake. I calculate it's position by removing the 11px that I shifted it initially. This literally solved most of the problems with the snake apart from stuff that Turtle's ui takes away.

Body:
I'm not sure why but on the left and top of a canvas I'm getting weird behaviour while creating my snake game using turtle. There's a border of 10 pixels on the left and on the top.

Main Code

import functools
from turtle import Screen
import time
from Snake import Snake

# initialize screen
win = Screen()
WIDTH = HEIGHT = 800
win.setup(width=WIDTH, height=HEIGHT)
win.bgcolor("black")
canvas = win.getcanvas()
root = canvas.winfo_toplevel()
root.overrideredirect(1)
win.tracer(0)

s = Snake()

def main():
    segments = s.init_segments()
    win.update()
    move_keys = ["Right", "Up", "Left", "Down"]
    running = True
    inc = 0

    for k in move_keys:
        win.onkeypress(functools.partial(s.move, segments, inc, k), key=k)
        inc += 90

    win.listen()

    while running:
        win.update()
        time.sleep(0.1)
        s.move(segments, segments[0].heading(), "none")

        if s.crashed(win.window_width(), win.window_height(), segments):
            running = False
            break

    win.exitonclick()

main()

Snake Code

from turtle import Turtle
class Snake:

    def init_segments(self):
        segs = []
        x_pos = 0
        for i in range(3):
            t = Turtle(shape="square")
            t.color("white")
            t.penup()
            t.speed(1)
            segs.append(t)
            if t != segs[0]:
                x_pos -= 20
                t.goto(x_pos, 0)
        return segs

    def __no_turn(self, h, d):
        if h - d == -180 or h - d == 180:
            return True
        else:
            return False

    def __no_skip(self, k, dir):
        if (k == "Right" and dir == 0 or k == "Up" and dir == 90
                or k == "Left" and dir == 180 or k == "Down" and dir == 270):
            return False
        else:
            return True

    def move(self, t_list , dir, k):
        for seg_num in range(len(t_list) - 1, -1, -1):
            if self.__no_turn(t_list[0].heading(), dir):
                continue
            elif seg_num > 0:
                if self.__no_skip(k, dir):
                    t_list[seg_num].goto(t_list[seg_num - 1].position())
            else:
                t_list[seg_num].setheading(dir)
                if self.__no_skip(k, dir):
                    t_list[seg_num].forward(20)

    def crashed(self, window_width, window_height, t_list):
        head_position = t_list[0].position()
        body_positions = []
        hw = window_width/2
        hh = window_height/2
        for i in range(len(t_list)):
            body_positions.append(t_list[i].position())

        body_positions.pop(0)
        for i in range(len(body_positions)):
            if head_position == body_positions[i]:
                return True

        if head_position[0] >= hw:
            print(f"Head Position: {head_position[0]} ... Wall Position: {hw}")
            return True

        elif head_position[0] <= -hw:
            print(f"Head Position: {head_position[0]} ... Wall Position: {-hw}")
            return True

        elif head_position[1] >= hh:
            print(f"Head Position: {head_position[1]} ... Wall Position: {hh}")
            return True

        elif head_position[1] <= -hh:
            print(f"Head Position: {head_position[1]} ... Wall Position: {-hh}")
            return True

The print lines in this file were added to try and figure out what was going on.

Please help me understand what's going on.

Thanks.

Edit:
Also I didn't notice it earlier, but there's a 1px border on the bottom and right hand sides.

Second Edit to illustrate the problem further.

I added the code for the pills a while ago. What I do is, I spawn every pill in all at once and hide them because you can't destroy a turtle without clearing the screen and it would be weird to get the turtle position every single time and redraw the turtle on the screen where it had been 0.1 seconds previously. Then I got this result.

As you can see the pills are spawning off screen.

The following is the code that I used in order to spawn in all pills and is similar to the code that I use for determining the edges of the screen.

hw = int(WIDTH/2)
hh = int(HEIGHT/2)
p_list = []
for i in range(-hw, hw, 20):
    for j in range(-hh, hh, 20):
        p = Pill((i, j))
        p.show_pill(segments)
        p_list.append(p)

What happens when I reorder the win.update()

As you can see here, the right side now crashes one whole segment in. If you look closely, you'll see in this picture that the white of the snake, covers the extra pixel of space that is not covered in the previous picture where it stops on the last pixel of the circle.
You'll also see in the second picture and this one that there is a row of circles on the bottom that are peeking over the edge of the window's border.


问:
List categories of a Blog with Angular ngFor directive
I just want to list the categories of a Blog in Angular. When I use ngFor, It shows a list of the categories but is bringing in some repeated ones, like if it were bringing all the blogs and not just the categories that some of them share. Hope I was clear on this question.

This is my html:

```<code><aside class="categories">
     <h2 class="aside-title">Categorias</h2>

     <ul *ngFor="let data of datas; index as i">
        <li class="nav-elipse-blue"><a [routerLink]="['/pagina',datas.category]" title="Blog CSS
        articles">{{ data.category.name }}</a></li>
     </ul>

</aside>

</code>```

答:
One way is to create a separate categories variable for your class, or if you can pull the list of categories straight from the database. To get the unique categories you can use JS's "set" data structure to filter out unique items: uniqueCategories = new Set(data.map(item => item.category.name))

Angular:

@Component({
  selector: 'component'
  templateUrl: 'component.html'
})
export class Component {
  data = ....
  uniqueCategories = new Set(this.data.map(item => item.category.name))
}
```
<p>HTML</p>
<pre class="lang-html prettyprint-override"><code><ul *ngFor="let category of uniqueCategories">
  <li>{{category}}</li>
</ul>
</code>```

Body:
I just want to list the categories of a Blog in Angular. When I use ngFor, It shows a list of the categories but is bringing in some repeated ones, like if it were bringing all the blogs and not just the categories that some of them share. Hope I was clear on this question.

This is my html:

Categorias

{{ data.category.name }}

Body:
One way is to create a separate categories variable for your class, or if you can pull the list of categories straight from the database. To get the unique categories you can use JS's "set" data structure to filter out unique items: uniqueCategories = new Set(data.map(item => item.category.name))

Angular:

@Component({
  selector: 'component'
  templateUrl: 'component.html'
})
export class Component {
  data = ....
  uniqueCategories = new Set(this.data.map(item => item.category.name))
}

HTML

<ul *ngFor="let category of uniqueCategories">
  <li>{{category}}</li>
</ul>


问:
Passing a Binding variable to a SwiftUI view from a function causes didSet observer to no longer fire
I want to be able to dynamically return the right variable to be used as a @Binding in a SwiftUI view however when I create a function to return something as Binding I no longer receive the didSet call on that variable. I'm not sure if this is unsupported behavior or I'm doing something wrong.

Here is an example

```<code>struct ContentView: View {
    @StateObject var dataStore = DataStore()

    var body: some View {
        VStack {
            Toggle("val1", isOn: $dataStore.val1)
            Toggle("val2", isOn: dataStore.boundVal2())
        }

    }
}

class DataStore: ObservableObject {

    @AppStorage("val1")
    var val1: Bool = false {
        didSet {
            print("did set val1")
        }
    }

    @AppStorage("val2")
    var val2: Bool = false {
        didSet {
            print("did set val2")
        }
    }

    func boundVal2() -> Binding<Bool> {
        return $val2
    }
}
</code>```

When you toggle the first value you get the didSet call, but when you toggle the second value you don't get it.

答:
It turns out that you need to use a Binding object to pass it back, like so:

```<code>    func boundVal2() -> Binding<Bool> {
        Binding(
            get: { self.val2 },
            set: { self.val2 = $0 }
        )
    }
</code>```

Body:
I want to be able to dynamically return the right variable to be used as a @Binding in a SwiftUI view however when I create a function to return something as Binding I no longer receive the didSet call on that variable. I'm not sure if this is unsupported behavior or I'm doing something wrong.

Here is an example

struct ContentView: View {
    @StateObject var dataStore = DataStore()

    var body: some View {
        VStack {
            Toggle("val1", isOn: $dataStore.val1)
            Toggle("val2", isOn: dataStore.boundVal2())
        }

    }
}

class DataStore: ObservableObject {

    @AppStorage("val1")
    var val1: Bool = false {
        didSet {
            print("did set val1")
        }
    }

    @AppStorage("val2")
    var val2: Bool = false {
        didSet {
            print("did set val2")
        }
    }

    func boundVal2() -> Binding<Bool> {
        return $val2
    }
}

When you toggle the first value you get the didSet call, but when you toggle the second value you don't get it.

Body:
It turns out that you need to use a Binding object to pass it back, like so:

    func boundVal2() -> Binding<Bool> {
        Binding(
            get: { self.val2 },
            set: { self.val2 = $0 }
        )
    }


问:
R: dpois not returning correct probabilities?
I am working with dataset of the number of truffles found in 288 search areas. I am planning to test the null hypothesis that the truffles are distributed randomly, thus I am using dpois() to to calculate the expected probability densities. There are 4 categories (0, 1, 2, or 3 truffles per plot). The expected probabilities will later be converted to expected proportions and incorporated into a chisq.test analysis.

The problem is that the expected probabilities that I get with the following code don't make sense. They should sum to 1, but are much too small. I run the same exact code with another dataset and it produces normal values. What is going on here?

```<code>trufflesFound<-c(rep(0,203),rep(1,39),rep(2,18),rep(3,28))
trufflesTable<-table(trufflesFound)
trufflesTable

mean(trufflesTable)

expTruffPois<-dpois(x = 0:3, lambda = mean(trufflesTable))
expTruffPois
</code>```

These are the probabilities it gives me, which are much too low!

0: 0.00000000000000000000000000000005380186

1: 0.00000000000000000000000000000387373404

2: 0.00000000000000000000000000013945442527

3: 0.00000000000000000000000000334690620643

In contrast, this dataset works just fine:

```<code>extinctData<-c(rep(1,13),rep(2,15),rep(3,16),rep(4,7),rep(5,10),rep(6,4),7,7,8,9,9,10,11,14,16,16,20)
extinctFreqTable <- table(extinctData)
extinctFreqTable

mean(extinctFreqTable)

expPois <- dpois(x = 0:20, lambda = mean(extinctFreqTable))
expPois

sum(expPois)
</code>```

The sum is 0.9999997, which is close to the expected value of 1

Thoughts?

答:
Lambda should be the average frequency, but taking mean(trufflesTable) returns the average of the counts of frequencies. Use mean(trufflesFound) instead. The reason the second one looks "right" is because mean(extinctData) is relatively close to mean(extinctFreqTable).
Note that the probabilities don't sum exactly to 1, because given the mean it is conceivable that we'd observe more than 4 truffles in a future search area.

trufflesFound<-c(rep(0,203),rep(1,39),rep(2,18),rep(3,28))
expTruffPois<-dpois(x = 0:3, lambda = mean(trufflesFound))
expTruffPois
#> [1] 0.57574908 0.31786147 0.08774301 0.01614715
sum(expTruffPois)
#> [1] 0.9975007
```

Created on 2022-02-08 by the reprex package (v2.0.1)

Body:
I am working with dataset of the number of truffles found in 288 search areas. I am planning to test the null hypothesis that the truffles are distributed randomly, thus I am using dpois() to to calculate the expected probability densities. There are 4 categories (0, 1, 2, or 3 truffles per plot). The expected probabilities will later be converted to expected proportions and incorporated into a chisq.test analysis.

The problem is that the expected probabilities that I get with the following code don't make sense. They should sum to 1, but are much too small. I run the same exact code with another dataset and it produces normal values. What is going on here?

trufflesFound<-c(rep(0,203),rep(1,39),rep(2,18),rep(3,28))
trufflesTable<-table(trufflesFound)
trufflesTable

mean(trufflesTable)

expTruffPois<-dpois(x = 0:3, lambda = mean(trufflesTable))
expTruffPois

These are the probabilities it gives me, which are much too low!

0: 0.00000000000000000000000000000005380186

1: 0.00000000000000000000000000000387373404

2: 0.00000000000000000000000000013945442527

3: 0.00000000000000000000000000334690620643

In contrast, this dataset works just fine:

extinctData<-c(rep(1,13),rep(2,15),rep(3,16),rep(4,7),rep(5,10),rep(6,4),7,7,8,9,9,10,11,14,16,16,20)
extinctFreqTable <- table(extinctData)
extinctFreqTable

mean(extinctFreqTable)

expPois <- dpois(x = 0:20, lambda = mean(extinctFreqTable))
expPois

sum(expPois)

The sum is 0.9999997, which is close to the expected value of 1

Thoughts?

Body:
Lambda should be the average frequency, but taking mean(trufflesTable) returns the average of the counts of frequencies. Use mean(trufflesFound) instead. The reason the second one looks "right" is because mean(extinctData) is relatively close to mean(extinctFreqTable).
Note that the probabilities don't sum exactly to 1, because given the mean it is conceivable that we'd observe more than 4 truffles in a future search area.

trufflesFound<-c(rep(0,203),rep(1,39),rep(2,18),rep(3,28))
expTruffPois<-dpois(x = 0:3, lambda = mean(trufflesFound))
expTruffPois
#> [1] 0.57574908 0.31786147 0.08774301 0.01614715
sum(expTruffPois)
#> [1] 0.9975007

Created on 2022-02-08 by the reprex package (v2.0.1)


问:
Clion: Target "[NAME]" not found
When trying to build my project, I see this in the build configurations (it pops up):

"LUCID" is the name of my project. I think it all built fine yesterday, but now after only restating I'm getting this:

Error: Target 'LUCID (LUCID)' not found.

The "Target" dropdown only has that one item in it (and also the "Build All" option). I do have project(LUCID) and add_executable(LUCID ${SOURCE_FILES}) in CMakeLists.txt, as was suggested in this question, although the situation is slightly different.

So, why am I getting this error and what do I do to fix it?

Another thing to note is that all the file names that should be part of my project and are specified in set(SOURCE_FILES ...) are greyed out in the CLion file browser, which they should not be.

答:
Reset cache and reload project!

```<code>Tools > CMake > Reset Cache and Reload Project
</code>```

Title: Clion: Target "[NAME]" not found

Body:
Reset cache and reload project!

Tools > CMake > Reset Cache and Reload Project