问:
Phaser 3 - Groups of Dynamic Sprites Not Colliding
I can’t get two groups of dynamic sprites or a dynamic sprite and a group of dynamic sprites to collide.  I can get each to collide with groups of static sprites that make up the level, but not the dynamic ones.

If I setup a collider for the sprites themselves instead of the group, they work fine.  Not sure what’s going on.

Here is a link to my code.  Could someone take a look?

https://github.com/deusprogrammer/mega-man-clone/blob/master/src/scripts/scenes/mainScene.ts

答:
The reason why the collisions doesn't work, is the physics - body of the group of enemies, seems to be interfering with, physics objects of the objects inside of the group.

Just replace the line 19 this.enemyGroup = this.physics.add.group(); (from the linked file) mainScene.ts, with this line this.enemyGroup = this.add.group(); and the collisions should work.

That line will only create a "simple" phaser group, without a physics body.

Here a running demo:

(I stripped your code, down to only essentials)

    class MegaMan extends Phaser.Physics.Arcade.Sprite {
        constructor(scene, x, y) {
            super(scene, x, y, 'megaman');
            scene.add.existing(this);
            scene.physics.add.existing(this);

            this.bulletGroup = scene.physics.add.staticGroup();

            this.scale *= 2;
            this.body.setSize(22, 22);
            this.setOrigin(0.5, 0.5);

            this.setCollideWorldBounds(true).setInteractive();

            this.controls = {
                up: this.scene.input.keyboard.addKey('W'),
                down: this.scene.input.keyboard.addKey('S'),
                left: this.scene.input.keyboard.addKey('A'),
                right: this.scene.input.keyboard.addKey('D'),
                jump: this.scene.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.SPACE),
                shoot: this.scene.input.keyboard.addKey('J')
            };
        }

        update() {
            super.update();

            // Controls
            if (this.controls.right.isDown) {
                this.setVelocityX(150);
            } else if (this.controls.left.isDown) {
                this.setVelocityX(-150);
            } else {
                this.setVelocityX(0);
            }

            // If player is jumping
            if (this.controls.jump.isDown && this.body.touching.down) {
                this.setVelocityY(-400);
            }

            if (this.controls.shoot.isDown && !this.isShooting) {
                this.isShooting = true;

                let megaBusterShot = this.scene.physics.add.sprite(this.x + 32, this.y, 'wood1');
                this.bulletGroup.add(megaBusterShot);

                megaBusterShot.body.allowGravity = false;
                megaBusterShot
                    .refreshBody()
                    .setVelocityX(this.flipX ? 300 : -300);

                setTimeout(() => {
                    this.isShooting = false;
                }, 200);
            }

        }

        onHit() {
            console.log("OUCH");
        }
    }

    class MetHat extends Phaser.Physics.Arcade.Sprite {

        constructor(scene, x, y) {
            super(scene, x, y, 'methat');
            scene.add.existing(this);
            scene.physics.add.existing(this);

            this.scale *= 1.5;

            this.state = "idle";

            this.setCollideWorldBounds(true);
            this.setInteractive();
            this.refreshBody();
        }

        onCollision() {

            if (this.body.touching.left) {
                this.body.velocity.x = 200;
            } else if (this.body.touching.right) {
                this.body.velocity.x = -200;
            }
        }

        onHit(weapon) {
            this.destroy();
        }

        update() {
            if (this.scene.game.loop.frame % 500 === 0 && this.body.touching.down && this.state === 'idle') {

                this.state = 'standing';

                // Make him start walking shortly after standing up
                setTimeout(() => {
                    this.state = 'walking';
                    this.setVelocityX(-200);
                }, 200);

                // Make him idle again after 10 seconds.
                setTimeout(() => {
                    this.state = 'idle';
                    this.setVelocityX(0);
                }, 3000);
            }

        }
    }

let assetMap = {
    "W1": {},
  "W2": {},
    "W3": {
        name: "wood3",
        file: "https://github.com/deusprogrammer/mega-man-clone/raw/master/src/assets/img/wood3.png",
    },
    "W4": {
        name: "wood4",
        file: "https://github.com/deusprogrammer/mega-man-clone/raw/master/src/assets/img/wood4.png",
    },
}

    const levels = {
        level1: {
            tilemap: [

                ["W3", "  ", "  ", "  ", "  ", "  ", "  ", "  ", "  ", "  ", "  ", "W3"],
                ["W3", "  ", "  ", "  ", "  ", "  ", "  ", "  ", "  ", "  ", "  ", "W3"],
                ["W3", "  ", "  ", "  ", "  ", "  ", "  ", "  ", "  ", "  ", "  ", "W3"],
                ["W3", "  ", "  ", "  ", "  ", "W4", "W4", "  ", "  ", "  ", "  ", "W3"],
                ["W3", "  ", "  ", "  ", "  ", "W4", "W4", "  ", "  ", "  ", "  ", "W3"],
                ["W4", "W4", "W4", "W4", "W4", "W4", "W4", "W4", "W4", "W4", "W4", "W4"],

            ],
            blocksX: 12,
            blocksY: 6,
            nextLevel: 'level2'
        }
    }

    class Level extends Phaser.GameObjects.GameObject {

        constructor(scene, levelConfig) {
            super(scene, 'level');
            this.levelConfig = levelConfig;

            scene.add.existing(this);
            scene.physics.add.existing(this);

            this.blocks = this.scene.physics.add.staticGroup();

            for (let y = 0; y < this.levelConfig.blocksY; y++) {
                for (let x = 0; x < this.levelConfig.blocksX; x++) {
                    let asset = assetMap[this.levelConfig.tilemap[y][x]];

                    if (!asset) {
                        continue;
                    }

                    let block = scene.physics.add.staticSprite(x * 32, y * 32, 'floor');
                    block.scale *= 2;
                    block.setOrigin(0, 0)
                        .setPushable(false)
                        .setImmovable(true)
                        .setGravity(0)
                        .refreshBody();
                    this.blocks.add(block);
                }
            }
        }
    }

    class MainScene extends Phaser.Scene {

        constructor() {
            super({ key: 'MainScene' });
        }

        preload(){
            let graphics;
            graphics = this.make.graphics({x: 0, y: 0});
            graphics.fillStyle(0xffffff, 1);
            graphics.fillRect(0, 0, 22, 22);
            graphics.generateTexture('megaman', 22, 22);

            graphics.fillStyle(0xff0000, 1);
            graphics.fillRect(0, 0, 22, 22);
            graphics.generateTexture('methat', 22, 22);

            graphics.fillStyle(0xcdcdcd, 1);
            graphics.fillRect(0, 0, 16, 16);
            graphics.generateTexture('floor', 16, 16);

        }

        create() {
            this.player = new MegaMan(this, 60, 0);
            this.level = new Level(this, levels['level1']);

            this.enemyGroup = this.add.group();
            this.enemyGroup.add(new MetHat(this, 300, 0));

            // Doesn't work?  Why?
            this.physics.add.collider(this.player, this.enemyGroup, () => {

                this.player.onHit();
            });
            this.physics.add.collider(this.player.bulletGroup, this.enemyGroup, (megaBusterShot, obj2) => {
                let enemy = obj2;
                megaBusterShot.destroy();
                enemy.onHit(megaBusterShot);
            });

            // Works
            this.physics.add.collider(this.player.bulletGroup, this.level.blocks, (megaBusterShot) => {
                megaBusterShot.destroy();
            });
            this.physics.add.collider(this.enemyGroup, this.level.blocks, (obj) => {
                let enemy = obj;
                enemy.onCollision();
            });

            this.physics.add.collider(this.player, this.level.blocks);
        }

        update() {
            this.player.update();
            this.enemyGroup.children.each((enemy) => {
                enemy.update();
            })
        }
    }

    const config = {
        type: Phaser.AUTO,
        backgroundColor: '#0000000',
        scene: [MainScene],
        width: 400,
        height: 248,
        physics: {
            default: 'arcade',
            arcade: {
                debug: true,
                gravity: { y: 600 }
            }
        }
    }

    const game = new Phaser.Game(config)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/npm/phaser@3.55.2/dist/phaser.js"></script></code>```

I had a similar problem (https://stackoverflow.com/a/70944607/1679286), seems to be a problem with nesten Objects, that have physics bodies.

Body:
The reason why the collisions doesn't work, is the physics - body of the group of enemies, seems to be interfering with, physics objects of the objects inside of the group.

Just replace the line 19 this.enemyGroup = this.physics.add.group(); (from the linked file) mainScene.ts, with this line this.enemyGroup = this.add.group(); and the collisions should work.

That line will only create a "simple" phaser group, without a physics body.

Here a running demo:

(I stripped your code, down to only essentials)

    class MegaMan extends Phaser.Physics.Arcade.Sprite {
        constructor(scene, x, y) {
            super(scene, x, y, 'megaman');
            scene.add.existing(this);
            scene.physics.add.existing(this);

            this.bulletGroup = scene.physics.add.staticGroup();

            this.scale *= 2;
            this.body.setSize(22, 22);
            this.setOrigin(0.5, 0.5);

            this.setCollideWorldBounds(true).setInteractive();

            this.controls = {
                up: this.scene.input.keyboard.addKey('W'),
                down: this.scene.input.keyboard.addKey('S'),
                left: this.scene.input.keyboard.addKey('A'),
                right: this.scene.input.keyboard.addKey('D'),
                jump: this.scene.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.SPACE),
                shoot: this.scene.input.keyboard.addKey('J')
            };
        }

        update() {
            super.update();

            // Controls
            if (this.controls.right.isDown) {
                this.setVelocityX(150);
            } else if (this.controls.left.isDown) {
                this.setVelocityX(-150);
            } else {
                this.setVelocityX(0);
            }

            // If player is jumping
            if (this.controls.jump.isDown && this.body.touching.down) {
                this.setVelocityY(-400);
            }

            if (this.controls.shoot.isDown && !this.isShooting) {
                this.isShooting = true;

                let megaBusterShot = this.scene.physics.add.sprite(this.x + 32, this.y, 'wood1');
                this.bulletGroup.add(megaBusterShot);

                megaBusterShot.body.allowGravity = false;
                megaBusterShot
                    .refreshBody()
                    .setVelocityX(this.flipX ? 300 : -300);

                setTimeout(() => {
                    this.isShooting = false;
                }, 200);
            }

        }

        onHit() {
            console.log("OUCH");
        }
    }

    class MetHat extends Phaser.Physics.Arcade.Sprite {

        constructor(scene, x, y) {
            super(scene, x, y, 'methat');
            scene.add.existing(this);
            scene.physics.add.existing(this);

            this.scale *= 1.5;

            this.state = "idle";

            this.setCollideWorldBounds(true);
            this.setInteractive();
            this.refreshBody();
        }

        onCollision() {

            if (this.body.touching.left) {
                this.body.velocity.x = 200;
            } else if (this.body.touching.right) {
                this.body.velocity.x = -200;
            }
        }

        onHit(weapon) {
            this.destroy();
        }

        update() {
            if (this.scene.game.loop.frame % 500 === 0 && this.body.touching.down && this.state === 'idle') {

                this.state = 'standing';

                // Make him start walking shortly after standing up
                setTimeout(() => {
                    this.state = 'walking';
                    this.setVelocityX(-200);
                }, 200);

                // Make him idle again after 10 seconds.
                setTimeout(() => {
                    this.state = 'idle';
                    this.setVelocityX(0);
                }, 3000);
            }

        }
    }

let assetMap = {
    "W1": {},
  "W2": {},
    "W3": {
        name: "wood3",
        file: "https://github.com/deusprogrammer/mega-man-clone/raw/master/src/assets/img/wood3.png",
    },
    "W4": {
        name: "wood4",
        file: "https://github.com/deusprogrammer/mega-man-clone/raw/master/src/assets/img/wood4.png",
    },
}

    const levels = {
        level1: {
            tilemap: [

                ["W3", "  ", "  ", "  ", "  ", "  ", "  ", "  ", "  ", "  ", "  ", "W3"],
                ["W3", "  ", "  ", "  ", "  ", "  ", "  ", "  ", "  ", "  ", "  ", "W3"],
                ["W3", "  ", "  ", "  ", "  ", "  ", "  ", "  ", "  ", "  ", "  ", "W3"],
                ["W3", "  ", "  ", "  ", "  ", "W4", "W4", "  ", "  ", "  ", "  ", "W3"],
                ["W3", "  ", "  ", "  ", "  ", "W4", "W4", "  ", "  ", "  ", "  ", "W3"],
                ["W4", "W4", "W4", "W4", "W4", "W4", "W4", "W4", "W4", "W4", "W4", "W4"],

            ],
            blocksX: 12,
            blocksY: 6,
            nextLevel: 'level2'
        }
    }

    class Level extends Phaser.GameObjects.GameObject {

        constructor(scene, levelConfig) {
            super(scene, 'level');
            this.levelConfig = levelConfig;

            scene.add.existing(this);
            scene.physics.add.existing(this);

            this.blocks = this.scene.physics.add.staticGroup();

            for (let y = 0; y < this.levelConfig.blocksY; y++) {
                for (let x = 0; x < this.levelConfig.blocksX; x++) {
                    let asset = assetMap[this.levelConfig.tilemap[y][x]];

                    if (!asset) {
                        continue;
                    }

                    let block = scene.physics.add.staticSprite(x * 32, y * 32, 'floor');
                    block.scale *= 2;
                    block.setOrigin(0, 0)
                        .setPushable(false)
                        .setImmovable(true)
                        .setGravity(0)
                        .refreshBody();
                    this.blocks.add(block);
                }
            }
        }
    }

    class MainScene extends Phaser.Scene {

        constructor() {
            super({ key: 'MainScene' });
        }

        preload(){
            let graphics;
            graphics = this.make.graphics({x: 0, y: 0});
            graphics.fillStyle(0xffffff, 1);
            graphics.fillRect(0, 0, 22, 22);
            graphics.generateTexture('megaman', 22, 22);

            graphics.fillStyle(0xff0000, 1);
            graphics.fillRect(0, 0, 22, 22);
            graphics.generateTexture('methat', 22, 22);

            graphics.fillStyle(0xcdcdcd, 1);
            graphics.fillRect(0, 0, 16, 16);
            graphics.generateTexture('floor', 16, 16);

        }

        create() {
            this.player = new MegaMan(this, 60, 0);
            this.level = new Level(this, levels['level1']);

            this.enemyGroup = this.add.group();
            this.enemyGroup.add(new MetHat(this, 300, 0));

            // Doesn't work?  Why?
            this.physics.add.collider(this.player, this.enemyGroup, () => {

                this.player.onHit();
            });
            this.physics.add.collider(this.player.bulletGroup, this.enemyGroup, (megaBusterShot, obj2) => {
                let enemy = obj2;
                megaBusterShot.destroy();
                enemy.onHit(megaBusterShot);
            });

            // Works
            this.physics.add.collider(this.player.bulletGroup, this.level.blocks, (megaBusterShot) => {
                megaBusterShot.destroy();
            });
            this.physics.add.collider(this.enemyGroup, this.level.blocks, (obj) => {
                let enemy = obj;
                enemy.onCollision();
            });

            this.physics.add.collider(this.player, this.level.blocks);
        }

        update() {
            this.player.update();
            this.enemyGroup.children.each((enemy) => {
                enemy.update();
            })
        }
    }

    const config = {
        type: Phaser.AUTO,
        backgroundColor: '#0000000',
        scene: [MainScene],
        width: 400,
        height: 248,
        physics: {
            default: 'arcade',
            arcade: {
                debug: true,
                gravity: { y: 600 }
            }
        }
    }

    const game = new Phaser.Game(config)

<script src="https://cdn.jsdelivr.net/npm/phaser@3.55.2/dist/phaser.js"></script>

I had a similar problem (https://stackoverflow.com/a/70944607/1679286), seems to be a problem with nesten Objects, that have physics bodies.


来源: stackexchange

问:
NodeJS incorrect `console.log` Date value
NodeJS outputs incorrect Date value in console.log

Assuming:
var todayDate = new Date();

Machine timezone: GMT+0530 / IST

Following are results:

#1

console.log ('Today  date:', todayDate);

Output: 020-04-04T09:54:29.107Z

#2
console.log ('Today  date as UTC:', todayDate.toUTCString());

Output: Today  date as UTC: Sat, 04 Apr 2020 09:54:29 GMT

#3
console.log ('Today  date as string:', todayDate.toString());

Output: Today  date as string: Sat Apr 04 2020 15:24:29 GMT+0530 (India Standard Time)

I am getting Output#1 whereas expected output is #3.

The Chrome browser shows same result as #3 which I expected with NodeJS since it runs on Chrome engine.

Please explain why NodeJS not output in local date/time.

答:
I can confirm that behaviour. In my case I was looping through unix dates from database:

```<code>    console.log(endunix); //epoch date
    console.log(endutc); // wrong date that will be fixed from unixdate
    let nowadatautc = new Date(endunix*1000);
    console.log(nowadatautc); // new date
let sql2 = "update schedule a set end_time_utc='"+nowadatautc+"' where a.`event_id` > 374 and a.`sport_id` = 5";
</code>```

and I get:

```<code>1645328100
2022-02-20T03:05:00.000Z
2022-02-20T03:35:00.000Z
update schedule a set end_time_utc='Sun Feb 20 2022 04:35:00 GMT+0100 (czas środkowoeuropejski standardowy)' where a.`event_id` > 374 and a.`sport_id` = 5
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I can confirm that behaviour. In my case I was looping through unix dates from database:

    console.log(endunix); //epoch date
    console.log(endutc); // wrong date that will be fixed from unixdate
    let nowadatautc = new Date(endunix*1000);
    console.log(nowadatautc); // new date
let sql2 = "update schedule a set end_time_utc='"+nowadatautc+"' where a.`event_id` > 374 and a.`sport_id` = 5";

and I get:

1645328100
2022-02-20T03:05:00.000Z
2022-02-20T03:35:00.000Z
update schedule a set end_time_utc='Sun Feb 20 2022 04:35:00 GMT+0100 (czas środkowoeuropejski standardowy)' where a.`event_id` > 374 and a.`sport_id` = 5


问:
Build was configured to prefer settings repositories over project repositories but repository 'maven' was added by build file 'build.gradle'
I want to add jitpack.io as a repository in my gradle file.
This is my gradle root file:

```<code>buildscript {
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:7.0.2"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.21"

        classpath 'com.google.dagger:hilt-android-gradle-plugin:2.38.1'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

Since I DON'T have a "allrepositories" to put my dependency there (only works there), I've created and added this code after buildscript code:

```<code>allprojects {
    repositories {
        maven {url 'https://www.jitpack.io'}
    }
}
</code>```

But this is the error I get

```<code>Caused by: org.gradle.api.InvalidUserCodeException: Build was configured to prefer settings repositories over project repositories but repository 'maven' was added by build file 'build.gradle'
</code>```

答:
As the Android studio is upadated so you have to control your dependency form your setting.app

```<code>dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
    google()
    mavenCentral()
    jcenter() // Warning: this repository is going to shut down soon
    maven { url 'https://jitpack.io' }
  }
</code>```

} rootProject.name = "EmfDetector"
include ':app'

Kindly place this line the respiratory

```<code>      maven { url 'https://jitpack.io' } //as i have done above
     `

</code>```

Body:
I want to add jitpack.io as a repository in my gradle file.
This is my gradle root file:

buildscript {
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:7.0.2"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.21"

        classpath 'com.google.dagger:hilt-android-gradle-plugin:2.38.1'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
task clean(type: Delete) {
    delete rootProject.buildDir
}

Since I DON'T have a "allrepositories" to put my dependency there (only works there), I've created and added this code after buildscript code:

allprojects {
    repositories {
        maven {url 'https://www.jitpack.io'}
    }
}

But this is the error I get

Caused by: org.gradle.api.InvalidUserCodeException: Build was configured to prefer settings repositories over project repositories but repository 'maven' was added by build file 'build.gradle'

Body:
As the Android studio is upadated so you have to control your dependency form your setting.app

dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
    google()
    mavenCentral()
    jcenter() // Warning: this repository is going to shut down soon
    maven { url 'https://jitpack.io' }
  }

} rootProject.name = "EmfDetector"
include ':app'

Kindly place this line the respiratory

      maven { url 'https://jitpack.io' } //as i have done above
     `


问:
What is the correct way of doing Java IPC through /dev/shm (with the lowest possible latency)
I'm trying to code an IPC solution through /dev/shm.

@SK-logic gave me some pointers in the comments here: Chronicle: How to optimize memory-mapped files for low-latency?

My doubt is: Should I use a MappedByteBuffer or just a plain FileChannel?

With a MappedByteBuffer I can use sun.misc.Unsafe and have direct access to memory. That's fantastic because Unsafe gives me methods like getLongVolatile (in addition to getLong) and putLongVolatile (in addition to putLong). Is that even possible if I use a plain FileChannel? How would I avoid reading cached data from the CPU cache with a plain FileChannel reading from /dev/shm/? Do I have to configure something in the operating system for volatile reads and writes from /dev/shm? What? Where? How? :)

What is the correct way of doing Java IPC through /dev/shm? Plain FileChannel? MappedByteBuffer?

Below how I get the pointer to memory through sun.misc.Unsafe:

```<code>    try {
        this.raf = new RandomAccessFile(file, "rw");
        this.fileChannel = raf.getChannel();
        this.mappedBuffer = this.fileChannel.map(MapMode.READ_WRITE, 0, size);
    } catch (Exception e) {
        throw new RuntimeException("Could not mmap file to memory: " + filename + " " + size, e);
    }

    try {
        addressField = Buffer.class.getDeclaredField("address");
        addressField.setAccessible(true);
        this.pointer = (long) addressField.get(this.mappedBuffer);
    } catch(Exception e) {
        throw new RuntimeException("Could not get off-heap pointer!", e);
    }
</code>```

答:
Chronicle Queue uses Unsafe for thread-safe memory access for heap and direct memory.

While this works, the JVM doesn't provide any guarantees as to how your system will behave. We test on Intel X64, AMD, and ARM processors.

Rather than writing this all yourself, why not try Chronicle Map or Queue to do this for you?

Body:
I'm trying to code an IPC solution through /dev/shm.

@SK-logic gave me some pointers in the comments here: Chronicle: How to optimize memory-mapped files for low-latency?

My doubt is: Should I use a MappedByteBuffer or just a plain FileChannel?

With a MappedByteBuffer I can use sun.misc.Unsafe and have direct access to memory. That's fantastic because Unsafe gives me methods like getLongVolatile (in addition to getLong) and putLongVolatile (in addition to putLong). Is that even possible if I use a plain FileChannel? How would I avoid reading cached data from the CPU cache with a plain FileChannel reading from /dev/shm/? Do I have to configure something in the operating system for volatile reads and writes from /dev/shm? What? Where? How? :)

What is the correct way of doing Java IPC through /dev/shm? Plain FileChannel? MappedByteBuffer?

Below how I get the pointer to memory through sun.misc.Unsafe:

    try {
        this.raf = new RandomAccessFile(file, "rw");
        this.fileChannel = raf.getChannel();
        this.mappedBuffer = this.fileChannel.map(MapMode.READ_WRITE, 0, size);
    } catch (Exception e) {
        throw new RuntimeException("Could not mmap file to memory: " + filename + " " + size, e);
    }

    try {
        addressField = Buffer.class.getDeclaredField("address");
        addressField.setAccessible(true);
        this.pointer = (long) addressField.get(this.mappedBuffer);
    } catch(Exception e) {
        throw new RuntimeException("Could not get off-heap pointer!", e);
    }


问:
Typescript type narrowing based on class instance
I have Person class which implements interface IPerson. The interface were to have two variants: IPerson1 | IPerson2

interface IPerson {
    name: string | "all",
    age?: number,
    height?: number,
    population?: number,
}

interface IPerson1 {
    name: string,
    age: number,
    height: number,
}
interface IPerson2 {
    name: "all",
    population: number
}

class Person implements IPerson {
    name: string;
    age?: number|undefined;
    height?: number|undefined;
    population?: number|undefined;
    constructor(name: "all", population: number);
    constructor(name: string, age: number, height: number);
    constructor(name: string, ageOrPopulation: number, height?: number) {
        this.name = name;
        if (height) {
            this.age = ageOrPopulation;
            this.height = height;
        } else {
            this.population = ageOrPopulation;
        }
    }
}

new Person("all", 3e6).population // I hope here population is number instead of number | undefined
// I hope Person can implement both interface IPerson1 and IPerson2, and typescript can do type narrowing for me.
```

It's worth to mention,  in my real code, Person class has so many methods, so I have to use class for good code structuring.

Is there any workaround for this scenario? Seems like if class can implments type, then I can make it implement a union type so TS can do type narrowing for me.  playground

答:
You can't  directly annotate the type of a constructor. You can however change the type of the class my assigning it to another variable and asserting a different type. With this technique you can then have different constructor signatures returning different types:

```<code>interface IPerson { name: string, age?: number, height?: number, population?: number, }
interface IPerson2 { name: "all", population: number }

class Person implements IPerson {
    age?: number|undefined;
    height?: number|undefined;
    population?: number|undefined;
    constructor(public name: string, ageOrPopulation: number, height?: number) {
        ///...
    }
}
const PersonCtor = Person as {
    new (name: "all", population: number): IPerson2
    new (name: string, age: number, height: number): IPerson
}

new PersonCtor("all", 3e6).population // I hope here population is number instead of number | undefined
</code>```

Playground Link

Body:
I have Person class which implements interface IPerson. The interface were to have two variants: IPerson1 | IPerson2

interface IPerson {
    name: string | "all",
    age?: number,
    height?: number,
    population?: number,
}

interface IPerson1 {
    name: string,
    age: number,
    height: number,
}
interface IPerson2 {
    name: "all",
    population: number
}

class Person implements IPerson {
    name: string;
    age?: number|undefined;
    height?: number|undefined;
    population?: number|undefined;
    constructor(name: "all", population: number);
    constructor(name: string, age: number, height: number);
    constructor(name: string, ageOrPopulation: number, height?: number) {
        this.name = name;
        if (height) {
            this.age = ageOrPopulation;
            this.height = height;
        } else {
            this.population = ageOrPopulation;
        }
    }
}

new Person("all", 3e6).population // I hope here population is number instead of number | undefined
// I hope Person can implement both interface IPerson1 and IPerson2, and typescript can do type narrowing for me.

It's worth to mention,  in my real code, Person class has so many methods, so I have to use class for good code structuring.

Is there any workaround for this scenario? Seems like if class can implments type, then I can make it implement a union type so TS can do type narrowing for me.  <a href="https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgJIAVoGcD2JkDeAsAFDLnIhwC2EAXMlmFKAObIA%20yARHADZ9uAGlIVkcVhAD8DEAFdqAI2giyFABYRgrdWBmUFyqKrEAHHKbl84YYHn3ylK0gF9SpUJFiIUGbHgBGQlEKKloGJhYQVhMKCXoDJ2MQ8k1tXVlDZxI3Ek9oeCQ0TChcEAAmYLVyMITeAWEU5HNLa1s8TKTXdxIEaywsZBKy5GBqUz4IWnBBv1K8KrFaiOY2AG4m%20IcsqA45EAATCBhQCAON6uQ0nT1Ooz3D49PzpparGzsQbaSHo5OQM4XMQIPCROQIMA4KAACmWPH4giEzQs73aIDu0AAlECKCCQGCIVDYTQEpE2Ej4hjjFctDcqdimniCZCYXCydEKZIAPJQdAotqfKlI666b5GTGLMQUMDqYBYAB0tWQAF5KCScVLRjBkNCRWAJcRLpryDK5fL4irxNzefyPngNcaTbKFXrLXqHWIXMgIHwsChDY6xKaFW8BQtVfEeXzWnaQB6KLlPd0SKQAQB3Ib%20EDQ%20qI5AAZggADZMfLQ7HkAB6StoK4WFCaKAocto0aDRxGUb4yBwA7IHDajvQTjIfZ-Z6kauMCBTQZ8YAAaxQwwWCDg%20DGEymEBmyEUOBlXa8hV8K5AQXXfbmZXKFMOyDAAE9TBAsAgWKYwMg1-gDjgH8%20KBUFAUA4GmbDIDAULILQ8pAA" rel="nofollow noreferrer">playground

Body:
You can't  directly annotate the type of a constructor. You can however change the type of the class my assigning it to another variable and asserting a different type. With this technique you can then have different constructor signatures returning different types:

interface IPerson { name: string, age?: number, height?: number, population?: number, }
interface IPerson2 { name: "all", population: number }

class Person implements IPerson {
    age?: number|undefined;
    height?: number|undefined;
    population?: number|undefined;
    constructor(public name: string, ageOrPopulation: number, height?: number) {
        ///...
    }
}
const PersonCtor = Person as {
    new (name: "all", population: number): IPerson2
    new (name: string, age: number, height: number): IPerson
}

new PersonCtor("all", 3e6).population // I hope here population is number instead of number | undefined

<a href="https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgJIAVoGcD2JkDeyIcAthAFzJZhSgDmANMnPRAPxUgCupARtGYALCMHpCwnYrwFRmABxzzuAGzhhgeKT36DkAXwBQoSLEQoM2PACZCxMpWQAiOCpVOFS1es0guM6ANDQwQ1LCxkTChcfGBSeRUIcnAIy2i8QkNkbJY2bQCoAB9uEAATCBhQCFKAbiyckTEJfN0ikvLKkGq6nORFZTUNLX9W4rKKqtr67IQ8GihuBDAcKAAKZT4VYAR7cip5hmZWCAB5KHQvQd8R2WFRcUkb6ABKTN7egHovgDpf6aCjLMQDRIlYQABhZZQZAAXlB6XwcAiBH+XQA7shViQ9s5XO5PAMfHgnlBnlQ0jFrKiIBisQ59rRDrlHDpbshGg8SWS0FEYoZ9Mhguj4TFIStVi43B5kABmCAANme3363iG+C+aHZShQIigKBVVwywAirMCoBoEDgpWQOBg0layEKyHaEy6pUMQA" rel="nofollow noreferrer">Playground Link


问:
ggplot, dplyr etc in Windows without rlang.dll?
In R for Windows and the tidyverse what does rlang.dll do and can I do without it if I install and load libraries such as dyplyr, magrittr and ggplot2 separately?</p>

答:
The file rlang.dll is a binary file that contains compiled C code that rlang calls to do some of its work. Since {dplyr} and {ggplot2} both import functions from rlang, this makes rlang a hard dependency of both packages, meaning that these packages can't run without it. If you specifically try to install {ggplot2} and {dplyr} without their hard dependencies, they won't run.

As a concrete example, the first line of the source code for the data frame method of dplyr's mutate function contains this line:

  keep <- arg_match(.keep)
```
<p>Where <code>arg_match</code> is imported from rlang. The source code for <code>arg_match</code>
includes a call to the <em>non-exported</em> rlang function <code>arg_match0</code>, which you can see in the r console by doing:</p>
<pre class="lang-r prettyprint-override"><code>rlang:::arg_match0
#> function (arg, values, arg_nm = as_label(substitute(arg)))
#> {
#>     .External(rlang_ext_arg_match0, arg, values, environment())
#> }
#> <bytecode: 0x00000258f4d35bd0>
#> <environment: namespace:rlang>
</code>```

This .External call indicates that the arguments are being passed to a compiled C function registered in rlang.dll.

So without the rlang dll, there is no arg_match0, so no arg_match, and therefore no mutate. It's difficult to imagine using {dplyr} without mutate. And of course, this is just one example.

Body:
The file rlang.dll is a binary file that contains compiled C code that rlang calls to do some of its work. Since {dplyr} and {ggplot2} both import functions from rlang, this makes rlang a hard dependency of both packages, meaning that these packages can't run without it. If you specifically try to install {ggplot2} and {dplyr} without their hard dependencies, they won't run.

As a concrete example, the first line of the source code for the data frame method of dplyr's mutate function contains this line:

  keep <- arg_match(.keep)

Where arg_match is imported from rlang. The source code for arg_match
includes a call to the non-exported rlang function arg_match0, which you can see in the r console by doing:

rlang:::arg_match0
#> function (arg, values, arg_nm = as_label(substitute(arg)))
#> {
#>     .External(rlang_ext_arg_match0, arg, values, environment())
#> }
#> <bytecode: 0x00000258f4d35bd0>
#> <environment: namespace:rlang>

This .External call indicates that the arguments are being passed to a compiled C function registered in rlang.dll.

So without the rlang dll, there is no arg_match0, so no arg_match, and therefore no mutate. It's difficult to imagine using {dplyr} without mutate. And of course, this is just one example.


问:
Implementing Multi-Label Margin-Loss in Tensorflow
I'm wanted to implement the Multi-Label Margin-Loss in Tensorflow, using as orientation the definition of pytorch, i.e.

https://pytorch.org/docs/stable/generated/torch.nn.MultiLabelMarginLoss.html

This is the naive solution I came up with:

```<code>def naive(y_true, y_pred, mu = 1.0):
    pos = tf.ragged.boolean_mask(y_pred, tf.cast(y_true, dtype=tf.bool))
    neg = tf.ragged.boolean_mask(y_pred, tf.cast(1 - y_true, dtype=tf.bool))

    loss = 0
    for i in range(y_true.shape[0]):
        loss += tf.reduce_mean(tf.nn.relu(mu - (tf.transpose([pos[i]]) - neg[i])))
    return loss
</code>```

The implementation above yield correct results (see example below), but I'm having a hard time removing the loop from the function, i.e. expressing this in matrix/vector multiplication, etc.

Example:

```<code>y_pred = tf.constant([[0.1, 0.2, 0.4, 0.8]], dtype=tf.float32)
print(y_pred)

y_true = tf.constant([[1, 0, 0, 1]], dtype=tf.float32)
print(y_true)

naive(y_true, y_pred)

# 0.25 * ((1-(0.1-0.2)) + (1-(0.1-0.4)) + (1-(0.8-0.2)) + (1-(0.8-0.4)))
# 0.8500

# (see pytorch example)
</code>```

Any ideas are very welcome.

答:
You could try using tf.while_loop like this:

import tensorflow as tf

def naive(y_true, y_pred, mu = 1.0):
    pos = tf.ragged.boolean_mask(y_pred, tf.cast(y_true, dtype=tf.bool))
    neg = tf.ragged.boolean_mask(y_pred, tf.cast(1 - y_true, dtype=tf.bool))

    loss = tf.Variable(0.0, trainable=False)
    i = tf.constant(0)
    while_condition = lambda i, loss, pos, neg: tf.math.less(i, tf.shape(y_true)[0])

    def body(i, loss, p, n):
      loss.assign_add(tf.reduce_mean(tf.nn.relu(1.0 - (tf.transpose([p[i]]) - n[i]))))
      return tf.add(i, 1), loss, p, n

    _, loss, _,_ = tf.while_loop(while_condition, body, loop_vars=(i, loss, pos, neg))

    return loss

y_pred = tf.constant([[0.1, 0.2, 0.4, 0.8], [0.1, 0.2, 0.4, 0.8]], dtype=tf.float32)
y_true = tf.constant([[1, 0, 0, 1], [1, 0, 0, 1]], dtype=tf.float32)
naive(y_true, y_pred)
```
```<tf.Tensor: shape=(), dtype=float32, numpy=1.7>
```

Body:
I'm wanted to implement the Multi-Label Margin-Loss in Tensorflow, using as orientation the definition of pytorch, i.e.

https://pytorch.org/docs/stable/generated/torch.nn.MultiLabelMarginLoss.html

This is the naive solution I came up with:

def naive(y_true, y_pred, mu = 1.0):
    pos = tf.ragged.boolean_mask(y_pred, tf.cast(y_true, dtype=tf.bool))
    neg = tf.ragged.boolean_mask(y_pred, tf.cast(1 - y_true, dtype=tf.bool))

    loss = 0
    for i in range(y_true.shape[0]):
        loss += tf.reduce_mean(tf.nn.relu(mu - (tf.transpose([pos[i]]) - neg[i])))
    return loss

The implementation above yield correct results (see example below), but I'm having a hard time removing the loop from the function, i.e. expressing this in matrix/vector multiplication, etc.

Example:

y_pred = tf.constant([[0.1, 0.2, 0.4, 0.8]], dtype=tf.float32)
print(y_pred)

y_true = tf.constant([[1, 0, 0, 1]], dtype=tf.float32)
print(y_true)

naive(y_true, y_pred)

# 0.25 * ((1-(0.1-0.2)) + (1-(0.1-0.4)) + (1-(0.8-0.2)) + (1-(0.8-0.4)))
# 0.8500

# (see pytorch example)

Any ideas are very welcome.

Body:
You could try using tf.while_loop like this:

import tensorflow as tf

def naive(y_true, y_pred, mu = 1.0):
    pos = tf.ragged.boolean_mask(y_pred, tf.cast(y_true, dtype=tf.bool))
    neg = tf.ragged.boolean_mask(y_pred, tf.cast(1 - y_true, dtype=tf.bool))

    loss = tf.Variable(0.0, trainable=False)
    i = tf.constant(0)
    while_condition = lambda i, loss, pos, neg: tf.math.less(i, tf.shape(y_true)[0])

    def body(i, loss, p, n):
      loss.assign_add(tf.reduce_mean(tf.nn.relu(1.0 - (tf.transpose([p[i]]) - n[i]))))
      return tf.add(i, 1), loss, p, n

    _, loss, _,_ = tf.while_loop(while_condition, body, loop_vars=(i, loss, pos, neg))

    return loss

y_pred = tf.constant([[0.1, 0.2, 0.4, 0.8], [0.1, 0.2, 0.4, 0.8]], dtype=tf.float32)
y_true = tf.constant([[1, 0, 0, 1], [1, 0, 0, 1]], dtype=tf.float32)
naive(y_true, y_pred)

<tf.Tensor: shape=(), dtype=float32, numpy=1.7>


问:
How to call specific array values in v-for in Vuejs?
User.vue

<template>

      {{ item }}

</template>

```

Working code:- https://codesandbox.io/s/hardcore-cartwright-vi6qg?file=/src/components/User.vue

How to call specific value from an array in Vuejs.

At present, It is calling all values, from an array. But want to call only {{name}} and {{age}} values.

If i remove the v-for and write directly like this  {{ user.name }} {{ user.age }} --> It is printing the array values, But getting error as

[Vue warn]: Error in render: "TypeError: Cannot read properties of undefined (reading 'name')"
TypeError: Cannot read properties of undefined (reading 'name')

答:
I think problem is in your computed block, use below solution

```<code>computed: {
    user: function () {
      return this.lists.find((item) => item.cmd_id === this.$route.params.id);
    },
  },
</code>```

sandbox

Body:
User.vue

<template>

      {{ item }}

</template>

Working code:- https://codesandbox.io/s/hardcore-cartwright-vi6qg?file=/src/components/User.vue

How to call specific value from an array in Vuejs.

At present, It is calling all values, from an array. But want to call only {{name}} and {{age}} values.

If i remove the v-for and write directly like this  {{ user.name }} {{ user.age }} --> It is printing the array values, But getting error as

[Vue warn]: Error in render: "TypeError: Cannot read properties of undefined (reading 'name')"
TypeError: Cannot read properties of undefined (reading 'name')

Body:
I think problem is in your computed block, use below solution

computed: {
    user: function () {
      return this.lists.find((item) => item.cmd_id === this.$route.params.id);
    },
  },

sandbox


问:
check valid date in java
I tried to check a String input that is a valid date using the format dd/MM/yyyy like this:

```<code>String input = Scanner.nextLine();
DateTimeFormatter formater = DateTimeFormatter.ofPattern("dd/MM/yyyy");
try{
    LocaleDate.parse(input, formater);
}
catch(Exception e)
</code>```

But it can't check some rules below:

```<code>Leap year, February 29 days.

Common year, February 28 days.

Month 1, 3, 5, 7, 8, 10, 12, max 31 days.

Month 4, 6, 9, 11, max 30 days.
</code>```

When I use input = "30/02/2022", it's legal.
I use netbeans 8.2 and jdk 1.8. Do they support some methods for checking these rules?

答:
You need to enable the strict mode of the DateTimeFormatter :

```<code>DateTimeFormatter formater = DateTimeFormatter.ofPattern("dd/MM/yyyy")
                            .withResolverStyle(ResolverStyle.STRICT);
</code>```

LocaleDate.parse("30/02/2022, formater); will then throw an exception.

Title: check valid date in java

Body:
I tried to check a String input that is a valid date using the format dd/MM/yyyy like this:

String input = Scanner.nextLine();
DateTimeFormatter formater = DateTimeFormatter.ofPattern("dd/MM/yyyy");
try{
    LocaleDate.parse(input, formater);
}
catch(Exception e)

But it can't check some rules below:

Leap year, February 29 days.

Common year, February 28 days.

Month 1, 3, 5, 7, 8, 10, 12, max 31 days.

Month 4, 6, 9, 11, max 30 days.

When I use input = "30/02/2022", it's legal.
I use netbeans 8.2 and jdk 1.8. Do they support some methods for checking these rules?

Body:
You need to enable the strict mode of the DateTimeFormatter :

DateTimeFormatter formater = DateTimeFormatter.ofPattern("dd/MM/yyyy")
                            .withResolverStyle(ResolverStyle.STRICT);

LocaleDate.parse("30/02/2022, formater); will then throw an exception.


问:
Table align="center" doesn't seem to be working
Why would the align="center" not be working on the first table on the page below:

http://eurochlor.amaze.com/chlorinated-solvents-%28ecsa%29/about-chlorinated-solvents/facts-figures/trichloroethylene.aspx

答:
If you want to have the table centered use:

```<code>.content-table {
    margin: 0 auto;
}
</code>```

if you want to have the td text centered use:

```<code>.content-table td {
    text-align: center;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
If you want to have the table centered use:

.content-table {
    margin: 0 auto;
}

if you want to have the td text centered use:

.content-table td {
    text-align: center;
}


问:
How to concatenate multiple rows list with same value into single row
I have the following class called "Person".

```<code>public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Hobby { get; set; }
}
</code>```

I created a list with the following data:

```<code>List<Person> users = new List<Person>()
{
    new Person {Id= 1, Name = "Silva", Hobby = "Football" },
    new Person {Id= 2, Name = "Bob", Hobby = "Golf"},
    new Person {Id= 2, Name = "Bob", Hobby = "Tennis"},
    new Person {Id= 1, Name = "Silva", Hobby = "Sleeping"},
    new Person {Id= 3, Name = "Sue", Hobby = "Drinking"}
    new Person {Id= 1, Name = "Silva", Hobby = "Handball"},
    new Person {Id= 3, Name = "Sue", Hobby = "Football"},
};
</code>```

Now I need to create a new list called "usersHobbies" that when called returns the following result.

```<code>Id    Name        Hobby
1     Silva       Football, Sleeping, Handball
2     Bob         Golf, Tennis
3     Sue         Drinking, Football
</code>```

答:
You would use GroupBy() to achieve that. Group by Id, select the Name from the first group, use string.Join() to join the Hobbies into a single string:

```<code>var result = users.GroupBy(u => u.Id)  // group by Id
                  .Select(g => new     // select values
                  {
                      Id = g.Key,
                      Name = g.First().Name,
                      Hobbies = string.Join(", ", g.Select(u => u.Hobby))
                  })
                  .ToList();
</code>```

Output:

If you want to return a new Person instead of an anonymous type, just update the Select:

```<code> .Select(g => new Person
  {
      Id = g.Key,
      Name = g.First().Name,
      Hobby = string.Join(", ", g.Select(u => u.Hobby))
  })
</code>```

Update from your comment:

is it possible instead of string.join() to return a list or array

Yes, it is. Using an anonymous type:

```<code>var result = users.GroupBy(u => u.Id)  // group by Id
                  .Select(g => new     // select values
                  {
                      Id = g.Key,
                      Name = g.First().Name,
                      Hobbies = g.Select(u => u.Hobby).ToList()
                  })
                  .ToList();
</code>```

Which returns a List<string> for Hobbies.

Body:
I have the following class called "Person".

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Hobby { get; set; }
}

I created a list with the following data:

List<Person> users = new List<Person>()
{
    new Person {Id= 1, Name = "Silva", Hobby = "Football" },
    new Person {Id= 2, Name = "Bob", Hobby = "Golf"},
    new Person {Id= 2, Name = "Bob", Hobby = "Tennis"},
    new Person {Id= 1, Name = "Silva", Hobby = "Sleeping"},
    new Person {Id= 3, Name = "Sue", Hobby = "Drinking"}
    new Person {Id= 1, Name = "Silva", Hobby = "Handball"},
    new Person {Id= 3, Name = "Sue", Hobby = "Football"},
};

Now I need to create a new list called "usersHobbies" that when called returns the following result.

Id    Name        Hobby
1     Silva       Football, Sleeping, Handball
2     Bob         Golf, Tennis
3     Sue         Drinking, Football

Body:
You would use GroupBy() to achieve that. Group by Id, select the Name from the first group, use string.Join() to join the Hobbies into a single string:

var result = users.GroupBy(u => u.Id)  // group by Id
                  .Select(g => new     // select values
                  {
                      Id = g.Key,
                      Name = g.First().Name,
                      Hobbies = string.Join(", ", g.Select(u => u.Hobby))
                  })
                  .ToList();

Output:

If you want to return a new Person instead of an anonymous type, just update the Select:

 .Select(g => new Person
  {
      Id = g.Key,
      Name = g.First().Name,
      Hobby = string.Join(", ", g.Select(u => u.Hobby))
  })

Update from your comment:

is it possible instead of string.join() to return a list or array

Yes, it is. Using an anonymous type:

var result = users.GroupBy(u => u.Id)  // group by Id
                  .Select(g => new     // select values
                  {
                      Id = g.Key,
                      Name = g.First().Name,
                      Hobbies = g.Select(u => u.Hobby).ToList()
                  })
                  .ToList();

Which returns a List<string> for Hobbies.


问:
GitHub CI - move a file using PHP copy() in a PHPUnit test
I have an application written in PHP 8. I've added some Unit Tests for it using PHPUnit.

In one of the tests I am using PHP's copy function to move a file from one location to another. This is done to test an endpoint which downloads the file by moving a "dummy" file to the "real" location that the file would be in, in the production application.

My test looks like this:

```<code>// tests/TestCase/Controller/DocsControllerTest.php
public function testDownload()
{
    $testFile = '75e57e4a-2149-4270-9d76-c7c8f0298c2c.pdf';
    copy('/full/path/to/testFiles/' . $testFile, '/webroot/docs/');

    // Download the file from the endpoint
    $id = 9; // File ID to download
    $this->get('/download/' . $id);

    // This should return a HTTP 200 response containing the PDF
    $this->assertResponseCode(200, 'Downloading a valid PDF should produce a 200 response.');
}
</code>```

To explain the function above:

We have a test file called 75e57e4a-2149-4270-9d76-c7c8f0298c2c.pdf. This is a real PDF file with appropriate encoding.

We move the file, using copy(), from a directory where we hold some test files, into the full directory path where the production web application will really store the files (/webroot/docs/).

The remainder of the logic deals with downloading the file from the endpoint. The $this->get makes a HTTP GET request to an endpoint (/download/) which also passes in the appropriate file ID. The location of the file is looked up from a MySQL database and then is streamed to the browser, thus generating a HTTP 200 response containing the PDF.

This works both when I run phpunit locally by executing vendor/bin/phpunit --filter testDownload:

```<code>PHPUnit 9.5.10 by Sebastian Bergmann and contributors.
Time: 00:05.053, Memory: 20.00 MB
OK (1 test, 16 assertions)
</code>```

It also works in a browser, i.e. if I make a request to /download/9 I am served the appropriate PDF.

The problem I'm having is on GitHub. When I run the unit test there it fails the CI with this error:

```<code>Warning Error: copy(/home/runner/work/my-app/webroot/docs/75e57e4a-2149-4270-9d76-c7c8f0298c2c.pdf): Failed to open stream: No such file or directory
In [/home/runner/work/my-app/tests/TestCase/Controller/DocsControllerTest.php, line 745]
</code>```

Given that this works locally I can't understand why this error is occurring. Is there some restriction with using copy() in GitHub's CI?

The directory and files at /full/path/to/testFiles/ are not .gitignore'd so they are committed with the rest of the repo code. So the test file, 75e57e4a-2149-4270-9d76-c7c8f0298c2c.pdf, exists within the codebase on GitHub.

I am using PHPUnit 9.5.10, PHP 8.0 on a Mac running macOS Monterey (12.2).

答:
It clearly reads:

Failed to open stream: No such file or directory

Maybe add .gitkeep into target directory docs? It may also be, that the source file is not there. One usually can take this error message literal. While it's entirely unclear what $this->get() even is or why your Mac would have anything to do with running GitHub Action?

Body:
I have an application written in PHP 8. I've added some Unit Tests for it using PHPUnit.

In one of the tests I am using PHP's copy function to move a file from one location to another. This is done to test an endpoint which downloads the file by moving a "dummy" file to the "real" location that the file would be in, in the production application.

My test looks like this:

// tests/TestCase/Controller/DocsControllerTest.php
public function testDownload()
{
    $testFile = '75e57e4a-2149-4270-9d76-c7c8f0298c2c.pdf';
    copy('/full/path/to/testFiles/' . $testFile, '/webroot/docs/');

    // Download the file from the endpoint
    $id = 9; // File ID to download
    $this->get('/download/' . $id);

    // This should return a HTTP 200 response containing the PDF
    $this->assertResponseCode(200, 'Downloading a valid PDF should produce a 200 response.');
}

To explain the function above:

We have a test file called 75e57e4a-2149-4270-9d76-c7c8f0298c2c.pdf. This is a real PDF file with appropriate encoding.

We move the file, using copy(), from a directory where we hold some test files, into the full directory path where the production web application will really store the files (/webroot/docs/).

The remainder of the logic deals with downloading the file from the endpoint. The $this->get makes a HTTP GET request to an endpoint (/download/) which also passes in the appropriate file ID. The location of the file is looked up from a MySQL database and then is streamed to the browser, thus generating a HTTP 200 response containing the PDF.

This works both when I run phpunit locally by executing vendor/bin/phpunit --filter testDownload:

PHPUnit 9.5.10 by Sebastian Bergmann and contributors.
Time: 00:05.053, Memory: 20.00 MB
OK (1 test, 16 assertions)

It also works in a browser, i.e. if I make a request to /download/9 I am served the appropriate PDF.

The problem I'm having is on GitHub. When I run the unit test there it fails the CI with this error:

Warning Error: copy(/home/runner/work/my-app/webroot/docs/75e57e4a-2149-4270-9d76-c7c8f0298c2c.pdf): Failed to open stream: No such file or directory
In [/home/runner/work/my-app/tests/TestCase/Controller/DocsControllerTest.php, line 745]

Given that this works locally I can't understand why this error is occurring. Is there some restriction with using copy() in GitHub's CI?

The directory and files at /full/path/to/testFiles/ are not .gitignore'd so they are committed with the rest of the repo code. So the test file, 75e57e4a-2149-4270-9d76-c7c8f0298c2c.pdf, exists within the codebase on GitHub.

I am using PHPUnit 9.5.10, PHP 8.0 on a Mac running macOS Monterey (12.2).


问:
converting a string to lowercase/uppercase depending upon the count of upper/lower case characters in it
i have to output a string in all uppercase if count of uppercase characters in it is more otherwise lowercase string will be shown if lowercase characters are more in the string,in case both characters are equal i will print the string in lowercase only
this the code i have written , but , it's not giving desired output,like it is returning the same string back to me , please help me with the errors

here's the code,i am using c++.

```<code>string s;
cin>>s;
int uc=0,lc=0;
for (int i = 0; i < s.size(); i++)
{
    if(isupper(s[i])){
        uc++;
    }
    else{
        lc++;
    }
}
if(uc>lc){
    for (int j = 0; j < s.size(); j++)
    {
        toupper(s[j]);

    }
    cout<<s<<endl;
}
else{
    for (int k = 0; k < s.size(); k++)
    {
        tolower(s[k]);
    }
    cout<<s<<endl;
}
</code>```

答:
Your problem is that your are not re-assigning the respective characters of your string resulting in your input string being untouched.

You need to do:

```<code>s[j] = toupper(s[j])
s[k] = tolower(s[k]);
</code>```

Another approach is to convert the string as a whole after your counting procedure - requires to include <algorithm> (credits to this answer):

```<code>if (uc > lc) {
    std::transform(s.begin(), s.end(), s.begin(), ::toupper);
}
else {
    std::transform(s.begin(), s.end(), s.begin(), ::tolower);
}
</code>```

Body:
i have to output a string in all uppercase if count of uppercase characters in it is more otherwise lowercase string will be shown if lowercase characters are more in the string,in case both characters are equal i will print the string in lowercase only
this the code i have written , but , it's not giving desired output,like it is returning the same string back to me , please help me with the errors

here's the code,i am using c++.

string s;
cin>>s;
int uc=0,lc=0;
for (int i = 0; i < s.size(); i++)
{
    if(isupper(s[i])){
        uc++;
    }
    else{
        lc++;
    }
}
if(uc>lc){
    for (int j = 0; j < s.size(); j++)
    {
        toupper(s[j]);

    }
    cout<<s<<endl;
}
else{
    for (int k = 0; k < s.size(); k++)
    {
        tolower(s[k]);
    }
    cout<<s<<endl;
}

Body:
Your problem is that your are not re-assigning the respective characters of your string resulting in your input string being untouched.

You need to do:

s[j] = toupper(s[j])
s[k] = tolower(s[k]);

Another approach is to convert the string as a whole after your counting procedure - requires to include <algorithm> (credits to this answer):

if (uc > lc) {
    std::transform(s.begin(), s.end(), s.begin(), ::toupper);
}
else {
    std::transform(s.begin(), s.end(), s.begin(), ::tolower);
}


问:
Can I remove the default root in a Rails application without creating a new one?
When creating a new Rails application, by default it serves a "Welcome to Rails" page at / unless you specify an alternative root in routes.rb.

My application currently only serves things from a subpath (e.g. /api/v1/) so accessing / should result in a 404. How can I accomplish this?

答: By default, rails will render 404 default page(not welcome page) in production.</p>


问:
The current Flutter SDK version is 0.0.0-unknown
I am not using GIT. As i have seen some posts/questions where users are mentioning they are using GIT and due to that they are getting the error.

Yesterday, I added Image Cropper Plugin and then I restarted the machine. After the restart, it starts giving the error.

```<code>The current Flutter SDK version is 0.0.0-unknown.

Because image_cropper 1.2.1 requires Flutter SDK version ^1.12.13 and no versions of image_cropper match >1.2.1 <2.0.0, image_cropper ^1.2.1 is forbidden.
So, because demoapp depends on image_cropper ^1.2.1, version solving failed.
pub get failed (1; So, because demoapp depends on image_cropper ^1.2.1, version solving failed.)
Exited (1)
</code>```

I run Flutter version command -> Below is the output.

```<code>Flutter 1.12.13+hotfix.9 • channel stable • https://github.com/flutter/flutter.git
Framework • revision f139b11009 (6 weeks ago) • 2020-03-30 13:57:30 -0700
Engine • revision af51afceb8
Tools • Dart 2.7.2
</code>```

I did Flutter Clean and Flutter Pub Get they both didn't fix the issue.

I run Flutter Doctor and here is the output.

```<code>flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, v1.12.13+hotfix.9, on Mac OS X 10.15.3 19D76, locale en-IN)

[✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
[✗] Xcode - develop for iOS and macOS
    ✗ Xcode installation is incomplete; a full installation is necessary for iOS development.
      Download at: https://developer.apple.com/xcode/download/
      Or install Xcode via the App Store.
      Once installed, run:
        sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer
        sudo xcodebuild -runFirstLaunch
    ✗ CocoaPods not installed.
        CocoaPods is used to retrieve the iOS and macOS platform side's plugin code that responds to your plugin usage on the
        Dart side.
        Without CocoaPods, plugins will not work on iOS or macOS.
        For more info, see https://flutter.dev/platform-plugins
      To install:
        sudo gem install cocoapods
[✓] Android Studio (version 3.1)
[✓] VS Code (version 1.44.2)
[✓] Connected device (1 available)

! Doctor found issues in 1 category.
</code>```

I am not using Xcode from the beginning.

Any advice on how to fix this issue.

Edit

I checked the path by running echo $PATH.

```<code>/Users/rahul/Desktop/flutter/bin
</code>```

Path is also there.

Edit 2
Flutter Upgrade also didn't helped.

答:
my flutter installation was git clone --depth=1
so I removed the whole dir: rm -rf flutter
then git clone once again. this time the full repository.

I think it solved the issue.
pub get works again, and flutter can build/run.

Body:
I am not using GIT. As i have seen some posts/questions where users are mentioning they are using GIT and due to that they are getting the error.

Yesterday, I added Image Cropper Plugin and then I restarted the machine. After the restart, it starts giving the error.

The current Flutter SDK version is 0.0.0-unknown.

Because image_cropper 1.2.1 requires Flutter SDK version ^1.12.13 and no versions of image_cropper match >1.2.1 <2.0.0, image_cropper ^1.2.1 is forbidden.
So, because demoapp depends on image_cropper ^1.2.1, version solving failed.
pub get failed (1; So, because demoapp depends on image_cropper ^1.2.1, version solving failed.)
Exited (1)

I run Flutter version command -> Below is the output.

Flutter 1.12.13+hotfix.9 • channel stable • https://github.com/flutter/flutter.git
Framework • revision f139b11009 (6 weeks ago) • 2020-03-30 13:57:30 -0700
Engine • revision af51afceb8
Tools • Dart 2.7.2

I did Flutter Clean and Flutter Pub Get they both didn't fix the issue.

I run Flutter Doctor and here is the output.

flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, v1.12.13+hotfix.9, on Mac OS X 10.15.3 19D76, locale en-IN)

[✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
[✗] Xcode - develop for iOS and macOS
    ✗ Xcode installation is incomplete; a full installation is necessary for iOS development.
      Download at: https://developer.apple.com/xcode/download/
      Or install Xcode via the App Store.
      Once installed, run:
        sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer
        sudo xcodebuild -runFirstLaunch
    ✗ CocoaPods not installed.
        CocoaPods is used to retrieve the iOS and macOS platform side's plugin code that responds to your plugin usage on the
        Dart side.
        Without CocoaPods, plugins will not work on iOS or macOS.
        For more info, see https://flutter.dev/platform-plugins
      To install:
        sudo gem install cocoapods
[✓] Android Studio (version 3.1)
[✓] VS Code (version 1.44.2)
[✓] Connected device (1 available)

! Doctor found issues in 1 category.

I am not using Xcode from the beginning.

Any advice on how to fix this issue.

Edit

I checked the path by running echo $PATH.

/Users/rahul/Desktop/flutter/bin

Path is also there.

Edit 2
Flutter Upgrade also didn't helped.


问:
How can i change the language of flutter app?
I want to make a dropdown item list of different languages and when user selects one of these app language should change. I don't know what logic to apply for changing language please help me.</p>

答:
I have found translator's:

https://pub.dev/packages/translator

https://pub.dev/packages/flutter_translate

https://pub.dev/packages/google_translator

By the plugins I writtend you have documentations but you also can go to youtube and look a tutorial about them.

Next time you can simple google what you want to have or go to pub.dev and writte in the search bar what you want.

I wish you a good day!


问:
How to grab specific details of device from result file using Python

I have more than 100 Apple Devices in my office. I want the details of particular device I want

I used PyAtv a python module to scan the devices which are on my network.

So I created a script which gives me the result like this when called.

```<code>rexter@rexter-pc:~$ python3 scan.py

Scan Results
========================================
       Name: Himanshu Gupta’s Mac mini (intel)
   Model/SW: Macmini8,1, Unknown OS
    Address: 192.168.3.243
        MAC: F0:18:98:EF:D2:E6
 Deep Sleep: False
Identifiers:
 - F0:18:98:EF:D2:E6
 - F01898EFD2E6
Services:
 - Protocol: AirPlay, Port: 7000, Credentials: None, Requires Password: False, Password: None, Pairing: Mandatory
 - Protocol: RAOP, Port: 7000, Credentials: None, Requires Password: False, Password: None, Pairing: Mandatory

       Name: Home Cinema
   Model/SW: Apple TV 4K, tvOS 14.4 build 18K802
    Address: 192.168.3.19
        MAC: C8:D0:83:B0:70:C7
 Deep Sleep: False
Identifiers:
 - C8:D0:83:B0:70:C7
 - 257B0C06-0227-4E42-AEEA-3C2C42B3E829
 - C8D083B070C7
Services:
 - Protocol: AirPlay, Port: 7000, Credentials: None, Requires Password: False, Password: None, Pairing: Mandatory
 - Protocol: Companion, Port: 49152, Credentials: None, Requires Password: False, Password: None, Pairing: Mandatory
 - Protocol: MRP, Port: 49153, Credentials: None, Requires Password: False, Password: None, Pairing: Optional
 - Protocol: RAOP, Port: 7000, Credentials: None, Requires Password: False, Password: None, Pairing: Mandatory

       Name: Pluto - GROUND FLOOR
   Model/SW: ShairportSync, Unknown OS
    Address: 172.17.100.55
        MAC: None
 Deep Sleep: False
Identifiers:
 - E4BB83B4A641
Services:
 - Protocol: RAOP, Port: 8901, Credentials: None, Requires Password: False, Password: None, Pairing: NotNeeded

       Name: 2424
   Model/SW: Apple TV 4K, tvOS 15.0
    Address: 172.17.88.11
        MAC: DC:56:E7:59:79:46
 Deep Sleep: False
Identifiers:
 - DC:56:E7:59:79:46
 - DC56E7597946
Services:
 - Protocol: Companion, Port: 49152, Credentials: None, Requires Password: False, Password: None, Pairing: Mandatory
 - Protocol: AirPlay, Port: 7000, Credentials: None, Requires Password: False, Password: None, Pairing: Mandatory
 - Protocol: RAOP, Port: 7000, Credentials: None, Requires Password: False, Password: None, Pairing: Mandatory
</code>```

But I want to get the results of specific device

```<code>EXAMPLE >>> python3 scan.py 2424

       Name: 2424
   Model/SW: Apple TV 4K, tvOS 15.0
    Address: 172.17.88.11
        MAC: DC:56:E7:59:79:46
 Deep Sleep: False
Identifiers:
 - DC:56:E7:59:79:46
 - DC56E7597946
Services:
 - Protocol: Companion, Port: 49152, Credentials: None, Requires Password: False, Password: None, Pairing: Mandatory
 - Protocol: AirPlay, Port: 7000, Credentials: None, Requires Password: False, Password: None, Pairing: Mandatory
 - Protocol: RAOP, Port: 7000, Credentials: None, Requires Password: False, Password: None, Pairing: Mandatory
</code>```

I tried a lot but the challenge I face is Multiple Services and Identifiers in the results

Any help is appreciated! Thanks!

答:
I assume you are using the scan function.

The scan function returns a List[interface.BaseConfig].

The BaseConfig contains the property name.

So, you can try:

```<code>name = '2424'

devices = scan(...)

for device in device:
    if device.name == name:
        my_device = device
</code>```

Body:
I have more than 100 Apple Devices in my office. I want the details of particular device I want

I used PyAtv a python module to scan the devices which are on my network.

So I created a script which gives me the result like this when called.

rexter@rexter-pc:~$ python3 scan.py

Scan Results
========================================
       Name: Himanshu Gupta’s Mac mini (intel)
   Model/SW: Macmini8,1, Unknown OS
    Address: 192.168.3.243
        MAC: F0:18:98:EF:D2:E6
 Deep Sleep: False
Identifiers:
 - F0:18:98:EF:D2:E6
 - F01898EFD2E6
Services:
 - Protocol: AirPlay, Port: 7000, Credentials: None, Requires Password: False, Password: None, Pairing: Mandatory
 - Protocol: RAOP, Port: 7000, Credentials: None, Requires Password: False, Password: None, Pairing: Mandatory

       Name: Home Cinema
   Model/SW: Apple TV 4K, tvOS 14.4 build 18K802
    Address: 192.168.3.19
        MAC: C8:D0:83:B0:70:C7
 Deep Sleep: False
Identifiers:
 - C8:D0:83:B0:70:C7
 - 257B0C06-0227-4E42-AEEA-3C2C42B3E829
 - C8D083B070C7
Services:
 - Protocol: AirPlay, Port: 7000, Credentials: None, Requires Password: False, Password: None, Pairing: Mandatory
 - Protocol: Companion, Port: 49152, Credentials: None, Requires Password: False, Password: None, Pairing: Mandatory
 - Protocol: MRP, Port: 49153, Credentials: None, Requires Password: False, Password: None, Pairing: Optional
 - Protocol: RAOP, Port: 7000, Credentials: None, Requires Password: False, Password: None, Pairing: Mandatory

       Name: Pluto - GROUND FLOOR
   Model/SW: ShairportSync, Unknown OS
    Address: 172.17.100.55
        MAC: None
 Deep Sleep: False
Identifiers:
 - E4BB83B4A641
Services:
 - Protocol: RAOP, Port: 8901, Credentials: None, Requires Password: False, Password: None, Pairing: NotNeeded

       Name: 2424
   Model/SW: Apple TV 4K, tvOS 15.0
    Address: 172.17.88.11
        MAC: DC:56:E7:59:79:46
 Deep Sleep: False
Identifiers:
 - DC:56:E7:59:79:46
 - DC56E7597946
Services:
 - Protocol: Companion, Port: 49152, Credentials: None, Requires Password: False, Password: None, Pairing: Mandatory
 - Protocol: AirPlay, Port: 7000, Credentials: None, Requires Password: False, Password: None, Pairing: Mandatory
 - Protocol: RAOP, Port: 7000, Credentials: None, Requires Password: False, Password: None, Pairing: Mandatory

But I want to get the results of specific device

EXAMPLE >>> python3 scan.py 2424

       Name: 2424
   Model/SW: Apple TV 4K, tvOS 15.0
    Address: 172.17.88.11
        MAC: DC:56:E7:59:79:46
 Deep Sleep: False
Identifiers:
 - DC:56:E7:59:79:46
 - DC56E7597946
Services:
 - Protocol: Companion, Port: 49152, Credentials: None, Requires Password: False, Password: None, Pairing: Mandatory
 - Protocol: AirPlay, Port: 7000, Credentials: None, Requires Password: False, Password: None, Pairing: Mandatory
 - Protocol: RAOP, Port: 7000, Credentials: None, Requires Password: False, Password: None, Pairing: Mandatory

I tried a lot but the challenge I face is Multiple Services and Identifiers in the results

Any help is appreciated! Thanks!

Body:
I assume you are using the scan function.

The scan function returns a List[interface.BaseConfig].

The BaseConfig contains the property name.

So, you can try:

name = '2424'

devices = scan(...)

for device in device:
    if device.name == name:
        my_device = device


问:
how can i fix this runtime error for a simple code written in c?
My code shows me a wrong output by showing the area to be zero:

```<code>#include <stdio.h>
double calc(float rad);
void main(void) {
    float rad;
    printf("Enter the circle radius: \n");
    scanf("%f",&rad);
    printf("You entered: %f\n",rad);
        printf("Area is %d\n",calc(rad));
    if(calc(rad)>1000){
       printf("Area is > 1000");
    }
    else{
         printf("Area is < 1000");
    }

}

double calc(float rad){
   double area=3.14*rad*rad;
   return area;
}
</code>```

Output:

Enter the circle radius : 20
you entered 20.000000
area is 0
area > 1000
```
<p>Desired output:</p>
<pre class="lang-none prettyprint-override"><code>Enter the circle radius : 20
you entered 20.000000
area is 1256.000000
area > 1000
</code>```

答: The erroneous output is as a result of using %d instead of %lf for double or %f for float in your printf statement. Turning on compiler warning -Wformat will highlight this during compilation

Body:
My code shows me a wrong output by showing the area to be zero:

#include <stdio.h>
double calc(float rad);
void main(void) {
    float rad;
    printf("Enter the circle radius: \n");
    scanf("%f",&rad);
    printf("You entered: %f\n",rad);
        printf("Area is %d\n",calc(rad));
    if(calc(rad)>1000){
       printf("Area is > 1000");
    }
    else{
         printf("Area is < 1000");
    }

}

double calc(float rad){
   double area=3.14*rad*rad;
   return area;
}

Output:

Enter the circle radius : 20
you entered 20.000000
area is 0
area > 1000

Desired output:

Enter the circle radius : 20
you entered 20.000000
area is 1256.000000
area > 1000


问:
Separating a string with large letters into words that begin with the same letters
Suppose you have a string "TodayIsABeautifulDay". How can we get separate it in Python into words like this ["Today", "Is", "A", "Beautiful", "Day"]?</p>

答:
First, use an empty list ‘words’ and append the first letter of ‘word’ to it.
Now using a for loop, check if the current character is in lower case or not, if yes append it to the current string, otherwise, if uppercase, begin a new individual string.

```<code>def split_words(word):
words = [[word[0]]]

for char in word[1:]:
    if words[-1][-1].islower() and char.isupper():
        words.append(list(char))
    else:
        words[-1].append(char)

return [''.join(word) for word in words]
</code>```

You can use this function :

```<code>word = "TodayIsABeautifulDay"
print(split_words(word))
</code>```

Body:
First, use an empty list ‘words’ and append the first letter of ‘word’ to it.
Now using a for loop, check if the current character is in lower case or not, if yes append it to the current string, otherwise, if uppercase, begin a new individual string.

def split_words(word):
words = [[word[0]]]

for char in word[1:]:
    if words[-1][-1].islower() and char.isupper():
        words.append(list(char))
    else:
        words[-1].append(char)

return [''.join(word) for word in words]

You can use this function :

word = "TodayIsABeautifulDay"
print(split_words(word))


问:
How to handle views.py after joining two models in Django?
Here I've two models first one is Contact and second model is Sent_replies. So, what should I do in views.py so that If anyone send response in Contact, the data will also update in the Sent_replies model

models.py

```<code>class Contact(models.Model):
    message_id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=100)
    email = models.CharField(max_length=100)
    phone = models.CharField(max_length=100)
    comment = models.TextField(max_length=100)
    date = models.DateField()

    def __str__(self):
        return self.name
</code>```
```<code>class Sent_replies(models.Model):
    message_sender = models.ForeignKey(Contact,on_delete=models.CASCADE, null=True)
    def __str__(self):
        return self.message.name
</code>```

views.py

```<code>def contact(request):
    if request.method == "POST":
        name = request.POST.get("name")
        email = request.POST.get("email")
        phone = request.POST.get("phone")
        comment = request.POST.get("comment")
        if name != "":
            contact = Contact(name=name, email=email, phone=phone, comment=comment, date=datetime.today())
            contact.save()
            messages.success(request, 'Your response has been submitted successfully!!!')
    return render(request, 'contact.html')
</code>```

答:
there are way of doing this, logic in your view only or create a signal to handle it.

logic in your views.py:

```<code>if name != "":
     contact = Contact.objects.create(name=name, email=email, phone=phone, comment=comment, date=datetime.today())
     Sent_replies.objects.create(message_sender=contact)
</code>```

Using signal in your models.py file

```<code>from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=Contact)
def add_reply(sender, instance, created, **kwargs):
    if created == True:
       Sent_replies.objects.create(message_sender=instance)
</code>```

Body:
Here I've two models first one is Contact and second model is Sent_replies. So, what should I do in views.py so that If anyone send response in Contact, the data will also update in the Sent_replies model

models.py

class Contact(models.Model):
    message_id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=100)
    email = models.CharField(max_length=100)
    phone = models.CharField(max_length=100)
    comment = models.TextField(max_length=100)
    date = models.DateField()

    def __str__(self):
        return self.name

class Sent_replies(models.Model):
    message_sender = models.ForeignKey(Contact,on_delete=models.CASCADE, null=True)
    def __str__(self):
        return self.message.name

views.py

def contact(request):
    if request.method == "POST":
        name = request.POST.get("name")
        email = request.POST.get("email")
        phone = request.POST.get("phone")
        comment = request.POST.get("comment")
        if name != "":
            contact = Contact(name=name, email=email, phone=phone, comment=comment, date=datetime.today())
            contact.save()
            messages.success(request, 'Your response has been submitted successfully!!!')
    return render(request, 'contact.html')

Body:
there are way of doing this, logic in your view only or create a signal to handle it.

logic in your views.py:

if name != "":
     contact = Contact.objects.create(name=name, email=email, phone=phone, comment=comment, date=datetime.today())
     Sent_replies.objects.create(message_sender=contact)

Using signal in your models.py file

from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=Contact)
def add_reply(sender, instance, created, **kwargs):
    if created == True:
       Sent_replies.objects.create(message_sender=instance)


问:
Creating a simple graph using pandas and Networkx
I am trying to figure out from the documentation how to create a simple graph using the pandas dataframe and the NetworkX package, but I couldn't get the solution. Below the final result I would like.

答:
This might help:

import pandas as pd
import networkx as nx

df = pd.DataFrame(
    {"from": ["A", "A", "A", "C"], "to": ["B", "C", "D", "D"], "weight": [10, 5, 4, 1]}
)

G = nx.from_pandas_edgelist(
    df, source="from", target="to", edge_attr=["weight"], create_using=nx.DiGraph
)
pos = nx.spring_layout(G)  # node positions

edge_labels = nx.get_edge_attributes(G, "weight") # labels to use for edges

nx.draw(G, pos, with_labels=True)
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
```


问:
EntityFrameworkCore is there a way to create EnumToStringConverter without passing the enum type as generic?
I am trying to use EntityFrameworkCore ORM to interact with my databases. By default, EntityFrameworkCore seems to store enum as int instead of string.

However, I would like to store the value in the database as a string. I can see that EntityFrameworkCore ships with a converter called EnumToStringConverter.

I am trying to use reflection to setup the model builder so I don't have to manually build each model.

The issue that I am running into is that EnumToStringConverter accepts a generic type which must be an enum. But since I am trying to use reflection here I am unable to pass the enum type when creating the converter

Here is what my code look like so far

```<code>protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    // Get all DbSet<> properties that are defined in the DbContext
    var modelTypes = typeof(DataContext).GetProperties()
                                        .Where(x => x.PropertyType.IsGenericType && x.PropertyType.GetGenericTypeDefinition() == typeof(DbSet<>))
                                        .Select(x => x.PropertyType.GetGenericArguments().First())
                                        .ToList();

    foreach (Type modelType in modelTypes)
    {
        var properties = modelType.GetProperties();

        foreach (var property in properties)
        {
            if (IsPrimaryKey(property))
            {
                // At this point we know that the property is a primary key
                modelBuilder.Entity(modelType)
                            .Property(property.Name)
                            .UseSqlServerIdentityColumn()
                            .Metadata.BeforeSaveBehavior = PropertySaveBehavior.Ignore;

                continue;
            }

            if (property.PropertyType.IsEnum)
            {
                // At this point we know that the property is an enum.
                // Add the EnumToStringConverter converter to the property so that
                // the value is stored in the database as a string instead of number
                var converter = new EnumToStringConverter(); // if somehow I can change this code to something like var `new EnumToStringConverter(property.PropertyType);` the code would work

                modelBuilder.Entity(modelType)
                            .Property(property.Name)
                            .HasConversion(converter);

                continue;
            }

        }
    }
}
</code>```

The only issue with the above code is how EnumToStringConverter is constructed. If somehow I can provide a Type to the constructor of the EnumToStringConverter instead of passing it as a generic argument that would solve the problem.

答:
As of EF core v6.0.0-preview6, there is a more elegant solution to register a ValueConverter globally. Since EFcore already ships with a EnumToStringConverter, just add these lines to your DbContext class:

protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
{
    // Instead of numeric conversion that EFcore uses by default
    configurationBuilder.Properties<Enum>().HaveConversion<string>();
}
```

and all properties of type Enum will be serialized as string, rather than numbers.

Body:
I am trying to use EntityFrameworkCore ORM to interact with my databases. By default, EntityFrameworkCore seems to store enum as int instead of string.

However, I would like to store the value in the database as a string. I can see that EntityFrameworkCore ships with a converter called EnumToStringConverter.

I am trying to use reflection to setup the model builder so I don't have to manually build each model.

The issue that I am running into is that EnumToStringConverter accepts a generic type which must be an enum. But since I am trying to use reflection here I am unable to pass the enum type when creating the converter

Here is what my code look like so far

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    // Get all DbSet<> properties that are defined in the DbContext
    var modelTypes = typeof(DataContext).GetProperties()
                                        .Where(x => x.PropertyType.IsGenericType && x.PropertyType.GetGenericTypeDefinition() == typeof(DbSet<>))
                                        .Select(x => x.PropertyType.GetGenericArguments().First())
                                        .ToList();

    foreach (Type modelType in modelTypes)
    {
        var properties = modelType.GetProperties();

        foreach (var property in properties)
        {
            if (IsPrimaryKey(property))
            {
                // At this point we know that the property is a primary key
                modelBuilder.Entity(modelType)
                            .Property(property.Name)
                            .UseSqlServerIdentityColumn()
                            .Metadata.BeforeSaveBehavior = PropertySaveBehavior.Ignore;

                continue;
            }

            if (property.PropertyType.IsEnum)
            {
                // At this point we know that the property is an enum.
                // Add the EnumToStringConverter converter to the property so that
                // the value is stored in the database as a string instead of number
                var converter = new EnumToStringConverter(); // if somehow I can change this code to something like var `new EnumToStringConverter(property.PropertyType);` the code would work

                modelBuilder.Entity(modelType)
                            .Property(property.Name)
                            .HasConversion(converter);

                continue;
            }

        }
    }
}

The only issue with the above code is how EnumToStringConverter is constructed. If somehow I can provide a Type to the constructor of the EnumToStringConverter instead of passing it as a generic argument that would solve the problem.

Body:
As of EF core v6.0.0-preview6, there is a more elegant solution to register a ValueConverter globally. Since EFcore already ships with a EnumToStringConverter, just add these lines to your DbContext class:

protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
{
    // Instead of numeric conversion that EFcore uses by default
    configurationBuilder.Properties<Enum>().HaveConversion<string>();
}

and all properties of type Enum will be serialized as string, rather than numbers.


问:
antd menu icons API not working. Does not render
im trying to render a a side menu with a submenu , however i soon realize that the icon api is not working:

```<code>                  <Menu.Item key="1" >
                        <HomeOutlined />
                        <span>Home</span>
                        <Link to='/' />
                    </Menu.Item>
</code>```

This is one of the menu items , it renders correctly if i were to place the icon within the menu.item.
However when i do this :

```<code>                   <Menu.Item key="1" icon={<HomeOutlined/>}>
                        <span>Home</span>
                        <Link to='/' />
                    </Menu.Item>
</code>```

The icon no longer shows. I have no issues for the first approach , however when i try to tranplant the 1st approach to a submenu :

```<code>             <SubMenu key="sub1" title="Settings">
                        <SettingFilled />
                    <Menu.Item key="7" onClick={this.props.logout}>
                        <span>Logout</span>
                    </Menu.Item>
                    </SubMenu>
</code>```

It would render the icon inside the inner dropdown instead of where its supposed to be

答:
You can do this: -

```<code><SubMenu key="sub1" title={<span><UserOutlined /><span>Settings</span></span>}>
    <SettingFilled />
    <Menu.Item key="7" onClick={this.props.logout}>
         <span>Logout</span>
    </Menu.Item>
</code>```

But there will be an issue of padding as the padding of Menu.Item is given relative to the title of the Sub-Menu and the padding is given as inline-css so you will not be able to override the css and it's a bad habit to use important. Here, you are using  so if you want the content aligned than you can give padding to the Link.

Body:
im trying to render a a side menu with a submenu , however i soon realize that the icon api is not working:

                  <Menu.Item key="1" >
                        <HomeOutlined />
                        Home
                        <Link to='/' />
                    </Menu.Item>

This is one of the menu items , it renders correctly if i were to place the icon within the menu.item.
However when i do this :

                   <Menu.Item key="1" icon={<HomeOutlined/>}>
                        Home
                        <Link to='/' />
                    </Menu.Item>

The icon no longer shows. I have no issues for the first approach , however when i try to tranplant the 1st approach to a submenu :

             <SubMenu key="sub1" title="Settings">
                        <SettingFilled />
                    <Menu.Item key="7" onClick={this.props.logout}>
                        Logout
                    </Menu.Item>
                    </SubMenu>

It would render the icon inside the inner dropdown instead of where its supposed to be

Body:
You can do this: -

<SubMenu key="sub1" title={<span><UserOutlined /><span>Settings</span></span>}>
    <SettingFilled />
    <Menu.Item key="7" onClick={this.props.logout}>
         <span>Logout</span>
    </Menu.Item>

But there will be an issue of padding as the padding of Menu.Item is given relative to the title of the Sub-Menu and the padding is given as inline-css so you will not be able to override the css and it's a bad habit to use important. Here, you are using  so if you want the content aligned than you can give padding to the Link.


问:
unable to change kivymd button line color
Ive tried using line_color function as provided in the docs, but it makes of  no use

```<code>from kivymd.app import MDApp
from kivy.lang import Builder
from kivy.factory import Factory
from kivymd.uix.selectioncontrol import MDCheckbox
from kivy.uix.behaviors import ButtonBehavior

Root="""
#:import hex kivy.utils.get_color_from_hex
BoxLayout:
    id:Layout_1

    MDRoundFlatButton:

        size_hint:None,None
        text:"MDRoundFlatButton"
        theme_text_color: "Custom"
        font_size:16
        size_hint_y:.05
        id:btn
        line_color: 1,1,0,1
        md_bg_color:1,1,1,1

    MDRectangleFlatButton:
        text: "MDRECTANGLEFLATBUTTON"
        theme_text_color: "Custom"
        text_color: 1, 0, 0, 1
        line_color: 1,1,0,1

"""

class Main(MDApp):
    def build(self):
        return Builder.load_string(Root)

Main().run()
</code>```

The desired line color was yellow for the first button

答:
Suddenly it will still be relevant. I configured these colors in this form and everything worked:

line_color: [255/255,255/255,255/255,1] color_active : [130/255,46/255,24/255,1] text_color : [196/255,196/255,196/255,1]

Body:
Ive tried using line_color function as provided in the docs, but it makes of  no use

from kivymd.app import MDApp
from kivy.lang import Builder
from kivy.factory import Factory
from kivymd.uix.selectioncontrol import MDCheckbox
from kivy.uix.behaviors import ButtonBehavior

Root="""
#:import hex kivy.utils.get_color_from_hex
BoxLayout:
    id:Layout_1

    MDRoundFlatButton:

        size_hint:None,None
        text:"MDRoundFlatButton"
        theme_text_color: "Custom"
        font_size:16
        size_hint_y:.05
        id:btn
        line_color: 1,1,0,1
        md_bg_color:1,1,1,1

    MDRectangleFlatButton:
        text: "MDRECTANGLEFLATBUTTON"
        theme_text_color: "Custom"
        text_color: 1, 0, 0, 1
        line_color: 1,1,0,1

"""

class Main(MDApp):
    def build(self):
        return Builder.load_string(Root)

Main().run()

The desired line color was yellow for the first button


答:
while there are many ways to do with css, divs, and style property and stuff
the simpliest way is not to use align="center" but to wrap the table in   tag :)

Note: the center element is considered obsolete in HTML5.

Title: Table align="center" doesn't seem to be working

Body:
Why would the align="center" not be working on the first table on the page below:

http://eurochlor.amaze.com/chlorinated-solvents-%28ecsa%29/about-chlorinated-solvents/facts-figures/trichloroethylene.aspx

Body:
while there are many ways to do with css, divs, and style property and stuff
the simpliest way is not to use align="center" but to wrap the table in <center> </center> tag :)

Note: the center element is considered obsolete in HTML5.


问:
what should java.testMethod be set to for vscode to run junit tests
vscode 1.52 redhat 7.7

I believe I have all the extensions I need installed ( although the maven extension failed to install it looks like the pom file was read ). When I open a junit test case I see "run all Tests". When I select it I get an error

set "java.testMethod"" in ./vscode/settings.json

I've searched the web and the vscode documentation but am not finding a reference to java.testMethod so I don't have any idea what to set it to. I am also puzzled that it refers to .vscode/settings.json when that file is under .config/Code/User

答: Had very similar issue and it turns out finally that some extensions which I unconsciously installed were fine by the time there was an update.After reintsalling only needed extensions all went back to working mode.Be sure the Test Runner for java (should be in Extension Pack for Java) is enabled.</p>


问:
Python look up value in same week, different product
Using python data frames, I want to find the volume of different products and get them together in one line. The basic is like this:

Week
Product
Volume

1
Drink
5

2
Drink
5

1
Burger
3

2
Burger
2

3
Drink
10

3
Burger
4

And I would like the output to be like this. Where the volume of the product of that week is obvious, but I don't know how else to visualize this. The goal is to see if in the week where we had a promotion on drinks and sold 10, the sale of burgers also went up.

The only thing is this is divided over 4 stores, 2 products and 5 variants per product.

Week
Product
Volume
Volume Burger
Volume Drink

1
Drink
5
3
5

2
Drink
5
2
5

1
Burger
3
3
5

2
Burger
2
2
5

3
Drink
10
4
10

3
Burger
4
10
4

What I tried:
First tried with groupby Product/Week and use shift. But this does not work with multiple products.

Then tried something like this:

```<code>data['Volume Burgers'] = data['Volume'].loc[('Product' == 'Burger') & ('Week' == 'Week')]
</code>```

答:
IIUC, use a combination of pivot and merge:

```<code>df.merge(df.pivot(index='Week', columns='Product', values='Volume')
           .add_prefix('Volume '),
         left_on='Week', right_index=True)
</code>```

output:

```<code>   Week  Product  Volume  Volume Burger   Volume Drink
0     1   Drink        5               3              5
2     1  Burger        3               3              5
1     2   Drink        5               2              5
3     2  Burger        2               2              5
4     3   Drink       10               4             10
5     3  Burger        4               4             10
</code>```

Body:
Using python data frames, I want to find the volume of different products and get them together in one line. The basic is like this:

Week
Product
Volume

1
Drink
5

2
Drink
5

1
Burger
3

2
Burger
2

3
Drink
10

3
Burger
4

And I would like the output to be like this. Where the volume of the product of that week is obvious, but I don't know how else to visualize this. The goal is to see if in the week where we had a promotion on drinks and sold 10, the sale of burgers also went up.

The only thing is this is divided over 4 stores, 2 products and 5 variants per product.

Week
Product
Volume
Volume Burger
Volume Drink

1
Drink
5
3
5

2
Drink
5
2
5

1
Burger
3
3
5

2
Burger
2
2
5

3
Drink
10
4
10

3
Burger
4
10
4

What I tried:
First tried with groupby Product/Week and use shift. But this does not work with multiple products.

Then tried something like this:

data['Volume Burgers'] = data['Volume'].loc[('Product' == 'Burger') & ('Week' == 'Week')]

Body:
IIUC, use a combination of pivot and merge:

df.merge(df.pivot(index='Week', columns='Product', values='Volume')
           .add_prefix('Volume '),
         left_on='Week', right_index=True)

output:

   Week  Product  Volume  Volume Burger   Volume Drink
0     1   Drink        5               3              5
2     1  Burger        3               3              5
1     2   Drink        5               2              5
3     2  Burger        2               2              5
4     3   Drink       10               4             10
5     3  Burger        4               4             10