问:
Symfony 6, selection of three select fields (Department -> Commune -> Arrondissement)
I was about to set up a form with Symfony 6 where the user must first select the department, then the municipality and finally the District to finish.
My problem is that I manage to correctly load the data of the municipality by choosing the department, but I'm produced to load the data of the district by selecting a department. I think the problem comes from JS.
I used an eventlister to do it but it works for the first select but nothing for the second.

Departement Entity

```<code><?php

namespace App\Entity;

use App\Repository\DepartementRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity(repositoryClass: DepartementRepository::class)]
class Departement
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column]
    private ?int $id = null;

    #[ORM\Column(length: 100)]
    private ?string $nom = null;

    #[ORM\Column]
    private ?int $codeDepartement = null;

    #[ORM\OneToMany(mappedBy: 'departement', targetEntity: CommuneDistrict::class)]
    private Collection $communeDistricts;

    #[ORM\OneToMany(mappedBy: 'departement', targetEntity: ZoneTravail::class)]
    private Collection $zoneTravails;

    #[ORM\OneToMany(mappedBy: 'departementResidenceID01', targetEntity: Candidat::class)]
    private Collection $candidats;

    public function __construct()
    {
        $this->communeDistricts = new ArrayCollection();
        $this->zoneTravails = new ArrayCollection();
        $this->candidats = new ArrayCollection();
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getNom(): ?string
    {
        return $this->nom;
    }

    public function setNom(string $nom): self
    {
        $this->nom = $nom;

        return $this;
    }

    public function getCodeDepartement(): ?int
    {
        return $this->codeDepartement;
    }

    public function setCodeDepartement(int $codeDepartement): self
    {
        $this->codeDepartement = $codeDepartement;
        return $this;
    }

    /**
     * @return Collection<int, CommuneDistrict>
     */
    public function getCommuneDistricts(): Collection
    {
        return $this->communeDistricts;
    }

    public function addCommuneDistrict(CommuneDistrict $communeDistrict): self
    {
        if (!$this->communeDistricts->contains($communeDistrict)) {
            $this->communeDistricts->add($communeDistrict);
            $communeDistrict->setDepartement($this);
        }

        return $this;
    }

    public function removeCommuneDistrict(CommuneDistrict $communeDistrict): self
    {
        if ($this->communeDistricts->removeElement($communeDistrict)) {
            // set the owning side to null (unless already changed)
            if ($communeDistrict->getDepartement() === $this) {
                $communeDistrict->setDepartement(null);
            }
        }

        return $this;
    }

    public function __toString(): string
    {
        return $this->nom;
    }
}

</code>```

Commune Entity

```<code><?php

namespace App\Entity;

use App\Repository\CommuneDistrictRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity(repositoryClass: CommuneDistrictRepository::class)]
class CommuneDistrict
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column]
    private ?int $id = null;

    #[ORM\Column(length: 100)]
    private ?string $nom = null;

    #[ORM\Column(nullable: true)]
    private ?int $codeComDistr = null;

    #[ORM\ManyToOne(inversedBy: 'communeDistricts')]
    private ?Departement $departement = null;

    #[ORM\OneToMany(mappedBy: 'CommuneDistr', targetEntity: ArrCuCr::class)]
    private Collection $arrCuCrs;

    #[ORM\OneToMany(mappedBy: 'ComDistr', targetEntity: ZoneTravail::class)]
    private Collection $zoneTravails;

    #[ORM\OneToMany(mappedBy: 'communeResidenceID02', targetEntity: Candidat::class)]
    private Collection $candidats;

    public function __construct()
    {
        $this->arrCuCrs = new ArrayCollection();
        $this->zoneTravails = new ArrayCollection();
        $this->candidats = new ArrayCollection();
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getNom(): ?string
    {
        return $this->nom;
    }

    public function setNom(string $nom): self
    {
        $this->nom = $nom;

        return $this;
    }

    public function getCodeComDistr(): ?int
    {
        return $this->codeComDistr;
    }

    public function setCodeComDistr(?int $codeComDistr): self
    {
        $this->codeComDistr = $codeComDistr;

        return $this;
    }

    public function getDepartement(): ?Departement
    {
        return $this->departement;
    }

    public function setDepartement(?Departement $departement): self
    {
        $this->departement = $departement;

        return $this;
    }

    /**
     * @return Collection<int, ArrCuCr>
     */
    public function getArrCuCrs(): Collection
    {
        return $this->arrCuCrs;
    }

    public function addArrCuCr(ArrCuCr $arrCuCr): self
    {
        if (!$this->arrCuCrs->contains($arrCuCr)) {
            $this->arrCuCrs->add($arrCuCr);
            $arrCuCr->setCommuneDistr($this);
        }

        return $this;
    }

    public function removeArrCuCr(ArrCuCr $arrCuCr): self
    {
        if ($this->arrCuCrs->removeElement($arrCuCr)) {
            // set the owning side to null (unless already changed)
            if ($arrCuCr->getCommuneDistr() === $this) {
                $arrCuCr->setCommuneDistr(null);
            }
        }

        return $this;
    }

    public function __toString(): string
    {
        return $this->nom;
    }

}

</code>```

Arrondissement Entity

```<code><?php

namespace App\Entity;

use App\Repository\ArrCuCrRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity(repositoryClass: ArrCuCrRepository::class)]
class ArrCuCr
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column]
    private ?int $id = null;

    #[ORM\Column(length: 100)]
    private ?string $nom = null;

    #[ORM\Column]
    private ?int $code = null;

    #[ORM\ManyToOne(inversedBy: 'arrCuCrs')]
    private ?CommuneDistrict $CommuneDistr = null;

    #[ORM\OneToMany(mappedBy: 'ArrCuCr', targetEntity: ZoneTravail::class)]
    private Collection $zoneTravails;

    #[ORM\OneToMany(mappedBy: 'arrondissementResidenceID03', targetEntity: Candidat::class)]
    private Collection $candidats;

    public function __construct()
    {
        $this->zoneTravails = new ArrayCollection();
        $this->candidats = new ArrayCollection();
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getNom(): ?string
    {
        return $this->nom;
    }

    public function setNom(string $nom): self
    {
        $this->nom = $nom;

        return $this;
    }

    public function getCode(): ?int
    {
        return $this->code;
    }

    public function setCode(int $code): self
    {
        $this->code = $code;

        return $this;
    }

    public function getCommuneDistr(): ?CommuneDistrict
    {
        return $this->CommuneDistr;
    }

    public function setCommuneDistr(?CommuneDistrict $CommuneDistr): self
    {
        $this->CommuneDistr = $CommuneDistr;

        return $this;
    }

    public function __toString(): string
    {
        return $this->nom;
    }
}
</code>```

My Candidat Form

```<code><?php

namespace App\Form;

use App\Entity\ArrCuCr;
use App\Entity\Candidat;
use App\Entity\CommuneDistrict;
use App\Entity\Departement;
use App\Entity\Langue;
use App\Entity\NiveauEtude;
use App\Entity\ZoneTravail;
use FOS\CKEditorBundle\Form\Type\CKEditorType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\CountryType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Vich\UploaderBundle\Form\Type\VichFileType;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Validator\Constraints\Regex;
use Symfony\Component\Validator\Constraints\IsTrue;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\Form\FormInterface;
use App\Repository\DepartementRepository;
use App\Repository\CommuneDistrictRepository;
use App\Repository\ArrCuCrRepository;
use Doctrine\ORM\EntityRepository;

class CandidatType extends AbstractType
{
    private $countryRepository;
    private $StateRepository;
    private $stateCitiesRepository;

    public function __construct(
        DepartementRepository $countryRepository,
        CommuneDistrictRepository $stateRepository,
        ArrCuCrRepository $stateCitiesRepository
    ) {
        $this->countryRepository = $countryRepository;
        $this->StateRepository = $stateRepository;
        $this->stateCitiesRepository = $stateCitiesRepository;
    }

    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('departementResidenceID01', EntityType::class,[
                'class' => Departement::class,
                'label' => 'ID01.Dans quel département vivez-vous ?',
                'disabled' => false,
                'required' => true,
                'choice_label' => function(Departement $country) {
                    return $country->getNom();
                },
                'invalid_message' => 'Vous devez selectionner un departement',
                'placeholder' => 'Choisir departement',
            ])

         ->add('communeResidenceID02', ChoiceType::class, [
            'choices' => [],
            'placeholder' => 'Choisir une commune/district',
        ])
            ->add('arrondissementResidenceID03', ChoiceType::class, [
                'placeholder' => 'Choisir un arrondissement CU/CR',
            'choices' => [],
        ]);

        //**************** Start Commune Form
        $formModifier = function (FormInterface $form, Departement $sport = null) {
            $positions = null === $sport ? [] : $sport->getCommuneDistricts();

            $form->add('communeResidenceID02', EntityType::class, [
                'class' => CommuneDistrict::class,
                'placeholder' => '',
                'choices' => $positions,
            ]);
        };

        $builder->addEventListener(
            FormEvents::PRE_SET_DATA,
            function (FormEvent $event) use ($formModifier) {
                // this would be your entity, i.e. SportMeetup
                $data = $event->getData();
                $formModifier($event->getForm(), $data->getDepartementResidenceID01());
            }
        );

        $builder->get('departementResidenceID01')->addEventListener(
            FormEvents::POST_SUBMIT,
            function (FormEvent $event) use ($formModifier) {
                $sport = $event->getForm()->getData();
                $formModifier($event->getForm()->getParent(), $sport);
            }
        );
        //**************** End State Form

        //**************** Start Arr Form
        $formModifierArr = function (FormInterface $form, CommuneDistrict $commune = null) {
            $com = null === $commune ? [] : $commune->getArrCuCrs();

            $form->add('arrondissementResidenceID03', EntityType::class, [
                'class' => ArrCuCr::class,
                'placeholder' => '',
                'choices' => $com,
            ]);
        };

        $builder->addEventListener(
            FormEvents::PRE_SET_DATA,
            function (FormEvent $eventCom) use ($formModifierArr) {
                // this would be your entity, i.e. SportMeetup
                $data = $eventCom->getData();
                $formModifierArr($eventCom->getForm(), $data->getCommuneResidenceID02());
            }
        );

        $builder->get('communeResidenceID02')->addEventListener(
            FormEvents::POST_SUBMIT,
            function (FormEvent $ev) use ($formModifierArr) {
                $comR = $ev->getForm()->getData();
                $formModifierArr($ev->getForm()->getParent(), $comR);
            }
        );

    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'data_class' => Candidat::class,
            //'csrf_protection' => false,
        ]);
    }
}
</code>```

Body:
I was about to set up a form with Symfony 6 where the user must first select the department, then the municipality and finally the District to finish.
My problem is that I manage to correctly load the data of the municipality by choosing the department, but I'm produced to load the data of the district by selecting a department. I think the problem comes from JS.
I used an eventlister to do it but it works for the first select but nothing for the second.

Departement Entity

<?php

namespace App\Entity;

use App\Repository\DepartementRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity(repositoryClass: DepartementRepository::class)]
class Departement
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column]
    private ?int $id = null;

    #[ORM\Column(length: 100)]
    private ?string $nom = null;

    #[ORM\Column]
    private ?int $codeDepartement = null;

    #[ORM\OneToMany(mappedBy: 'departement', targetEntity: CommuneDistrict::class)]
    private Collection $communeDistricts;

    #[ORM\OneToMany(mappedBy: 'departement', targetEntity: ZoneTravail::class)]
    private Collection $zoneTravails;

    #[ORM\OneToMany(mappedBy: 'departementResidenceID01', targetEntity: Candidat::class)]
    private Collection $candidats;

    public function __construct()
    {
        $this->communeDistricts = new ArrayCollection();
        $this->zoneTravails = new ArrayCollection();
        $this->candidats = new ArrayCollection();
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getNom(): ?string
    {
        return $this->nom;
    }

    public function setNom(string $nom): self
    {
        $this->nom = $nom;

        return $this;
    }

    public function getCodeDepartement(): ?int
    {
        return $this->codeDepartement;
    }

    public function setCodeDepartement(int $codeDepartement): self
    {
        $this->codeDepartement = $codeDepartement;
        return $this;
    }

    /**
     * @return Collection<int, CommuneDistrict>
     */
    public function getCommuneDistricts(): Collection
    {
        return $this->communeDistricts;
    }

    public function addCommuneDistrict(CommuneDistrict $communeDistrict): self
    {
        if (!$this->communeDistricts->contains($communeDistrict)) {
            $this->communeDistricts->add($communeDistrict);
            $communeDistrict->setDepartement($this);
        }

        return $this;
    }

    public function removeCommuneDistrict(CommuneDistrict $communeDistrict): self
    {
        if ($this->communeDistricts->removeElement($communeDistrict)) {
            // set the owning side to null (unless already changed)
            if ($communeDistrict->getDepartement() === $this) {
                $communeDistrict->setDepartement(null);
            }
        }

        return $this;
    }

    public function __toString(): string
    {
        return $this->nom;
    }
}

Commune Entity

<?php

namespace App\Entity;

use App\Repository\CommuneDistrictRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity(repositoryClass: CommuneDistrictRepository::class)]
class CommuneDistrict
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column]
    private ?int $id = null;

    #[ORM\Column(length: 100)]
    private ?string $nom = null;

    #[ORM\Column(nullable: true)]
    private ?int $codeComDistr = null;

    #[ORM\ManyToOne(inversedBy: 'communeDistricts')]
    private ?Departement $departement = null;

    #[ORM\OneToMany(mappedBy: 'CommuneDistr', targetEntity: ArrCuCr::class)]
    private Collection $arrCuCrs;

    #[ORM\OneToMany(mappedBy: 'ComDistr', targetEntity: ZoneTravail::class)]
    private Collection $zoneTravails;

    #[ORM\OneToMany(mappedBy: 'communeResidenceID02', targetEntity: Candidat::class)]
    private Collection $candidats;

    public function __construct()
    {
        $this->arrCuCrs = new ArrayCollection();
        $this->zoneTravails = new ArrayCollection();
        $this->candidats = new ArrayCollection();
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getNom(): ?string
    {
        return $this->nom;
    }

    public function setNom(string $nom): self
    {
        $this->nom = $nom;

        return $this;
    }

    public function getCodeComDistr(): ?int
    {
        return $this->codeComDistr;
    }

    public function setCodeComDistr(?int $codeComDistr): self
    {
        $this->codeComDistr = $codeComDistr;

        return $this;
    }

    public function getDepartement(): ?Departement
    {
        return $this->departement;
    }

    public function setDepartement(?Departement $departement): self
    {
        $this->departement = $departement;

        return $this;
    }

    /**
     * @return Collection<int, ArrCuCr>
     */
    public function getArrCuCrs(): Collection
    {
        return $this->arrCuCrs;
    }

    public function addArrCuCr(ArrCuCr $arrCuCr): self
    {
        if (!$this->arrCuCrs->contains($arrCuCr)) {
            $this->arrCuCrs->add($arrCuCr);
            $arrCuCr->setCommuneDistr($this);
        }

        return $this;
    }

    public function removeArrCuCr(ArrCuCr $arrCuCr): self
    {
        if ($this->arrCuCrs->removeElement($arrCuCr)) {
            // set the owning side to null (unless already changed)
            if ($arrCuCr->getCommuneDistr() === $this) {
                $arrCuCr->setCommuneDistr(null);
            }
        }

        return $this;
    }

    public function __toString(): string
    {
        return $this->nom;
    }

}

Arrondissement Entity

<?php

namespace App\Entity;

use App\Repository\ArrCuCrRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity(repositoryClass: ArrCuCrRepository::class)]
class ArrCuCr
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column]
    private ?int $id = null;

    #[ORM\Column(length: 100)]
    private ?string $nom = null;

    #[ORM\Column]
    private ?int $code = null;

    #[ORM\ManyToOne(inversedBy: 'arrCuCrs')]
    private ?CommuneDistrict $CommuneDistr = null;

    #[ORM\OneToMany(mappedBy: 'ArrCuCr', targetEntity: ZoneTravail::class)]
    private Collection $zoneTravails;

    #[ORM\OneToMany(mappedBy: 'arrondissementResidenceID03', targetEntity: Candidat::class)]
    private Collection $candidats;

    public function __construct()
    {
        $this->zoneTravails = new ArrayCollection();
        $this->candidats = new ArrayCollection();
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getNom(): ?string
    {
        return $this->nom;
    }

    public function setNom(string $nom): self
    {
        $this->nom = $nom;

        return $this;
    }

    public function getCode(): ?int
    {
        return $this->code;
    }

    public function setCode(int $code): self
    {
        $this->code = $code;

        return $this;
    }

    public function getCommuneDistr(): ?CommuneDistrict
    {
        return $this->CommuneDistr;
    }

    public function setCommuneDistr(?CommuneDistrict $CommuneDistr): self
    {
        $this->CommuneDistr = $CommuneDistr;

        return $this;
    }

    public function __toString(): string
    {
        return $this->nom;
    }
}

My Candidat Form

<?php

namespace App\Form;

use App\Entity\ArrCuCr;
use App\Entity\Candidat;
use App\Entity\CommuneDistrict;
use App\Entity\Departement;
use App\Entity\Langue;
use App\Entity\NiveauEtude;
use App\Entity\ZoneTravail;
use FOS\CKEditorBundle\Form\Type\CKEditorType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\CountryType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Vich\UploaderBundle\Form\Type\VichFileType;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Validator\Constraints\Regex;
use Symfony\Component\Validator\Constraints\IsTrue;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\Form\FormInterface;
use App\Repository\DepartementRepository;
use App\Repository\CommuneDistrictRepository;
use App\Repository\ArrCuCrRepository;
use Doctrine\ORM\EntityRepository;

class CandidatType extends AbstractType
{
    private $countryRepository;
    private $StateRepository;
    private $stateCitiesRepository;

    public function __construct(
        DepartementRepository $countryRepository,
        CommuneDistrictRepository $stateRepository,
        ArrCuCrRepository $stateCitiesRepository
    ) {
        $this->countryRepository = $countryRepository;
        $this->StateRepository = $stateRepository;
        $this->stateCitiesRepository = $stateCitiesRepository;
    }

    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('departementResidenceID01', EntityType::class,[
                'class' => Departement::class,
                'label' => 'ID01.Dans quel département vivez-vous ?',
                'disabled' => false,
                'required' => true,
                'choice_label' => function(Departement $country) {
                    return $country->getNom();
                },
                'invalid_message' => 'Vous devez selectionner un departement',
                'placeholder' => 'Choisir departement',
            ])

         ->add('communeResidenceID02', ChoiceType::class, [
            'choices' => [],
            'placeholder' => 'Choisir une commune/district',
        ])
            ->add('arrondissementResidenceID03', ChoiceType::class, [
                'placeholder' => 'Choisir un arrondissement CU/CR',
            'choices' => [],
        ]);

        //**************** Start Commune Form
        $formModifier = function (FormInterface $form, Departement $sport = null) {
            $positions = null === $sport ? [] : $sport->getCommuneDistricts();

            $form->add('communeResidenceID02', EntityType::class, [
                'class' => CommuneDistrict::class,
                'placeholder' => '',
                'choices' => $positions,
            ]);
        };

        $builder->addEventListener(
            FormEvents::PRE_SET_DATA,
            function (FormEvent $event) use ($formModifier) {
                // this would be your entity, i.e. SportMeetup
                $data = $event->getData();
                $formModifier($event->getForm(), $data->getDepartementResidenceID01());
            }
        );

        $builder->get('departementResidenceID01')->addEventListener(
            FormEvents::POST_SUBMIT,
            function (FormEvent $event) use ($formModifier) {
                $sport = $event->getForm()->getData();
                $formModifier($event->getForm()->getParent(), $sport);
            }
        );
        //**************** End State Form

        //**************** Start Arr Form
        $formModifierArr = function (FormInterface $form, CommuneDistrict $commune = null) {
            $com = null === $commune ? [] : $commune->getArrCuCrs();

            $form->add('arrondissementResidenceID03', EntityType::class, [
                'class' => ArrCuCr::class,
                'placeholder' => '',
                'choices' => $com,
            ]);
        };

        $builder->addEventListener(
            FormEvents::PRE_SET_DATA,
            function (FormEvent $eventCom) use ($formModifierArr) {
                // this would be your entity, i.e. SportMeetup
                $data = $eventCom->getData();
                $formModifierArr($eventCom->getForm(), $data->getCommuneResidenceID02());
            }
        );

        $builder->get('communeResidenceID02')->addEventListener(
            FormEvents::POST_SUBMIT,
            function (FormEvent $ev) use ($formModifierArr) {
                $comR = $ev->getForm()->getData();
                $formModifierArr($ev->getForm()->getParent(), $comR);
            }
        );

    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'data_class' => Candidat::class,
            //'csrf_protection' => false,
        ]);
    }
}


来源: stackexchange

问:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb0 in position 0: invalid start byte
Hello i am using TensorFlow to load a dataset and trying to decode b in front of a literal string so later be able to cast to float64 it but i can't. Here is my code

```<code>import tensorflow as tf
import codecs

LABEL_COLUMN = 'flid'
TRAIN_DATA_URL = "C:\\Users\\User\\PycharmProjects\\lashProject\\FINGERPRINT_LOCATION.csv"

def process_categorical_data(data):
    """Returns a one-hot encoded tensor representing categorical values."""
    data = tf.strings.regex_replace(data, '^ ', '')
    # Remove trailing '.'.
    data = tf.strings.regex_replace(data, r'\.$', '')

    data = tf.map_fn(lambda x: codecs.decode(x),data)
    data = tf.cast(data, tf.float64)

def get_dataset(file_path):
    col_types = [tf.int64, tf.string, tf.int64, tf.string, tf.string, tf.string, tf.string, tf.int64, tf.int64]
    dataset = tf.data.experimental.make_csv_dataset(
        file_path,
        batch_size=100,  # Artificially small to make examples easier to show.
        column_defaults=col_types,
        label_name=LABEL_COLUMN,
        na_value="?",
        num_epochs=1,
        ignore_errors=True,
        encoding='latin-1')
    return dataset

if __name__ == '__main__':
    raw_train_data = get_dataset(TRAIN_DATA_URL)

    examples, labels = next(iter(raw_train_data))  # Just the first batch. # Just the first batch.
    print("EXAMPLES: \n", examples, "\n")
    print("LABELS: \n", labels)

    class_tensor = examples['x']

    processed_class = process_categorical_data(class_tensor)
</code>```

Also, note that i face a second problem if I load the dataset 'x' column instead of string to float64 i lose some precision numbers so any help also to this?

```<code>tensorflow.python.autograph.impl.api.StagingError: in user code:

    File "C:\Users\User\PycharmProjects\lashProject\test2.py", line 15, in None  *
        lambda x: codecs.decode(x)
    File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\encodings\utf_8.py", line 16, in decode  **
        return codecs.utf_8_decode(input, errors, True)

    UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb5 in position 1: invalid start byte
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Hello i am using TensorFlow to load a dataset and trying to decode b in front of a literal string so later be able to cast to float64 it but i can't. Here is my code

import tensorflow as tf
import codecs

LABEL_COLUMN = 'flid'
TRAIN_DATA_URL = "C:\\Users\\User\\PycharmProjects\\lashProject\\FINGERPRINT_LOCATION.csv"

def process_categorical_data(data):
    """Returns a one-hot encoded tensor representing categorical values."""
    data = tf.strings.regex_replace(data, '^ ', '')
    # Remove trailing '.'.
    data = tf.strings.regex_replace(data, r'\.$', '')

    data = tf.map_fn(lambda x: codecs.decode(x),data)
    data = tf.cast(data, tf.float64)

def get_dataset(file_path):
    col_types = [tf.int64, tf.string, tf.int64, tf.string, tf.string, tf.string, tf.string, tf.int64, tf.int64]
    dataset = tf.data.experimental.make_csv_dataset(
        file_path,
        batch_size=100,  # Artificially small to make examples easier to show.
        column_defaults=col_types,
        label_name=LABEL_COLUMN,
        na_value="?",
        num_epochs=1,
        ignore_errors=True,
        encoding='latin-1')
    return dataset

if __name__ == '__main__':
    raw_train_data = get_dataset(TRAIN_DATA_URL)

    examples, labels = next(iter(raw_train_data))  # Just the first batch. # Just the first batch.
    print("EXAMPLES: \n", examples, "\n")
    print("LABELS: \n", labels)

    class_tensor = examples['x']

    processed_class = process_categorical_data(class_tensor)

Also, note that i face a second problem if I load the dataset 'x' column instead of string to float64 i lose some precision numbers so any help also to this?

tensorflow.python.autograph.impl.api.StagingError: in user code:

    File "C:\Users\User\PycharmProjects\lashProject\test2.py", line 15, in None  *
        lambda x: codecs.decode(x)
    File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\encodings\utf_8.py", line 16, in decode  **
        return codecs.utf_8_decode(input, errors, True)

    UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb5 in position 1: invalid start byte


问:
Github GraphQL API - Add collaborators to cloned template repository
I am trying to create a new repository based on a template using the Github GraphQL api.
I am using the mutation notation in combination with some custom variables. I know there is a 'cloneTemplateRepository' call which accepts some input. However I can't seem to figure out how to add collaborators to this newly created repository.

This is my mutation call so far:

```<code>mutation Mutation ($ownerId: ID!, $newRepoName: String!, $templateID: ID!){

    cloneTemplateRepository(input: {ownerId: $ownerId, name: $newRepoName, visibility: PRIVATE, repositoryId: $templateID}) {
        repository {
            owner {
                id
            }
            collaborators(first: 10) {
                nodes {
                    name
                }
            }
        }
    }
}
</code>```

I know that I can get the currently assigned collaborators from a existing repository as can be seen above. But I do not know how to add new collaborators to this 'cloneTemplateRepository' mutation.
Thanks in advance!!

Body:
I am trying to create a new repository based on a template using the Github GraphQL api.
I am using the mutation notation in combination with some custom variables. I know there is a 'cloneTemplateRepository' call which accepts some input. However I can't seem to figure out how to add collaborators to this newly created repository.

This is my mutation call so far:

mutation Mutation ($ownerId: ID!, $newRepoName: String!, $templateID: ID!){

    cloneTemplateRepository(input: {ownerId: $ownerId, name: $newRepoName, visibility: PRIVATE, repositoryId: $templateID}) {
        repository {
            owner {
                id
            }
            collaborators(first: 10) {
                nodes {
                    name
                }
            }
        }
    }
}

I know that I can get the currently assigned collaborators from a existing repository as can be seen above. But I do not know how to add new collaborators to this 'cloneTemplateRepository' mutation.
Thanks in advance!!


问:
How to remove shipping taxes from woocommerce order programmatically?
I need to remove shipping taxes from my WooCommerce orders for some specific clients. How can I do that programatically?

7 is the ID of the zero rate tax :

```<code>function remove_shipping_tax($item, $tax_rate_id, $order){
    $cart = WC()->cart->get_cart();
    $item->set_props(
                    array(
                        'rate_id' => 7,
                        'tax_total' => $cart->get_tax_amount(7),
                        'shipping_tax_total' => $cart->get_shipping_tax_amount(7),
                        'rate_code' => WC_Tax::get_rate_code(7),
                        'label' => WC_Tax::get_rate_label(7),
                        'compound' => WC_Tax::is_compound(7),
                    )
            );
    $order->calculate_totals();
}

do_action('woocommerce_checkout_create_order_tax_item', 'remove_shipping_tax',20,4);
</code>```
```<code>function also_reassign_the_setter($item, $cart_item_key, $values, $order){

        $shipping_items = $order->get_items('shipping');
        $order->set_shipping_tax(0);
        foreach ($shipping_items as $item_id => $itemship) {
            $itemship->set_total_tax(0);
        }

        $order->calculate_totals();
    }
add_action('woocommerce_checkout_create_order_line_item', 'also_reassign_the_setter', 20, 4);
</code>```

Body:
I need to remove shipping taxes from my WooCommerce orders for some specific clients. How can I do that programatically?

7 is the ID of the zero rate tax :

function remove_shipping_tax($item, $tax_rate_id, $order){
    $cart = WC()->cart->get_cart();
    $item->set_props(
                    array(
                        'rate_id' => 7,
                        'tax_total' => $cart->get_tax_amount(7),
                        'shipping_tax_total' => $cart->get_shipping_tax_amount(7),
                        'rate_code' => WC_Tax::get_rate_code(7),
                        'label' => WC_Tax::get_rate_label(7),
                        'compound' => WC_Tax::is_compound(7),
                    )
            );
    $order->calculate_totals();
}

do_action('woocommerce_checkout_create_order_tax_item', 'remove_shipping_tax',20,4);

function also_reassign_the_setter($item, $cart_item_key, $values, $order){

        $shipping_items = $order->get_items('shipping');
        $order->set_shipping_tax(0);
        foreach ($shipping_items as $item_id => $itemship) {
            $itemship->set_total_tax(0);
        }

        $order->calculate_totals();
    }
add_action('woocommerce_checkout_create_order_line_item', 'also_reassign_the_setter', 20, 4);


问:
Execute Python Script From Php in Cpanel Internal Server Error
I am trying to execute a python script from php in my Cpanel. I have setup a python app version 3.7.12, Below is my php code to execute the script

```<code><?php
   $command=escapeshellcmd('python /home/mesuivln/seopython/h1parser.py');
   $output = shell_exec($command);
   echo $output;
 ?>
</code>```

it is working with below Python Code

```<code>#!/usr/bin/env python

import requests
import re
import sys

print('ok')
</code>```

But don't work whenever I try to import below modules. Returns internal server error

```<code>#!/usr/bin/env python

import requests
from readability import Document
import yake
from bs4 import BeautifulSoup
from urllib.parse import urlparse
from collections import Counter
import re
import sys
import mysql.connector
import html

print('ok')
</code>```

But samething works when I execute from the cpanel terminal with below commands

```<code>source /home/mesuivln/virtualenv/seopython/3.7/bin/activate && cd /home/mesuivln/seopython
</code>```

then

```<code> python h1parser.py
</code>```

Below is my ErrorLog

```<code>  Traceback (most recent call last):
  File "/home/mesuivln/seopython/passenger_wsgi.py", line 8, in <module>
  wsgi = imp.load_source('wsgi', 'h1parser.py')
  File "/opt/alt/python37/lib64/python3.7/imp.py", line 171, in load_source
  module = _load(spec)
  File "<frozen importlib._bootstrap>", line 696, in _load
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 728, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "h1parser.py", line 5, in <module>
  import yake
  ModuleNotFoundError: No module named 'yake'
  Traceback (most recent call last):
  File "/home/mesuivln/seopython/passenger_wsgi.py", line 8, in <module>
  wsgi = imp.load_source('wsgi', 'h1parser.py')
  File "/opt/alt/python37/lib64/python3.7/imp.py", line 171, in load_source
  module = _load(spec)
  File "<frozen importlib._bootstrap>", line 696, in _load
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 728, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "h1parser.py", line 5, in <module>
  import yake
  ModuleNotFoundError: No module named 'yake'
</code>```

I have installed the module yake in my app location and it is working from the terminal command but not working while calling from php or through app url, below is the module directory location

https://i.stack.imgur.com/0ygur.png

how can I solve this

Body:
I am trying to execute a python script from php in my Cpanel. I have setup a python app version 3.7.12, Below is my php code to execute the script

<?php
   $command=escapeshellcmd('python /home/mesuivln/seopython/h1parser.py');
   $output = shell_exec($command);
   echo $output;
 ?>

it is working with below Python Code

#!/usr/bin/env python

import requests
import re
import sys

print('ok')

But don't work whenever I try to import below modules. Returns internal server error

#!/usr/bin/env python

import requests
from readability import Document
import yake
from bs4 import BeautifulSoup
from urllib.parse import urlparse
from collections import Counter
import re
import sys
import mysql.connector
import html

print('ok')

But samething works when I execute from the cpanel terminal with below commands

source /home/mesuivln/virtualenv/seopython/3.7/bin/activate && cd /home/mesuivln/seopython

then

 python h1parser.py

Below is my ErrorLog

  Traceback (most recent call last):
  File "/home/mesuivln/seopython/passenger_wsgi.py", line 8, in <module>
  wsgi = imp.load_source('wsgi', 'h1parser.py')
  File "/opt/alt/python37/lib64/python3.7/imp.py", line 171, in load_source
  module = _load(spec)
  File "<frozen importlib._bootstrap>", line 696, in _load
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 728, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "h1parser.py", line 5, in <module>
  import yake
  ModuleNotFoundError: No module named 'yake'
  Traceback (most recent call last):
  File "/home/mesuivln/seopython/passenger_wsgi.py", line 8, in <module>
  wsgi = imp.load_source('wsgi', 'h1parser.py')
  File "/opt/alt/python37/lib64/python3.7/imp.py", line 171, in load_source
  module = _load(spec)
  File "<frozen importlib._bootstrap>", line 696, in _load
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 728, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "h1parser.py", line 5, in <module>
  import yake
  ModuleNotFoundError: No module named 'yake'

I have installed the module yake in my app location and it is working from the terminal command but not working while calling from php or through app url, below is the module directory location

https://i.stack.imgur.com/0ygur.png

how can I solve this


问:
FastAPI with MQTT client deployed to GAE not receive any message after running for a while
I built a FastAPI app to forward MQTT message using paho-mqtt lib from broker to another REST api service.

After deploying the app to google app engine, everything works fine (can normally send/receive message) at the beginning.
But about hours later, my app can still publish messages but not receiving any message.

app.yaml

```<code>runtime: python310
entrypoint: gunicorn -b :$PORT -w 1 -k uvicorn.workers.UvicornWorker main:app
...

instance_class: F1

inbound_services:
- warmup

automatic_scaling:
  min_instances: 1
  max_instances: 1
  min_idle_instances: 1
</code>```

mqtt client wrapper

```<code>class MqttClient:
    _instance = None
    _lock = threading.Lock()
    _on_msg_callback: Set[Callable] = set()
    _subscribe_topics: Set[str] = set()
    _mqtt_client = None

    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            with cls._lock:
                if not cls._instance:
                    cls._instance = super().__new__(cls)

        return cls._instance

    def init(self, config: MqttConfig):
        broker_host = config.broker_host
        random_id = ''.join(random.choices(string.digits, k=6))
        client_id = f'mqtt-forwarder-{random_id}'
        port = config.port
        keepalive = config.keepalive

        client = mqtt.Client(client_id=client_id, userdata=self)
        client.username_pw_set(
            username=config.username,
            password=config.password
        )
        context = ssl.SSLContext(protocol=ssl.PROTOCOL_TLSv1_2)
        client.tls_set_context(context)

        # set callbacks
        client.on_log = self._on_log
        client.on_connect = self._on_connect
        client.on_disconnect = self._on_disconnect
        client.on_publish = self._on_publish
        client.on_subscribe = self._on_subscribe
        client.on_message = self._on_message

        client.connect(broker_host, port=port, keepalive=keepalive)

        client.loop_start()
        self._mqtt_client = client
</code>```

main.py

```<code>import...

app = FastAPI()

mqtt_client = MqttClient()
mqtt_client.init(
    MqttConfig(
        broker_host='...',
        port=8883,
        keepalive=60,
        username=...,
        password=...
    ))
mqtt_client.subscribe('...')
mqtt_client.subscribe('...')
mqtt_client.register_on_message_callback(mqtt_cb.mqtt_on_msg_callback)

@app.get('/_ah/warmup')
def warmup():
    return Response('', status_code=status.HTTP_200_OK)

</code>```

After checking the GAE logging, I found a process is terminated (pid1, 16:23:44.397).

I am not sure if this caused MQTT client receiving no message, and curious about why the process was terminated.
GAE log

My main Question:

How can I fix this issue and keep receiving MQTT messages?

Other Question:

Is it a good idea to deploy a GAE FastAPI to forward MQTT messages to my other services? Any suggestion is appreciated.

Thank you.

Body:
I built a FastAPI app to forward MQTT message using paho-mqtt lib from broker to another REST api service.

After deploying the app to google app engine, everything works fine (can normally send/receive message) at the beginning.
But about hours later, my app can still publish messages but not receiving any message.

app.yaml

runtime: python310
entrypoint: gunicorn -b :$PORT -w 1 -k uvicorn.workers.UvicornWorker main:app
...

instance_class: F1

inbound_services:
- warmup

automatic_scaling:
  min_instances: 1
  max_instances: 1
  min_idle_instances: 1

mqtt client wrapper

class MqttClient:
    _instance = None
    _lock = threading.Lock()
    _on_msg_callback: Set[Callable] = set()
    _subscribe_topics: Set[str] = set()
    _mqtt_client = None

    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            with cls._lock:
                if not cls._instance:
                    cls._instance = super().__new__(cls)

        return cls._instance

    def init(self, config: MqttConfig):
        broker_host = config.broker_host
        random_id = ''.join(random.choices(string.digits, k=6))
        client_id = f'mqtt-forwarder-{random_id}'
        port = config.port
        keepalive = config.keepalive

        client = mqtt.Client(client_id=client_id, userdata=self)
        client.username_pw_set(
            username=config.username,
            password=config.password
        )
        context = ssl.SSLContext(protocol=ssl.PROTOCOL_TLSv1_2)
        client.tls_set_context(context)

        # set callbacks
        client.on_log = self._on_log
        client.on_connect = self._on_connect
        client.on_disconnect = self._on_disconnect
        client.on_publish = self._on_publish
        client.on_subscribe = self._on_subscribe
        client.on_message = self._on_message

        client.connect(broker_host, port=port, keepalive=keepalive)

        client.loop_start()
        self._mqtt_client = client

main.py

import...

app = FastAPI()

mqtt_client = MqttClient()
mqtt_client.init(
    MqttConfig(
        broker_host='...',
        port=8883,
        keepalive=60,
        username=...,
        password=...
    ))
mqtt_client.subscribe('...')
mqtt_client.subscribe('...')
mqtt_client.register_on_message_callback(mqtt_cb.mqtt_on_msg_callback)

@app.get('/_ah/warmup')
def warmup():
    return Response('', status_code=status.HTTP_200_OK)

After checking the GAE logging, I found a process is terminated (pid1, 16:23:44.397).

I am not sure if this caused MQTT client receiving no message, and curious about why the process was terminated.
GAE log

My main Question:

How can I fix this issue and keep receiving MQTT messages?

Other Question:

Is it a good idea to deploy a GAE FastAPI to forward MQTT messages to my other services? Any suggestion is appreciated.

Thank you.


问:
(C++) Is there a way to use a shorthand if statement using return of a function?
I'm doing a lot of function calls to a specific function that returns a integer. Now I want to check for every call if the integer returned is higher than the one before that. I want to create a nice oneliner to prevent a lot of code duplication.

What I currently have:

```<code>int callFunction() {
  int result = // do something;
  return result;
}

int main() {
  int result = 0;
  int tmpResult = 0;

  //call 1
  int tmpResult = callFunction();
  result = (tmpResult > result) ? tmpResult : result;

  // call 2
  int tmpResult = callFunction();
  result = (tmpResult > result) ? tmpResult : result;

  // call 3
  int tmpResult = callFunction();
  result = (tmpResult > result) ? tmpResult : result;

  // log the highest result
}
</code>```

Ideally I want the return of the callFunction() directly parsed into the result, given it's higher than the current result.

I tried this:

```<code>result = (callFunction() > result) ? callFunction() : result;
</code>```

But I don't want to call the same function twice if that's not necessary.
Is there a way to get this oneliner without calling the function twice?

Body:
I'm doing a lot of function calls to a specific function that returns a integer. Now I want to check for every call if the integer returned is higher than the one before that. I want to create a nice oneliner to prevent a lot of code duplication.

What I currently have:

int callFunction() {
  int result = // do something;
  return result;
}

int main() {
  int result = 0;
  int tmpResult = 0;

  //call 1
  int tmpResult = callFunction();
  result = (tmpResult > result) ? tmpResult : result;

  // call 2
  int tmpResult = callFunction();
  result = (tmpResult > result) ? tmpResult : result;

  // call 3
  int tmpResult = callFunction();
  result = (tmpResult > result) ? tmpResult : result;

  // log the highest result
}

Ideally I want the return of the callFunction() directly parsed into the result, given it's higher than the current result.

I tried this:

result = (callFunction() > result) ? callFunction() : result;

But I don't want to call the same function twice if that's not necessary.
Is there a way to get this oneliner without calling the function twice?


问:
How can I setup AWS cognito SSO with Strapi
I want to accomplish SSO for Strapi Admin Panel. I've the following Use Case

I've a React Admin Panel Running on AWS using Cognito Authentincation

I've a Strapi Application running on Some Server

I've a Redirect button on React Admin Panel, that redirects to strapi login page

I want to use Cognito SSO for Strapi Admin panel so that my admin have only central credentials on AWS cognito and can use to login in both React Admin panel as well as Strapi Admin panel.

I've some confusions about strapi SSO. First one is,
Is strapi SSO available on free plan of strapi?
Even if your answer is either, How can It be done for Admin Panel?

Thanks in advance

I've tried to use this Strapi-Plugin but couldn't get what I want to acheive as it don't have any affect on strapi app.


问:
Count the duplicate values on multiple array and sort it to highest
I have a target where I have this DUPLICATE checker with COUNT for multiple arrays. As we can see. Any suggestions on how I make this work? Thank you and have a nice day.

DATA:

id
value

1
[5,6,8,4,2]

2
[2,3,4,1,8]

3
[9,3,2,1,10]

Normal result:

number
count

1
2

2
3

3
2

4
2

5
1

6
1

7
0

8
2

9
1

10
1

This is my target result with sorting (Highest count):

number
count

2
3

1
2

3
2

4
2

8
2

5
1

6
1

10
1

9
1


问:
Refering global values from JSON in the table footer
I'm using the Table in the Jasper Reports. I've defined the subDataset, over which the Table iterates:

```<code><subDataset name="Dataset1"
    <property name="com.jaspersoft.studio.data.defaultdataadapter" value="JSON"/>
    <queryString language="JSON">
        <![CDATA[result.details]]>
    </queryString>
....
</code>```

Now I need to refer a field from the structure other then result.details:

```<code>    <field name="totalTax" class="java.lang.String">
        <property name="result.Description" value="result.cantonal.cantonalTax.totalTax"/>
        <fieldDescription><![CDATA[result.description]]></fieldDescription>
    </field>
</code>```

The problem is, that I get 'null' in the field, which results from, I suppose, that Jasper resolves the field relative to the result.details. How to add JSON field that would be addressed from globally?

Body:
I'm using the Table in the Jasper Reports. I've defined the subDataset, over which the Table iterates:

<subDataset name="Dataset1"
    <property name="com.jaspersoft.studio.data.defaultdataadapter" value="JSON"/>
    <queryString language="JSON">
        <![CDATA[result.details]]>
    </queryString>
....

Now I need to refer a field from the structure other then result.details:

    <field name="totalTax" class="java.lang.String">
        <property name="result.Description" value="result.cantonal.cantonalTax.totalTax"/>
        <fieldDescription><![CDATA[result.description]]></fieldDescription>
    </field>

The problem is, that I get 'null' in the field, which results from, I suppose, that Jasper resolves the field relative to the result.details. How to add JSON field that would be addressed from globally?


问:
uniswap v2 fork npm run build failed TypeScript error
`npm start is working fine but npm run build is creating issue.

I have changed typescript, esline and react scripts versions but didn't get any success.`


问:
Set data range in chart to only use values > 0 in libreoffice calc (without using a filter)
I have created a chart from a spreadsheet which contains a number of values. I want to show values in the chart where one column has values >0 and ignore the others. When I filter on the data the chart is perfect. But I would like the chart to be independent of a filter. I would prefer the chart to "self-filter".

Is this possible?

So in the above example I would like the chart to pick up the first because of the number 7 in the last column, but ignore the next entry because it has a zero in that column.


问:
How to create a custom react-hot-toast but keeping the default animations
Creating a customized Toast seems easy enough when using react-hot-toast:

```<code>toast.custom(<div>Hello World</div>);
</code>```

But it seems to loss the default animations. Docs only mention how to create customized animations, is there an easy way to reuse the already existing enter and exit animations on a customized toast?

Body:
Creating a customized Toast seems easy enough when using react-hot-toast:

toast.custom(
Hello World
);

But it seems to loss the default animations. Docs only mention how to create customized animations, is there an easy way to reuse the already existing enter and exit animations on a customized toast?


问:
copy a private font with OCR
I am copying website to train myself but some fonts are not open source. Is there a way to recreate those fonts by copying all the letters, putting it in an OCR and recreate a font file ?

Thanks

Title: copy a private font with OCR


问:
python setup.py egg_info did not run successfully
When I am trying to install pygame from pip its always showing errors for other modules it didn't showed any such errors
enter image description here

install pygame  didnt install


问:
useSession returning session object as null in production nextauth
I am using next auth to provide google sign up for my project and it was working fine in development but when I deployed it the session object is returning null. The env file contains all the necessary values nextauth_url,nextauth_secret,google_id, and google_secret and the redirect Uri is also set in the google console.

[...nextauth].ts

```<code>export default NextAuth({
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_ID,
      clientSecret: process.env.GOOGLE_SECRET,
      authorization: {
        params: {
          prompt: "consent",
          access_type: "offline",
          response_type: "code"
        }
      }
    }),
  ],
   callbacks: {
    async session({ session, token, user }) {
      console.log(user.id)
      // Send properties to the client, like an access_token from a provider.
      session.user.userId = user.id;
      console.log(session.user.userId)
      return session
    }
  },
  secret:process.env.NEXT_PUBLIC_SECRET,
  debug: true,
})
</code>```

index.tsx

```<code>import type { NextPage } from 'next'
import { useSession} from 'next-auth/react';
import {useEffect} from 'react';
import {useSelector, useDispatch } from 'react-redux';
import { RootState } from '../app/store';
import {addCurrentUser} from '../components/currentUserSlice'
import SignUpLoginFullScreen from '../components/SignUpLoginFullScreen';
import LoadingScreen from '../components/LoadingScreen';
import MainSection from '../components/MainSection';
import PostsList from '../components/Posts/PostsList';

const Home: NextPage = () => {

  const {data:session,status}=useSession();
  console.log(session,status)

  const currentUser=useSelector((state:RootState)=>state.currentUser);
  console.log(currentUser)

  const dispatch=useDispatch();

  useEffect(()=>{
    if(session?.user){
      console.log(session.user)
      dispatch(
        addCurrentUser({name:session.user.name,
                        email:session.user.email,
                        image:session.user.image,
                        userId:session?.user.userId}))
    }

  },[session?.user,dispatch,session?.user.userId])

  return (
  <>
       {!session && status==='loading' &&
      <LoadingScreen/>
    }

    {session &&
        <MainSection>
            <PostsList currUserId={currentUser.userId} errMsg='No posts found'/>
        </MainSection>
     }

      {!session &&
      <SignUpLoginFullScreen/>
    }

  </>
  )
}

export default Home
</code>```

Body:
I am using next auth to provide google sign up for my project and it was working fine in development but when I deployed it the session object is returning null. The env file contains all the necessary values nextauth_url,nextauth_secret,google_id, and google_secret and the redirect Uri is also set in the google console.

[...nextauth].ts

export default NextAuth({
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_ID,
      clientSecret: process.env.GOOGLE_SECRET,
      authorization: {
        params: {
          prompt: "consent",
          access_type: "offline",
          response_type: "code"
        }
      }
    }),
  ],
   callbacks: {
    async session({ session, token, user }) {
      console.log(user.id)
      // Send properties to the client, like an access_token from a provider.
      session.user.userId = user.id;
      console.log(session.user.userId)
      return session
    }
  },
  secret:process.env.NEXT_PUBLIC_SECRET,
  debug: true,
})

index.tsx

import type { NextPage } from 'next'
import { useSession} from 'next-auth/react';
import {useEffect} from 'react';
import {useSelector, useDispatch } from 'react-redux';
import { RootState } from '../app/store';
import {addCurrentUser} from '../components/currentUserSlice'
import SignUpLoginFullScreen from '../components/SignUpLoginFullScreen';
import LoadingScreen from '../components/LoadingScreen';
import MainSection from '../components/MainSection';
import PostsList from '../components/Posts/PostsList';

const Home: NextPage = () => {

  const {data:session,status}=useSession();
  console.log(session,status)

  const currentUser=useSelector((state:RootState)=>state.currentUser);
  console.log(currentUser)

  const dispatch=useDispatch();

  useEffect(()=>{
    if(session?.user){
      console.log(session.user)
      dispatch(
        addCurrentUser({name:session.user.name,
                        email:session.user.email,
                        image:session.user.image,
                        userId:session?.user.userId}))
    }

  },[session?.user,dispatch,session?.user.userId])

  return (
  <>
       {!session && status==='loading' &&
      <LoadingScreen/>
    }

    {session &&
        <MainSection>
            <PostsList currUserId={currentUser.userId} errMsg='No posts found'/>
        </MainSection>
     }

      {!session &&
      <SignUpLoginFullScreen/>
    }

  </>
  )
}

export default Home


问:
Open the file and save as another name
I want to create a new word file called "xxx_def_xxx" from selected word file called "xxx_docu_xxx".

So I select a file from dialog -> do something -> SaveAs with new file name.

It does work, but I'm getting "run time error 4160: Bad file name" if I select the file created from others, i.e., if the author is not me but another person.

I was struggling with this problem for couple of days but couldn't solve it.

Any help will be really thankful!

```<code>Private Sub CommandButton1_Click()

    Dim fileOpen As FileDialog
    Dim docuName As String, defName As String
    Dim docu As Document

    Set fileOpen = Application.FileDialog(FileDialogType:=msoFileDialogOpen)
    With fileOpen
        .Filters.Clear
        .Filters.Add "Word Documents", "*.docx*"
        .Title = "Select the docu"
        .AllowMultiSelect = False
        If .Show = -1 Then
            docuName = .SelectedItems(1)
        Else
            Exit Sub
        End If
    End With

    Set docu = Documents.Open(docuName)

    'do something: remove or edit some texts in the file

    defName = Replace(docu.Name, "docu", "def")

    docu.SaveAs docu.Path & "\" & defName
    docu.Saved = True
    docu.Close

End Sub
</code>```

Title: Open the file and save as another name

Body:
I want to create a new word file called "xxx_def_xxx" from selected word file called "xxx_docu_xxx".

So I select a file from dialog -> do something -> SaveAs with new file name.

It does work, but I'm getting "run time error 4160: Bad file name" if I select the file created from others, i.e., if the author is not me but another person.

I was struggling with this problem for couple of days but couldn't solve it.

Any help will be really thankful!

Private Sub CommandButton1_Click()

    Dim fileOpen As FileDialog
    Dim docuName As String, defName As String
    Dim docu As Document

    Set fileOpen = Application.FileDialog(FileDialogType:=msoFileDialogOpen)
    With fileOpen
        .Filters.Clear
        .Filters.Add "Word Documents", "*.docx*"
        .Title = "Select the docu"
        .AllowMultiSelect = False
        If .Show = -1 Then
            docuName = .SelectedItems(1)
        Else
            Exit Sub
        End If
    End With

    Set docu = Documents.Open(docuName)

    'do something: remove or edit some texts in the file

    defName = Replace(docu.Name, "docu", "def")

    docu.SaveAs docu.Path & "\" & defName
    docu.Saved = True
    docu.Close

End Sub


问:
can anybody explain what are these errors in python code. It is a malware analysis code in python using keras package
so this is the code that i am trying to run

```<code>import numpy as np
import pandas as pd
from copy import deepcopy
import gc

from col_headers import Header
from experiments import Experiments, Configs
from experiments.useful import timestamped_to_vector, unison_shuffled_copies, extract_neg

# Load data
headers = Header()
c = headers.classification_col
v = headers.vector_col
data = pd.read_csv("data.csv")

test = data[data["test_set"] == True]
train = data[data["test_set"] == False]

train = train.as_matrix(columns=headers.training_headers)
test = test.as_matrix(columns=headers.training_headers)

x_test, y_test = timestamped_to_vector(test, vector_col=v, time_start=0, classification_col=c)
x_train, y_train = timestamped_to_vector(train, vector_col=v, time_start=0, classification_col=c)

# Random search with thresholding
rand_params = Configs.get_all()

expt = Experiments.Experiment(rand_params, search_algorithm="random",
                              data=(x_train, y_train), folds=10, folder_name="random_search_reults",
                              thresholding=True, threshold=0.5)

# parameter configurations
A_B_C = Configs.get_A_B_C

# Ensemble model
ensemble_config = Experiments.Ensemble_configurations(list(A_B_C.values()),
                                                      x_test=x_test, y_test=y_test,
                                                      x_train=x_train, y_train=y_train,
                                                      folder_name="test_train_results",`your text`
                                                      batch_size=64)
ensemble_config.run_experiments()

</code>```

These are the error messages i get

```<code>Traceback (most recent call last):
  File "C:\Program Files\JetBrains\PyCharm 2022.3\plugins\python\helpers\pydev\pydevconsole.py", line 364, in runcode
    coro = func()
  File "<input>", line 1, in <module>
  File "C:\Program Files\JetBrains\PyCharm 2022.3\plugins\python\helpers\pydev\_pydev_bundle\pydev_umd.py", line 198, in runfile
    pydev_imports.execfile(filename, global_vars, local_vars)  # execute the script
  File "C:\Program Files\JetBrains\PyCharm 2022.3\plugins\python\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "C:\Users\awais ramzan\Documents\papaer\malware-prediction-rnn-master\main.py", line 2, in <module>
    import pandas as pd
  File "C:\Program Files\JetBrains\PyCharm 2022.3\plugins\python\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 21, in do_import
    module = self._system_import(name, *args, **kwargs)
ModuleNotFoundError: No module named 'pandas'

</code>```

Body:
so this is the code that i am trying to run

import numpy as np
import pandas as pd
from copy import deepcopy
import gc

from col_headers import Header
from experiments import Experiments, Configs
from experiments.useful import timestamped_to_vector, unison_shuffled_copies, extract_neg

# Load data
headers = Header()
c = headers.classification_col
v = headers.vector_col
data = pd.read_csv("data.csv")

test = data[data["test_set"] == True]
train = data[data["test_set"] == False]

train = train.as_matrix(columns=headers.training_headers)
test = test.as_matrix(columns=headers.training_headers)

x_test, y_test = timestamped_to_vector(test, vector_col=v, time_start=0, classification_col=c)
x_train, y_train = timestamped_to_vector(train, vector_col=v, time_start=0, classification_col=c)

# Random search with thresholding
rand_params = Configs.get_all()

expt = Experiments.Experiment(rand_params, search_algorithm="random",
                              data=(x_train, y_train), folds=10, folder_name="random_search_reults",
                              thresholding=True, threshold=0.5)

# parameter configurations
A_B_C = Configs.get_A_B_C

# Ensemble model
ensemble_config = Experiments.Ensemble_configurations(list(A_B_C.values()),
                                                      x_test=x_test, y_test=y_test,
                                                      x_train=x_train, y_train=y_train,
                                                      folder_name="test_train_results",`your text`
                                                      batch_size=64)
ensemble_config.run_experiments()

These are the error messages i get

Traceback (most recent call last):
  File "C:\Program Files\JetBrains\PyCharm 2022.3\plugins\python\helpers\pydev\pydevconsole.py", line 364, in runcode
    coro = func()
  File "<input>", line 1, in <module>
  File "C:\Program Files\JetBrains\PyCharm 2022.3\plugins\python\helpers\pydev\_pydev_bundle\pydev_umd.py", line 198, in runfile
    pydev_imports.execfile(filename, global_vars, local_vars)  # execute the script
  File "C:\Program Files\JetBrains\PyCharm 2022.3\plugins\python\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "C:\Users\awais ramzan\Documents\papaer\malware-prediction-rnn-master\main.py", line 2, in <module>
    import pandas as pd
  File "C:\Program Files\JetBrains\PyCharm 2022.3\plugins\python\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 21, in do_import
    module = self._system_import(name, *args, **kwargs)
ModuleNotFoundError: No module named 'pandas'


问:
Could not print "hello" in Geany editor
I have installed geany and also have MinGW compiler. I am trying to print a simple "hello" but unable to do so. I have saved my file in the name of print.c.
The error that I am getting- .\print is not recognized as an internal or external command.
below I have attached the need:

enter image description here

enter image description here

Title: Could not print "hello" in Geany editor


问:
Uncaught Error: Class "APP\Utilities\Asset" not found in
In the asset file in utilities, I put the namespace APP\Utilities correctly, but when I use the asset::get() object, for example, it gives an error.

#Meanwhile, I am just learning MVC :)


问:
laravel belong to many not working -- "1048 Column 'purchase_id' cannot be null"
I am trying to store multiple purchaseCategory using Laravel and Vue, but after clicking submit I am getting this error. How do I solve it?

1048 Column 'purchase_id' cannot be null
```
<p>In my Vue file I am getting the <code>purchaseCategory</code> like this:</p>
<pre class="lang-html prettyprint-override"><code><select multiple v-model="purchaseCategory">
  <option
    v-for="purchaseType in purchaseTypes"
    :key="purchaseType.id"
    :value="purchaseType.id"
  >
    {{ purchaseType.purchaseType }}
  </option>
</select>
</code>```

I have also created a table to join purchases and purchase_types:

Schema::create('purchase_type_purchase', function (Blueprint $table) {
    $table->unsignedBigInteger('purchase_type_id');
    $table->unsignedBigInteger('purchase_id');
    $table->primary(['purchase_type_id', 'purchase_id']);
    $table->foreign('purchase_type_id')->references('id')->on('purchase_types')->onUpdate('cascade')->onDelete('cascade');
    $table->foreign('purchase_id')->references('id')->on('purchases')->onUpdate('cascade')->onDelete('cascade');
});
```
<p>In my <code>purchase.php</code> model I have:</p>
<pre class="lang-php prettyprint-override"><code>use HasFactory;

protected $guarded = [];

public function purchase_types()
{
    return $this->belongsToMany(PurchaseType::class,'purchase_type_purchase', 'purchase_id', 'purchase_type_id');
}
</code>```

In my PurchaseType.php model I have:

class PurchaseType extends Model
{
    protected $guarded = [];

    public function purchases()
    {
        return $this->belongsToMany(purchase::class);
    }
}
```
<p>In my controller I am storing the data like this:</p>
<pre class="lang-php prettyprint-override"><code>$data = new purchase;

foreach ($req->purchaseCategory as $value) {
    $data->purchase_types()->attach($value);
}
</code>```

Body:
I am trying to store multiple purchaseCategory using Laravel and Vue, but after clicking submit I am getting this error. How do I solve it?

1048 Column 'purchase_id' cannot be null

In my Vue file I am getting the purchaseCategory like this:

<select multiple v-model="purchaseCategory">
  <option
    v-for="purchaseType in purchaseTypes"
    :key="purchaseType.id"
    :value="purchaseType.id"
  >
    {{ purchaseType.purchaseType }}
  </option>
</select>

I have also created a table to join purchases and purchase_types:

Schema::create('purchase_type_purchase', function (Blueprint $table) {
    $table->unsignedBigInteger('purchase_type_id');
    $table->unsignedBigInteger('purchase_id');
    $table->primary(['purchase_type_id', 'purchase_id']);
    $table->foreign('purchase_type_id')->references('id')->on('purchase_types')->onUpdate('cascade')->onDelete('cascade');
    $table->foreign('purchase_id')->references('id')->on('purchases')->onUpdate('cascade')->onDelete('cascade');
});

In my purchase.php model I have:

use HasFactory;

protected $guarded = [];

public function purchase_types()
{
    return $this->belongsToMany(PurchaseType::class,'purchase_type_purchase', 'purchase_id', 'purchase_type_id');
}

In my PurchaseType.php model I have:

class PurchaseType extends Model
{
    protected $guarded = [];

    public function purchases()
    {
        return $this->belongsToMany(purchase::class);
    }
}

In my controller I am storing the data like this:

$data = new purchase;

foreach ($req->purchaseCategory as $value) {
    $data->purchase_types()->attach($value);
}


问:
How to show the old contents after clearing the search
After showing the content for searched item, while removing the letters from search bar not showing the contents correctly. How to show the contents based on the word which is there in search bar. I have started to learn redux. So need some suggestions

```<code>import logo from "./logo.svg";
import "./App.css";
import React, { useState } from "react";
import { useSelector, useDispatch } from "react-redux";

function App() {
  const [name, setName] = useState("");
  const [searchTerm, setSearchterm] = useState("");
  const dispatch = useDispatch();
  const data = useSelector((state) => state.add);
  console.log(data, "dfata");
  const handleChange = (e) => {
    setName(e.target.value);
  };
  console.log(name);
  if (data.length == 0) {
    return <p>No data</p>;
  }

  const Submithandler = () => {
    dispatch({ type: "ADD_ITEM", name });
    setName("");
  };
  const handleSearch = (e) => {
    setSearchterm(e.target.value);
  };
  const submitSerach = () => {
    dispatch({ type: "SEARCH_ITEM", searchTerm });
  };
  const reset = () => {
    dispatch({ type: "RESET", searchTerm });
  };

  return (
    <div className="App">
      {data.loading && <p>loading</p>}
      <input value={searchTerm} onChange={(e) => handleSearch(e)} />
      <button onClick={() => submitSerach()}>search</button>
      <button onClick={() => reset()}>reset</button>
      <input value={name} onChange={handleChange} />
      <button onClick={Submithandler}>Add</button>

      {data.item.length === 0 && <p>no item</p>}
      {data.item.map((dta, i) => {
        return (
          <div>
            {dta}
            <button
              onClick={() => dispatch({ type: "REMOVE_ITEM", name: dta })}
            >
              Remove
            </button>
          </div>
        );
      })}
    </div>
  );
}

export default App;
</code>```
```<code>const INITIAL_STATE = {
  item: [],
  loading: false,
};

function addReducer(state = INITIAL_STATE, action) {
  switch (action.type) {
    case "ADD_ITEM":
      console.log(action, "ahghsgda");
      return { item: [...state.item, action.name] };
    case "REMOVE_ITEM":
      console.log(action, "REMOPVE");
      return {
        item: state.item.filter((inditem) => inditem !== action.name),
      };
    case "SEARCH_ITEM":
      console.log(action, "ahghsgda");
      const data = [...state.item];
      return {
        loading: true,
        item: [data.filter((product) => product.includes(action.searchTerm))],
      };
    case "RESET":
      return {
        item: [...state.item],
      };
    default:
      return state;
  }
}

export default addReducer;

</code>```

After showing the content for searched item, while removing the letters from search bar not showing the contents correctly

Body:
After showing the content for searched item, while removing the letters from search bar not showing the contents correctly. How to show the contents based on the word which is there in search bar. I have started to learn redux. So need some suggestions

import logo from "./logo.svg";
import "./App.css";
import React, { useState } from "react";
import { useSelector, useDispatch } from "react-redux";

function App() {
  const [name, setName] = useState("");
  const [searchTerm, setSearchterm] = useState("");
  const dispatch = useDispatch();
  const data = useSelector((state) => state.add);
  console.log(data, "dfata");
  const handleChange = (e) => {
    setName(e.target.value);
  };
  console.log(name);
  if (data.length == 0) {
    return
No data
;
  }

  const Submithandler = () => {
    dispatch({ type: "ADD_ITEM", name });
    setName("");
  };
  const handleSearch = (e) => {
    setSearchterm(e.target.value);
  };
  const submitSerach = () => {
    dispatch({ type: "SEARCH_ITEM", searchTerm });
  };
  const reset = () => {
    dispatch({ type: "RESET", searchTerm });
  };

  return (

      {data.loading &&
loading
}
      <input value={searchTerm} onChange={(e) => handleSearch(e)} />
      <button onClick={() => submitSerach()}>search</button>
      <button onClick={() => reset()}>reset</button>
      <input value={name} onChange={handleChange} />
      <button onClick={Submithandler}>Add</button>

      {data.item.length === 0 &&
no item
}
      {data.item.map((dta, i) => {
        return (

            {dta}
            <button
              onClick={() => dispatch({ type: "REMOVE_ITEM", name: dta })}
            >
              Remove
            </button>

        );
      })}

  );
}

export default App;

const INITIAL_STATE = {
  item: [],
  loading: false,
};

function addReducer(state = INITIAL_STATE, action) {
  switch (action.type) {
    case "ADD_ITEM":
      console.log(action, "ahghsgda");
      return { item: [...state.item, action.name] };
    case "REMOVE_ITEM":
      console.log(action, "REMOPVE");
      return {
        item: state.item.filter((inditem) => inditem !== action.name),
      };
    case "SEARCH_ITEM":
      console.log(action, "ahghsgda");
      const data = [...state.item];
      return {
        loading: true,
        item: [data.filter((product) => product.includes(action.searchTerm))],
      };
    case "RESET":
      return {
        item: [...state.item],
      };
    default:
      return state;
  }
}

export default addReducer;

After showing the content for searched item, while removing the letters from search bar not showing the contents correctly


问:
maven deploy-file with links to dependencies
As jitpack.io has been down for almost two days now, I am trying to migrate the jars to different repository.

I took the local jars of the required libraries and deployed them with mvn deployfile:

```<code>     mvn deploy:deploy-file \
              -DgroupId=com.github.dmurph \
              -DartifactId=jgoogleanalyticstracker \
              -Dversion=69f68caf8e \
              -Dpackaging=jar \
              -Dfile=jgoogleanalyticstracker-master-69f68caf8e-1.jar \
              -Durl=https://gitlab.com/api/v4/projects/{your-project-id}/packages/maven \
              -DrepositoryId=gitlab-maven
</code>```

This is great and I can see the jars being deployed and I can link to them.

However it seems that any dependencies for the original library are ignored and when trying to use this I am getting a lot of Class not found exceptions of the related dependencies.

Is there a way to publish the jar with correct links to dependencies?

Body:
As jitpack.io has been down for almost two days now, I am trying to migrate the jars to different repository.

I took the local jars of the required libraries and deployed them with mvn deployfile:

     mvn deploy:deploy-file \
              -DgroupId=com.github.dmurph \
              -DartifactId=jgoogleanalyticstracker \
              -Dversion=69f68caf8e \
              -Dpackaging=jar \
              -Dfile=jgoogleanalyticstracker-master-69f68caf8e-1.jar \
              -Durl=https://gitlab.com/api/v4/projects/{your-project-id}/packages/maven \
              -DrepositoryId=gitlab-maven

This is great and I can see the jars being deployed and I can link to them.

However it seems that any dependencies for the original library are ignored and when trying to use this I am getting a lot of Class not found exceptions of the related dependencies.

Is there a way to publish the jar with correct links to dependencies?


问:
Array constructor for 2-dimensional array push cause all element do the same
I declare a 2-dimensional array

```<code>var arr = new Array(4).fill([])
// arr = [[],[],[],[]]
</code>```

When I want to push a value to one of its elements, it cause others do the same

```<code>arr[0].push(1)
// arr = [[1],[1],[1],[1]]
</code>```

Why that happend, how to fix it?

Body:
I declare a 2-dimensional array

var arr = new Array(4).fill([])
// arr = [[],[],[],[]]

When I want to push a value to one of its elements, it cause others do the same

arr[0].push(1)
// arr = [[1],[1],[1],[1]]

Why that happend, how to fix it?


问:
Makefile listing all files when i use %
```<code>src/p1.c  src/p1.s

STRIPPED_FILE= $(src:%.c=%.o)

all:
    @echo $(STRIPPED_FILE)

output is src/p1.o src/p1.s
</code>```

Question:

Why has $(src:%.c=%.o) listed src/p1.s though I have given src:%.c

How can i get only src/p1.o?

Title: Makefile listing all files when i use %

Body:
src/p1.c  src/p1.s

STRIPPED_FILE= $(src:%.c=%.o)

all:
    @echo $(STRIPPED_FILE)

output is src/p1.o src/p1.s

Question:

Why has $(src:%.c=%.o) listed src/p1.s though I have given src:%.c

How can i get only src/p1.o?


问:
Graphiti can not call method with args including keyword inside attribute/extra_attribute
my environment:
Ruby 3.1.3
Rails 7.0.4
Graphiti 1.3.9
Graphiti-rails 0.4.0

I faced this issue

```<code>extra_attribute :attribute_name, :array do
  get_my_age(@object, date: Date.current)
end

def get_my_age(birth, date:)
end
</code>```

it will throw ArgumentError (wrong number of arguments (given 2, expected 1; required keyword: date)):

but, if I try with

```<code>extra_attribute :attribute_name, :array do
  wrapper(@object, Date.current)
end

def wrapper(a, b)
  get_my_age(a, date: b)
end

def get_my_age(birth, date:)
end
</code>```

it will not throw any errors.

Which am I wrong? or is this a bug of graphiti?

Body:
my environment:
Ruby 3.1.3
Rails 7.0.4
Graphiti 1.3.9
Graphiti-rails 0.4.0

I faced this issue

extra_attribute :attribute_name, :array do
  get_my_age(@object, date: Date.current)
end

def get_my_age(birth, date:)
end

it will throw ArgumentError (wrong number of arguments (given 2, expected 1; required keyword: date)):

but, if I try with

extra_attribute :attribute_name, :array do
  wrapper(@object, Date.current)
end

def wrapper(a, b)
  get_my_age(a, date: b)
end

def get_my_age(birth, date:)
end

it will not throw any errors.

Which am I wrong? or is this a bug of graphiti?


问:
Swagger Python async client, handling exceptions
I have Python REST client generated by Swagger codegen. How to send async requests and handle exceptions in non-blocking way? I came up to something like this but it does not differ from synchronous approach since thread.get() is blocking:

```<code>thread = some_api.some_method(body, async_req=True)
try
  thread.get()
except Exception as e:
  logger.error(str(e))
</code>```

I would expect callback method parameter for handling exceptions but there is no any in generated client. I checked latest Swagger 2 and 3 so OpenAPI with default library (urllib3) but no callbacks present.

Body:
I have Python REST client generated by Swagger codegen. How to send async requests and handle exceptions in non-blocking way? I came up to something like this but it does not differ from synchronous approach since thread.get() is blocking:

thread = some_api.some_method(body, async_req=True)
try
  thread.get()
except Exception as e:
  logger.error(str(e))

I would expect callback method parameter for handling exceptions but there is no any in generated client. I checked latest Swagger 2 and 3 so OpenAPI with default library (urllib3) but no callbacks present.


问:
Persistent Volume required in one of the Gitlab CICD pipeline
I have a requirement where customer wants to put some java based dependencies in the persistent volume and their app containers can refer that and we have to create cicd pipelines for this use case.

We are using Gitlab for CI and codestream for CD. How it can be possible in this case with regard to persistent volume ? Please suggest

Thanks,

Persistent Volume needs to be created at codestream level and we can refern in gitlab OR something we can deal at Gitlab itself.


问:
CGO core dump analysis using GDB
The following GO code is using CGO to call C function test3(), which calls test2(), which calls test1(). The program will crash, because there is a NULL pointer assignment in test1(). When I use GDB, I am not getting the CGO stack trace. I need help to get the stack trace for CGO part.

```<code>package main

/*
void test1(void) {
   int *p = (int*)NULL;
   *p = 30;
}

void test2(void) {
    test1();
}

void test3(void) {
    test2();
}
*/
import "C"

func main() {
    C.test3();
}

</code>```
```<code>(gdb) bt

#0  runtime.raise () at /usr/local/go/src/runtime/sys_linux_amd64.s:150

#1  0x000000000043793b in runtime.dieFromSignal (sig=6) at /usr/local/go/src/runtime/signal_unix.go:428

#2  0x0000000000437d9d in runtime.sigfwdgo (sig=6, info=0xc0000094b0, ctx=0xc000009380,

    ~r3=<optimized out>) at /usr/local/go/src/runtime/signal_unix.go:631

#3  0x0000000000437020 in runtime.sigtrampgo (sig=<optimized out>, info=0xc0000094b0, ctx=0xc000009380)

    at /usr/local/go/src/runtime/signal_unix.go:289

#4  0x000000000044ed43 in runtime.sigtramp () at /usr/local/go/src/runtime/sys_linux_amd64.s:357

#5  <signal handler called>

#6  runtime.raise () at /usr/local/go/src/runtime/sys_linux_amd64.s:150

#7  0x000000000043793b in runtime.dieFromSignal (sig=6) at /usr/local/go/src/runtime/signal_unix.go:428

#8  0x0000000000437ada in runtime.crash () at /usr/local/go/src/runtime/signal_unix.go:520

#9  0x0000000000449dd1 in runtime.fatalthrow.func1 () at /usr/local/go/src/runtime/panic.go:833

#10 0x0000000000425c97 in runtime.fatalthrow () at /usr/local/go/src/runtime/panic.go:826

#11 0x0000000000425ac2 in runtime.throw (s=...) at /usr/local/go/src/runtime/panic.go:774

#12 0x00000000004378ec in runtime.sigpanic () at /usr/local/go/src/runtime/signal_unix.go:378

#13 0x0000000000456730 in main.main ()
</code>```

I tried GDB to get the stack trace from the core dump. But not getting stack trace for CGO part.

Title: CGO core dump analysis using GDB

Body:
The following GO code is using CGO to call C function test3(), which calls test2(), which calls test1(). The program will crash, because there is a NULL pointer assignment in test1(). When I use GDB, I am not getting the CGO stack trace. I need help to get the stack trace for CGO part.

package main

/*
void test1(void) {
   int *p = (int*)NULL;
   *p = 30;
}

void test2(void) {
    test1();
}

void test3(void) {
    test2();
}
*/
import "C"

func main() {
    C.test3();
}

(gdb) bt

#0  runtime.raise () at /usr/local/go/src/runtime/sys_linux_amd64.s:150

#1  0x000000000043793b in runtime.dieFromSignal (sig=6) at /usr/local/go/src/runtime/signal_unix.go:428

#2  0x0000000000437d9d in runtime.sigfwdgo (sig=6, info=0xc0000094b0, ctx=0xc000009380,

    ~r3=<optimized out>) at /usr/local/go/src/runtime/signal_unix.go:631

#3  0x0000000000437020 in runtime.sigtrampgo (sig=<optimized out>, info=0xc0000094b0, ctx=0xc000009380)

    at /usr/local/go/src/runtime/signal_unix.go:289

#4  0x000000000044ed43 in runtime.sigtramp () at /usr/local/go/src/runtime/sys_linux_amd64.s:357

#5  <signal handler called>

#6  runtime.raise () at /usr/local/go/src/runtime/sys_linux_amd64.s:150

#7  0x000000000043793b in runtime.dieFromSignal (sig=6) at /usr/local/go/src/runtime/signal_unix.go:428

#8  0x0000000000437ada in runtime.crash () at /usr/local/go/src/runtime/signal_unix.go:520

#9  0x0000000000449dd1 in runtime.fatalthrow.func1 () at /usr/local/go/src/runtime/panic.go:833

#10 0x0000000000425c97 in runtime.fatalthrow () at /usr/local/go/src/runtime/panic.go:826

#11 0x0000000000425ac2 in runtime.throw (s=...) at /usr/local/go/src/runtime/panic.go:774

#12 0x00000000004378ec in runtime.sigpanic () at /usr/local/go/src/runtime/signal_unix.go:378

#13 0x0000000000456730 in main.main ()

I tried GDB to get the stack trace from the core dump. But not getting stack trace for CGO part.


问:
Flower running the server and clients on different machines
I use Flower API for federated learning applications. Is there any way to run the server and clients on different machines for a real-world benchmark?</p>


问:
Cannot traverse through a tag in jdom
I have a xml response in the below format. I am trying to find the text in the each of the manifestGeneric:url tag. But unable to get traverse through the manifestGeneric:files tag. Throwing a null pointer exception.

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<tcm  xmlns:manifestGeneric="http://theplatform.com/tcm">
    <height>148</height>
    <width>262</width>
    <startTime>0</startTime>
    <endTime>128862</endTime>
    <imageCount>13</imageCount>
    <manifestGeneric:files>
        <manifestGeneric:file>
            <manifestGeneric:url>1671697301434-sample2minsvideo.0000000.jpg</manifestGeneric:url>
        </manifestGeneric:file>
        <manifestGeneric:file>
            <manifestGeneric:url>1671697301434-sample2minsvideo.0000001.jpg</manifestGeneric:url>
        </manifestGeneric:file>
        <manifestGeneric:file>
            <manifestGeneric:url>1671697301434-sample2minsvideo.0000002.jpg</manifestGeneric:url>
        </manifestGeneric:file>
        <manifestGeneric:file>
            <manifestGeneric:url>1671697301434-sample2minsvideo.0000003.jpg</manifestGeneric:url>
        </manifestGeneric:file>
        <manifestGeneric:file>
            <manifestGeneric:url>1671697301434-sample2minsvideo.0000004.jpg</manifestGeneric:url>
        </manifestGeneric:file>
        <manifestGeneric:file>
            <manifestGeneric:url>1671697301434-sample2minsvideo.0000005.jpg</manifestGeneric:url>
        </manifestGeneric:file>
        <manifestGeneric:file>
            <manifestGeneric:url>1671697301434-sample2minsvideo.0000006.jpg</manifestGeneric:url>
        </manifestGeneric:file>
        <manifestGeneric:file>
            <manifestGeneric:url>1671697301434-sample2minsvideo.0000007.jpg</manifestGeneric:url>
        </manifestGeneric:file>
        <manifestGeneric:file>
            <manifestGeneric:url>1671697301434-sample2minsvideo.0000008.jpg</manifestGeneric:url>
        </manifestGeneric:file>
        <manifestGeneric:file>
            <manifestGeneric:url>1671697301434-sample2minsvideo.0000009.jpg</manifestGeneric:url>
        </manifestGeneric:file>
        <manifestGeneric:file>
            <manifestGeneric:url>1671697301434-sample2minsvideo.0000010.jpg</manifestGeneric:url>
        </manifestGeneric:file>
        <manifestGeneric:file>
            <manifestGeneric:url>1671697301434-sample2minsvideo.0000011.jpg</manifestGeneric:url>
        </manifestGeneric:file>
        <manifestGeneric:file>
            <manifestGeneric:url>1671697301434-sample2minsvideo.0000012.jpg</manifestGeneric:url>
        </manifestGeneric:file>
    </manifestGeneric:files>
</tcm >
</code>```

Below is the code I have written

```<code>        SAXBuilder saxBuilder = new SAXBuilder();

        File inputFile = new File("response.txt");

        Document document =  saxBuilder.build(inputFile);
        System.out.println("Root element :" + document.getRootElement().getName());
        Element classElement = document.getRootElement();

        Element heightEle = classElement.getChild("height");
        System.out.println("Height: "+heightEle.getText());

        Element widthEle = classElement.getChild("width");
        System.out.println("Width: "+widthEle.getText());

        Element startTimeEle = classElement.getChild("startTime");
        System.out.println("Start time: "+startTimeEle.getText());

        Element endTimeEle = classElement.getChild("endTime");
        System.out.println("End time: "+endTimeEle.getText());

        Element imgCountEle = classElement.getChild("imageCount");
        System.out.println("Img Count: "+imgCountEle.getText());

        Element manifestGenFilesEle = classElement.getChild("manifestGeneric:files");

        System.out.println("Tag name: "+manifestGenFilesEle.getName());
</code>```

manifestGenFilesEle.getName() is throwing a null pointer exception.
Can someone please help me here.

Title: Cannot traverse through a tag in jdom

Body:
I have a xml response in the below format. I am trying to find the text in the each of the manifestGeneric:url tag. But unable to get traverse through the manifestGeneric:files tag. Throwing a null pointer exception.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<tcm  xmlns:manifestGeneric="http://theplatform.com/tcm">
    <height>148</height>
    <width>262</width>
    <startTime>0</startTime>
    <endTime>128862</endTime>
    <imageCount>13</imageCount>
    <manifestGeneric:files>
        <manifestGeneric:file>
            <manifestGeneric:url>1671697301434-sample2minsvideo.0000000.jpg</manifestGeneric:url>
        </manifestGeneric:file>
        <manifestGeneric:file>
            <manifestGeneric:url>1671697301434-sample2minsvideo.0000001.jpg</manifestGeneric:url>
        </manifestGeneric:file>
        <manifestGeneric:file>
            <manifestGeneric:url>1671697301434-sample2minsvideo.0000002.jpg</manifestGeneric:url>
        </manifestGeneric:file>
        <manifestGeneric:file>
            <manifestGeneric:url>1671697301434-sample2minsvideo.0000003.jpg</manifestGeneric:url>
        </manifestGeneric:file>
        <manifestGeneric:file>
            <manifestGeneric:url>1671697301434-sample2minsvideo.0000004.jpg</manifestGeneric:url>
        </manifestGeneric:file>
        <manifestGeneric:file>
            <manifestGeneric:url>1671697301434-sample2minsvideo.0000005.jpg</manifestGeneric:url>
        </manifestGeneric:file>
        <manifestGeneric:file>
            <manifestGeneric:url>1671697301434-sample2minsvideo.0000006.jpg</manifestGeneric:url>
        </manifestGeneric:file>
        <manifestGeneric:file>
            <manifestGeneric:url>1671697301434-sample2minsvideo.0000007.jpg</manifestGeneric:url>
        </manifestGeneric:file>
        <manifestGeneric:file>
            <manifestGeneric:url>1671697301434-sample2minsvideo.0000008.jpg</manifestGeneric:url>
        </manifestGeneric:file>
        <manifestGeneric:file>
            <manifestGeneric:url>1671697301434-sample2minsvideo.0000009.jpg</manifestGeneric:url>
        </manifestGeneric:file>
        <manifestGeneric:file>
            <manifestGeneric:url>1671697301434-sample2minsvideo.0000010.jpg</manifestGeneric:url>
        </manifestGeneric:file>
        <manifestGeneric:file>
            <manifestGeneric:url>1671697301434-sample2minsvideo.0000011.jpg</manifestGeneric:url>
        </manifestGeneric:file>
        <manifestGeneric:file>
            <manifestGeneric:url>1671697301434-sample2minsvideo.0000012.jpg</manifestGeneric:url>
        </manifestGeneric:file>
    </manifestGeneric:files>
</tcm >

Below is the code I have written

        SAXBuilder saxBuilder = new SAXBuilder();

        File inputFile = new File("response.txt");

        Document document =  saxBuilder.build(inputFile);
        System.out.println("Root element :" + document.getRootElement().getName());
        Element classElement = document.getRootElement();

        Element heightEle = classElement.getChild("height");
        System.out.println("Height: "+heightEle.getText());

        Element widthEle = classElement.getChild("width");
        System.out.println("Width: "+widthEle.getText());

        Element startTimeEle = classElement.getChild("startTime");
        System.out.println("Start time: "+startTimeEle.getText());

        Element endTimeEle = classElement.getChild("endTime");
        System.out.println("End time: "+endTimeEle.getText());

        Element imgCountEle = classElement.getChild("imageCount");
        System.out.println("Img Count: "+imgCountEle.getText());

        Element manifestGenFilesEle = classElement.getChild("manifestGeneric:files");

        System.out.println("Tag name: "+manifestGenFilesEle.getName());

manifestGenFilesEle.getName() is throwing a null pointer exception.
Can someone please help me here.


问:
Entity Framework Core - Assignment of referenced properties
I have a question about Entity Framework Core related to the way EF Core assigns referenced objects to the model. For example this code:

try
{
    List<Application> ApplicationList = await _dbContextDigitVP.Applications
        .FromSqlRaw("Exec dbo.GetApplication {0}", id)
        .ToListAsync();

    if (ApplicationList.Any())
    {
        Application Application = ApplicationList.First();
        await CategoryRepository.GetCategoryByApplicationIdAsync(Application.Id);
        await PromoterRepository.GetPromoterByApplicationIdAsync(Application.Id);
        await ApplicantRepository.GetApplicantByApplicationIdFullAsync(Application.Id);
        await SepaRepository.GetSepaByApplicationIdAsync(Application.Id);
        await VerificationRepository.GetVerificationByApplicationIdAsync(Application.Id);
        await ApplicationStateRepository.GetAllApplicationStatesByApplicationIdAsync(Application.Id);
        await ApplicationCommentRepository.GetApplicationCommentByApplicationIdAsync(Application.Id);
        await ConfirmationRepository.GetConfirmationByApplicationIdAsync(Application.Id);
        await HistoryRepository.GetHistoriesByApplicationIdAsync(Application.Id);
        await TaxRepository.GetTaxByApplicationIdAsync(Application.Id);

        return Application;
    }
    return null;
}
catch (Exception ex)
{
    Logger.LogError(ex.ToString());
    return null;
}
```

Now what these other repository functions do is essentially the same as how the variable ApplicationList gets set by executing a stored procedure directly on the database.

When I go through my code with the debugger then I can see that the Category of an Application gets set after the code inside the GetCategoryByApplicationIdAsync gets executed. I do not assign any referenced property anywhere in my code.

Is this normal behaviour of the framework or should I be alarmed about this?

Body:
I have a question about Entity Framework Core related to the way EF Core assigns referenced objects to the model. For example this code:

try
{
    List<Application> ApplicationList = await _dbContextDigitVP.Applications
        .FromSqlRaw("Exec dbo.GetApplication {0}", id)
        .ToListAsync();

    if (ApplicationList.Any())
    {
        Application Application = ApplicationList.First();
        await CategoryRepository.GetCategoryByApplicationIdAsync(Application.Id);
        await PromoterRepository.GetPromoterByApplicationIdAsync(Application.Id);
        await ApplicantRepository.GetApplicantByApplicationIdFullAsync(Application.Id);
        await SepaRepository.GetSepaByApplicationIdAsync(Application.Id);
        await VerificationRepository.GetVerificationByApplicationIdAsync(Application.Id);
        await ApplicationStateRepository.GetAllApplicationStatesByApplicationIdAsync(Application.Id);
        await ApplicationCommentRepository.GetApplicationCommentByApplicationIdAsync(Application.Id);
        await ConfirmationRepository.GetConfirmationByApplicationIdAsync(Application.Id);
        await HistoryRepository.GetHistoriesByApplicationIdAsync(Application.Id);
        await TaxRepository.GetTaxByApplicationIdAsync(Application.Id);

        return Application;
    }
    return null;
}
catch (Exception ex)
{
    Logger.LogError(ex.ToString());
    return null;
}

Now what these other repository functions do is essentially the same as how the variable ApplicationList gets set by executing a stored procedure directly on the database.

When I go through my code with the debugger then I can see that the Category of an Application gets set after the code inside the GetCategoryByApplicationIdAsync gets executed. I do not assign any referenced property anywhere in my code.

Is this normal behaviour of the framework or should I be alarmed about this?