问:
Symfony 6 authentification
Good morning everyone
Please i am block on authentification.The debug log :
my debug log

here is my entity code

```<code>class User implements UserInterface, \Serializable,PasswordAuthenticatedUserInterface,PasswordHasherAwareInterface
</code>```

{
/**
* @var int
*
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;

```<code>/**
 * @var string
 *
 * @ORM\Column(type="string", nullable=true)
 */
private $fullName;

/**
 * @var
 *
 * @ORM\Column(name="gender", type="string", length=10, nullable=true)
 */
protected $gender;

/**
 * @var
 *
 * @ORM\Column(name="firstname", type="string", length=50, nullable=true)
 */
protected $firstname;

/**
 * @var
 *
 * @ORM\Column(name="lastname", type="string", length=50, nullable=true)
 * @Assert\NotBlank()
 */
protected $lastname;

/**
 * @var string
 *
 * @ORM\Column(type="string", unique=true)
 */
private $username;

/**
 * @var string
 *
 * @ORM\Column(type="string", unique=true)
 * @Assert\NotBlank()
 * @Assert\Email()
 */
private $email;

/**
 * @var string
 *
 * @ORM\Column(type="string", length=64)
 */
private $password;

/**
 * @var
 *
 * @ORM\Column(name="notes", type="text", nullable=true)
 */
protected $notes;

/**
 * @var
 *
 * @ORM\Column(name="locked", type="boolean")
 */
protected $locked = false;

/**
 * @var array
 *
 * @ORM\Column(name="roles", type="json")
 */
private $roles = [];

/**
 * @var \DateTime
 *
 * @ORM\Column(name="lastLogin", type="datetime", nullable=true)
 */
protected $lastLogin;

/**
 * Random string sent to the user email address in order to verify it.
 *
 * @var string
 *
 * @ORM\Column(name="confirmationToken", type="string", length=255, nullable=true)
 */
protected $confirmationToken;

/**
 * @var \DateTime
 *
 * @ORM\Column(name="passwordRequestedAt", type="datetime", nullable=true)
 */
protected $passwordRequestedAt;

/**
 * @var
 *
 * @ORM\ManyToMany(targetEntity="Group", inversedBy="users")
 * @ORM\JoinTable(name="sf_user_group",
 *      joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
 *      inverseJoinColumns={@ORM\JoinColumn(name="group_id", referencedColumnName="id")}
 * )
 */
protected $groups;

/**
 * @var \Doctrine\Common\Collections\Collection
 */
private $group;

/**
 * @ORM\Column(type="date", nullable=true)
 */
private $birth_date;

/**
 * @ORM\Column(type="string", length=255, nullable=true)
 */
private $blood_group;

/**
 * @ORM\Column(type="string", length=255)
 */
private $address;

/**
 * @ORM\Column(type="string", length=255)
 */
private $phone;

/**
 * @ORM\Column(type="string", length=255, nullable=true)
 */
private $license;

/**
 * @ORM\ManyToOne(targetEntity=Specialty::class, inversedBy="users")
 */
private $speciality;

/**
 * @ORM\OneToMany(targetEntity=Schedule::class, mappedBy="user")
 */
private $schedules;

/**
 * User constructor.
 */
public function __construct()
{
    $this->locked = false;
    $this->roles = array();
    $this->groups = new ArrayCollection();
    $this->schedules = new ArrayCollection();
}

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

public function setFullName(string $fullName): void
{
    $this->fullName = $fullName;
}

// le ? signifie que cela peut aussi retourner null
public function getFullName()
{
    return $this->fullName;
}

public function getUsername()
{
    return $this->username;
}

public function setUsername(string $username): void
{
    $this->username = $username;
}

public function getGender()
{
    return $this->gender;
}

public function setGender(string $gender): void
{
    $this->gender = $gender;
}

public function getNotes()
{
    return $this->notes;
}

public function setNotes(string $notes): void
{
    $this->notes = $notes;
}

public function getEmail(): ?string
{
    return $this->email;
}

public function setEmail(?string $email): void
{
    $this->email = $email;
}

public function getPassword(): ?string
{
    return $this->password;
}

public function setPassword($password = null): void
{
    $this->password = $password;
}

public function getFirstname(): ?string
{
    return $this->firstname;
}

public function setFirstname(string $firstname): void
{
    $this->firstname = $firstname;
}

public function getLastname(): ?string
{
    return $this->lastname;
}

public function setLastname(string $lastname): void
{
    $this->lastname = $lastname;
}

public function getLocked(): ?bool
{
    return $this->locked;
}

public function setLocked(bool $locked): void
{
    $this->locked = $locked;
}

/**
 * Retourne les rôles de l'user
 */
public function getRoles(): array
{
    $roles = $this->roles;

    // Afin d'être sûr qu'un user a toujours au moins 1 rôle
    if (empty($roles)) {
        $roles[] = 'ROLE_USER';
    }

    foreach ($this->getGroups() as $group) {
        $roles = array_merge($roles, $group->getRoles());
    }
   // die(var_dump($roles, array_unique($roles)));
    return array_unique($roles);
}

public function setRoles(array $roles): void
{
    $this->roles = $roles;
}

/**
 * Retour le salt qui a servi à coder le mot de passe
 *
 * {@inheritdoc}
 */
public function getSalt(): ?string
{
    // See "Do you need to use a Salt?" at https://symfony.com/doc/current/cookbook/security/entity_provider.html
    // we're using bcrypt in security.yml to encode the password, so
    // the salt value is built-in and you don't have to generate one

    return null;
}

/**
 * Removes sensitive data from the user.
 *
 * {@inheritdoc}
 */
public function eraseCredentials(): void
{
    // Nous n'avons pas besoin de cette methode car nous n'utilions pas de plainPassword
    // Mais elle est obligatoire car comprise dans l'interface UserInterface
    // $this->plainPassword = null;
}

/**
 * {@inheritdoc}
 */
public function serialize(): string
{
    return serialize([$this->id, $this->username, $this->password, $this->locked]);
}

/**
 * {@inheritdoc}
 */
public function unserialize($serialized): void
{
    [$this->id, $this->username, $this->password, $this->locked] = unserialize($serialized);
}

/**
 * {@inheritdoc}
 */
public function setLastLogin(\DateTime $time = null)
{
    $this->lastLogin = $time;

    return $this;
}

/**
 * {@inheritdoc}
 */
public function setConfirmationToken($confirmationToken)
{
    $this->confirmationToken = $confirmationToken;

    return $this;
}

/**
 * {@inheritdoc}
 */
public function setPasswordRequestedAt(\DateTime $date = null)
{
    $this->passwordRequestedAt = $date;

    return $this;
}

/**
 * Gets the last login time.
 *
 * @return \DateTime
 */
public function getLastLogin()
{
    return $this->lastLogin;
}

/**
 * {@inheritdoc}
 */
public function getConfirmationToken()
{
    return $this->confirmationToken;
}

 /**
 * Gets the timestamp that the user requested a password reset.
 *
 * @return null|\DateTime
 */
public function getPasswordRequestedAt()
{
    return $this->passwordRequestedAt;
}

/**
 * {@inheritdoc}
 */
public function isPasswordRequestNonExpired($ttl)
{
    return $this->getPasswordRequestedAt() instanceof \DateTime &&
           $this->getPasswordRequestedAt()->getTimestamp() + $ttl > time();
}

/**
 * @param $group
 * @return $this
 */
public function addGroup($group)
{
    $this->groups[] = $group;
</code>```

//        $group->addUser($this);

```<code>    return $this;
}

/**
 * @param $groups
 */

public function setGroup($group = null)
{
    $this->addGroup($group);
}

/**
 * @param $groups
 */

public function clearGroups()
{
    $this->groups->clear();
}
/**
 * @param $groups
 */

 /**
 * @param $groups
 */

public function setGroups(ArrayCollection $groups = null)
{
    if ($groups !== null) {
        $this->groups->clear();
        foreach ($groups as $group) {
            $this->addGroup($group);
        }
    }
}

/**
 * @return ArrayCollection
 */
public function getGroups()
{
    return $this->groups;
}

public function hasRole($role) {
    foreach($this->getGroups() as $grp) {
        if($grp->hasRole($role)) {
            return true;
        }
    }
    return false;
}

/**
 * Get group
 *
 * @return \Doctrine\Common\Collections\Collection
 */
public function getGroup()
{
    return $this->group;
}

public function hasGroup($name = '')
{
    return in_array($name, $this->getGroupNames());
}

public function containGroup(Group $group)
{
    return $this->groups->contains($group);
}

public function __toString() {
    return $this->getUsername().' - '.$this->getFirstname().' '.$this->getLastname();
}

public function removeGroup(Group $group): self
{
    if ($this->groups->contains($group)) {
        $this->groups->removeElement($group);
    }

    return $this;
}

public function getUserIdentifier(): string
{
    return (string)$this->email;
}

public function getPasswordHasherName(): ?string
{
    return null; // use the default hasher
}

public function getBirthDate(): ?\DateTimeInterface
{
    return $this->birth_date;
}

public function setBirthDate(?\DateTimeInterface $birth_date): self
{
    $this->birth_date = $birth_date;

    return $this;
}

public function getBloodGroup(): ?string
{
    return $this->blood_group;
}

public function setBloodGroup(?string $blood_group): self
{
    $this->blood_group = $blood_group;

    return $this;
}

public function getAddress(): ?string
{
    return $this->address;
}

public function setAddress(string $address): self
{
    $this->address = $address;

    return $this;
}

public function getPhone(): ?string
{
    return $this->phone;
}

public function setPhone(string $phone): self
{
    $this->phone = $phone;

    return $this;
}
</code>```

security.yaml

```<code>security:
enable_authenticator_manager: true
# https://symfony.com/doc/current/security.html#registering-the-user-hashing-passwords
password_hashers:
    App\Entity\Security\User: 'auto'
    Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: 'auto'
# https://symfony.com/doc/current/security.html#loading-the-user-the-user-provider
providers:
    main:
        entity:
            class: App\Entity\Security\User
            property: email
firewalls:
    main:
        provider: main
        pattern: "^/gestion"
        form_login:
            provider: main
            login_path: adminlogin
            check_path: adminlogin
            default_target_path: /gestion
            target_path_parameter: go_to
        logout:
            path: adminlogout
            target: adminlogin
            invalidate_session: true
        remember_me:
            secret: "%env(APP_SECRET)%"
            lifetime: 2232000
            path: /gestion
        entry_point: form_login
    dev:
        pattern: ^/(_(profiler|wdt)|css|images|js)/
        security: false

        # activate different ways to authenticate
        # https://symfony.com/doc/current/security.html#the-firewall

        # https://symfony.com/doc/current/security/impersonating_user.html
        # switch_user: true

# Easy way to control access for large sections of your site
# Note: Only the *first* access control that matches will be used
access_control:
    - { path: ^/gestion/login, roles: PUBLIC_ACCESS }
    - { path: ^/gestion, roles: [IS_AUTHENTICATED_FULLY, ROLE_ADMIN] }

role_hierarchy:
    ROLE_ADMIN: ROLE_PATIENT
</code>```

when@test:
security:
password_hashers:
App\Entity\Security\User: 'auto'
# By default, password hashers are resource intensive and take time. This is
# important to generate secure password hashes. In tests however, secure hashes
# are not important, waste resources and increase test times. The following
# reduces the work factor to the lowest possible values.
Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface:
algorithm: auto
cost: 4 # Lowest possible value for bcrypt
time_cost: 3 # Lowest possible value for argon
memory_cost: 10 # Lowest possible value for argon

Each time i try to log in , i receive authentification successfull after what i get access denied
enter code here

答: You are successfully authenticated then you can't access the wanted url, a possible reason for this is your access control, please verify the role of the user used to connect.</p>

Title: Symfony 6 authentification

Body:
Good morning everyone
Please i am block on authentification.The debug log :
my debug log

here is my entity code

class User implements UserInterface, \Serializable,PasswordAuthenticatedUserInterface,PasswordHasherAwareInterface

{
/**
* @var int
*
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;

/**
 * @var string
 *
 * @ORM\Column(type="string", nullable=true)
 */
private $fullName;

/**
 * @var
 *
 * @ORM\Column(name="gender", type="string", length=10, nullable=true)
 */
protected $gender;

/**
 * @var
 *
 * @ORM\Column(name="firstname", type="string", length=50, nullable=true)
 */
protected $firstname;

/**
 * @var
 *
 * @ORM\Column(name="lastname", type="string", length=50, nullable=true)
 * @Assert\NotBlank()
 */
protected $lastname;

/**
 * @var string
 *
 * @ORM\Column(type="string", unique=true)
 */
private $username;

/**
 * @var string
 *
 * @ORM\Column(type="string", unique=true)
 * @Assert\NotBlank()
 * @Assert\Email()
 */
private $email;

/**
 * @var string
 *
 * @ORM\Column(type="string", length=64)
 */
private $password;

/**
 * @var
 *
 * @ORM\Column(name="notes", type="text", nullable=true)
 */
protected $notes;

/**
 * @var
 *
 * @ORM\Column(name="locked", type="boolean")
 */
protected $locked = false;

/**
 * @var array
 *
 * @ORM\Column(name="roles", type="json")
 */
private $roles = [];

/**
 * @var \DateTime
 *
 * @ORM\Column(name="lastLogin", type="datetime", nullable=true)
 */
protected $lastLogin;

/**
 * Random string sent to the user email address in order to verify it.
 *
 * @var string
 *
 * @ORM\Column(name="confirmationToken", type="string", length=255, nullable=true)
 */
protected $confirmationToken;

/**
 * @var \DateTime
 *
 * @ORM\Column(name="passwordRequestedAt", type="datetime", nullable=true)
 */
protected $passwordRequestedAt;

/**
 * @var
 *
 * @ORM\ManyToMany(targetEntity="Group", inversedBy="users")
 * @ORM\JoinTable(name="sf_user_group",
 *      joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
 *      inverseJoinColumns={@ORM\JoinColumn(name="group_id", referencedColumnName="id")}
 * )
 */
protected $groups;

/**
 * @var \Doctrine\Common\Collections\Collection
 */
private $group;

/**
 * @ORM\Column(type="date", nullable=true)
 */
private $birth_date;

/**
 * @ORM\Column(type="string", length=255, nullable=true)
 */
private $blood_group;

/**
 * @ORM\Column(type="string", length=255)
 */
private $address;

/**
 * @ORM\Column(type="string", length=255)
 */
private $phone;

/**
 * @ORM\Column(type="string", length=255, nullable=true)
 */
private $license;

/**
 * @ORM\ManyToOne(targetEntity=Specialty::class, inversedBy="users")
 */
private $speciality;

/**
 * @ORM\OneToMany(targetEntity=Schedule::class, mappedBy="user")
 */
private $schedules;

/**
 * User constructor.
 */
public function __construct()
{
    $this->locked = false;
    $this->roles = array();
    $this->groups = new ArrayCollection();
    $this->schedules = new ArrayCollection();
}

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

public function setFullName(string $fullName): void
{
    $this->fullName = $fullName;
}

// le ? signifie que cela peut aussi retourner null
public function getFullName()
{
    return $this->fullName;
}

public function getUsername()
{
    return $this->username;
}

public function setUsername(string $username): void
{
    $this->username = $username;
}

public function getGender()
{
    return $this->gender;
}

public function setGender(string $gender): void
{
    $this->gender = $gender;
}

public function getNotes()
{
    return $this->notes;
}

public function setNotes(string $notes): void
{
    $this->notes = $notes;
}

public function getEmail(): ?string
{
    return $this->email;
}

public function setEmail(?string $email): void
{
    $this->email = $email;
}

public function getPassword(): ?string
{
    return $this->password;
}

public function setPassword($password = null): void
{
    $this->password = $password;
}

public function getFirstname(): ?string
{
    return $this->firstname;
}

public function setFirstname(string $firstname): void
{
    $this->firstname = $firstname;
}

public function getLastname(): ?string
{
    return $this->lastname;
}

public function setLastname(string $lastname): void
{
    $this->lastname = $lastname;
}

public function getLocked(): ?bool
{
    return $this->locked;
}

public function setLocked(bool $locked): void
{
    $this->locked = $locked;
}

/**
 * Retourne les rôles de l'user
 */
public function getRoles(): array
{
    $roles = $this->roles;

    // Afin d'être sûr qu'un user a toujours au moins 1 rôle
    if (empty($roles)) {
        $roles[] = 'ROLE_USER';
    }

    foreach ($this->getGroups() as $group) {
        $roles = array_merge($roles, $group->getRoles());
    }
   // die(var_dump($roles, array_unique($roles)));
    return array_unique($roles);
}

public function setRoles(array $roles): void
{
    $this->roles = $roles;
}

/**
 * Retour le salt qui a servi à coder le mot de passe
 *
 * {@inheritdoc}
 */
public function getSalt(): ?string
{
    // See "Do you need to use a Salt?" at https://symfony.com/doc/current/cookbook/security/entity_provider.html
    // we're using bcrypt in security.yml to encode the password, so
    // the salt value is built-in and you don't have to generate one

    return null;
}

/**
 * Removes sensitive data from the user.
 *
 * {@inheritdoc}
 */
public function eraseCredentials(): void
{
    // Nous n'avons pas besoin de cette methode car nous n'utilions pas de plainPassword
    // Mais elle est obligatoire car comprise dans l'interface UserInterface
    // $this->plainPassword = null;
}

/**
 * {@inheritdoc}
 */
public function serialize(): string
{
    return serialize([$this->id, $this->username, $this->password, $this->locked]);
}

/**
 * {@inheritdoc}
 */
public function unserialize($serialized): void
{
    [$this->id, $this->username, $this->password, $this->locked] = unserialize($serialized);
}

/**
 * {@inheritdoc}
 */
public function setLastLogin(\DateTime $time = null)
{
    $this->lastLogin = $time;

    return $this;
}

/**
 * {@inheritdoc}
 */
public function setConfirmationToken($confirmationToken)
{
    $this->confirmationToken = $confirmationToken;

    return $this;
}

/**
 * {@inheritdoc}
 */
public function setPasswordRequestedAt(\DateTime $date = null)
{
    $this->passwordRequestedAt = $date;

    return $this;
}

/**
 * Gets the last login time.
 *
 * @return \DateTime
 */
public function getLastLogin()
{
    return $this->lastLogin;
}

/**
 * {@inheritdoc}
 */
public function getConfirmationToken()
{
    return $this->confirmationToken;
}

 /**
 * Gets the timestamp that the user requested a password reset.
 *
 * @return null|\DateTime
 */
public function getPasswordRequestedAt()
{
    return $this->passwordRequestedAt;
}

/**
 * {@inheritdoc}
 */
public function isPasswordRequestNonExpired($ttl)
{
    return $this->getPasswordRequestedAt() instanceof \DateTime &&
           $this->getPasswordRequestedAt()->getTimestamp() + $ttl > time();
}

/**
 * @param $group
 * @return $this
 */
public function addGroup($group)
{
    $this->groups[] = $group;

//        $group->addUser($this);

    return $this;
}

/**
 * @param $groups
 */

public function setGroup($group = null)
{
    $this->addGroup($group);
}

/**
 * @param $groups
 */

public function clearGroups()
{
    $this->groups->clear();
}
/**
 * @param $groups
 */

 /**
 * @param $groups
 */

public function setGroups(ArrayCollection $groups = null)
{
    if ($groups !== null) {
        $this->groups->clear();
        foreach ($groups as $group) {
            $this->addGroup($group);
        }
    }
}

/**
 * @return ArrayCollection
 */
public function getGroups()
{
    return $this->groups;
}

public function hasRole($role) {
    foreach($this->getGroups() as $grp) {
        if($grp->hasRole($role)) {
            return true;
        }
    }
    return false;
}

/**
 * Get group
 *
 * @return \Doctrine\Common\Collections\Collection
 */
public function getGroup()
{
    return $this->group;
}

public function hasGroup($name = '')
{
    return in_array($name, $this->getGroupNames());
}

public function containGroup(Group $group)
{
    return $this->groups->contains($group);
}

public function __toString() {
    return $this->getUsername().' - '.$this->getFirstname().' '.$this->getLastname();
}

public function removeGroup(Group $group): self
{
    if ($this->groups->contains($group)) {
        $this->groups->removeElement($group);
    }

    return $this;
}

public function getUserIdentifier(): string
{
    return (string)$this->email;
}

public function getPasswordHasherName(): ?string
{
    return null; // use the default hasher
}

public function getBirthDate(): ?\DateTimeInterface
{
    return $this->birth_date;
}

public function setBirthDate(?\DateTimeInterface $birth_date): self
{
    $this->birth_date = $birth_date;

    return $this;
}

public function getBloodGroup(): ?string
{
    return $this->blood_group;
}

public function setBloodGroup(?string $blood_group): self
{
    $this->blood_group = $blood_group;

    return $this;
}

public function getAddress(): ?string
{
    return $this->address;
}

public function setAddress(string $address): self
{
    $this->address = $address;

    return $this;
}

public function getPhone(): ?string
{
    return $this->phone;
}

public function setPhone(string $phone): self
{
    $this->phone = $phone;

    return $this;
}

security.yaml

security:
enable_authenticator_manager: true
# https://symfony.com/doc/current/security.html#registering-the-user-hashing-passwords
password_hashers:
    App\Entity\Security\User: 'auto'
    Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: 'auto'
# https://symfony.com/doc/current/security.html#loading-the-user-the-user-provider
providers:
    main:
        entity:
            class: App\Entity\Security\User
            property: email
firewalls:
    main:
        provider: main
        pattern: "^/gestion"
        form_login:
            provider: main
            login_path: adminlogin
            check_path: adminlogin
            default_target_path: /gestion
            target_path_parameter: go_to
        logout:
            path: adminlogout
            target: adminlogin
            invalidate_session: true
        remember_me:
            secret: "%env(APP_SECRET)%"
            lifetime: 2232000
            path: /gestion
        entry_point: form_login
    dev:
        pattern: ^/(_(profiler|wdt)|css|images|js)/
        security: false

        # activate different ways to authenticate
        # https://symfony.com/doc/current/security.html#the-firewall

        # https://symfony.com/doc/current/security/impersonating_user.html
        # switch_user: true

# Easy way to control access for large sections of your site
# Note: Only the *first* access control that matches will be used
access_control:
    - { path: ^/gestion/login, roles: PUBLIC_ACCESS }
    - { path: ^/gestion, roles: [IS_AUTHENTICATED_FULLY, ROLE_ADMIN] }

role_hierarchy:
    ROLE_ADMIN: ROLE_PATIENT

when@test:
security:
password_hashers:
App\Entity\Security\User: 'auto'
# By default, password hashers are resource intensive and take time. This is
# important to generate secure password hashes. In tests however, secure hashes
# are not important, waste resources and increase test times. The following
# reduces the work factor to the lowest possible values.
Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface:
algorithm: auto
cost: 4 # Lowest possible value for bcrypt
time_cost: 3 # Lowest possible value for argon
memory_cost: 10 # Lowest possible value for argon

Each time i try to log in , i receive authentification successfull after what i get access denied
enter code here


来源: stackexchange

问:
How to get a file path from Shiny UI, and access the file from there
I would like to choose a file (for example dataset) through the shiny app, which will then give some basic outputs such as str(), summary(), and describe() (Hmisc package).
the dataset could be iris or cars in this case.

I would be grateful for some help, couldn't figure it out myself.

```<code>library(shiny)
library(shinyFiles)

ui <- fluidPage(
  shinyFilesButton("Btn_GetFile", "Choose a file" ,
                   title = "Please select a file:", multiple = FALSE,
                   buttonType = "default", class = NULL),

  textOutput("txt_file")
)

server <- function(input,output,session){

  volumes = getVolumes()
  observe({
    shinyFileChoose(input, "Btn_GetFile", roots = volumes, session = session)

    if(!is.null(input$Btn_GetFile)){
      # browser()
      file_selected<-parseFilePaths(volumes, input$Btn_GetFile)
      output$txt_file <- renderText(as.character(file_selected$datapath))
    }
  })
}
shinyApp(ui = ui, server = server)
</code>```

答:
I have never found a situation where having nested reactive functions (observe, reactive, or render*) made any sense (or even worked well). Do not nest them.

Related to this, shinyFileChoose must be outside of other reactive blocks.

getVolumes() returns a function, so in your example, volumes = getVolumes(), your variable volumes is a function ... which does not do what you want. Try getVolumes()(). Perhaps this is confusing ... I don't know enough about the package to understand this design decision, but the docs are clear about this point. (It has something to do with the sentence: "dynamic so that a shinyFiles instance reflects new volumes as they get added", though shinyFilesExample() does not seem to attempt to be dynamic about it? Idk.)

I'm inferring here, but your choice of txt_file as a name suggests that you intend to show the contents of the selected file, not its name or actually the data.frame that the shinyFiles tools are giving you. I'll provide both options, where $selected_file() provides the returned structure (data.frame that includes the file(s) name, path, etc), and $file_contents(), which is the raw contents of the file itself. (I'll truncate to a couple of lines for brevity.)

library(shiny)
library(shinyFiles)

ui <- fluidPage(
  shinyFilesButton("Btn_GetFile", "Choose a file" ,
                   title = "Please select a file:", multiple = FALSE,
                   buttonType = "default", class = NULL),
  tableOutput("selected_file"),
  verbatimTextOutput("file_contents")
)

server <- function(input,output,session){
  volumes = getVolumes()()
  shinyFileChoose(input, "Btn_GetFile", roots = volumes, session = session)
  file_selected <- eventReactive(input$Btn_GetFile, {
    req(input$Btn_GetFile)
    parseFilePaths(volumes, input$Btn_GetFile)
  })
  output$file_contents <- renderText({
    req(nrow(file_selected()) > 0,
        file.exists(file_selected()$datapath))
    readLines(file_selected()$datapath, n = 2)
  })
  # optional, purely informative, can safely be removed along with UI component
  output$selected_file <- renderTable({
    req(nrow(file_selected()) > 0)
    file_selected()
  })
}
shinyApp(ui = ui, server = server)
```

I found running shinyFilesExample() to be instructive in researching this question.

ContentLicense: CC BY-SA 4.0

Body:
I would like to choose a file (for example dataset) through the shiny app, which will then give some basic outputs such as str(), summary(), and describe() (Hmisc package).
the dataset could be iris or cars in this case.

I would be grateful for some help, couldn't figure it out myself.

library(shiny)
library(shinyFiles)

ui <- fluidPage(
  shinyFilesButton("Btn_GetFile", "Choose a file" ,
                   title = "Please select a file:", multiple = FALSE,
                   buttonType = "default", class = NULL),

  textOutput("txt_file")
)

server <- function(input,output,session){

  volumes = getVolumes()
  observe({
    shinyFileChoose(input, "Btn_GetFile", roots = volumes, session = session)

    if(!is.null(input$Btn_GetFile)){
      # browser()
      file_selected<-parseFilePaths(volumes, input$Btn_GetFile)
      output$txt_file <- renderText(as.character(file_selected$datapath))
    }
  })
}
shinyApp(ui = ui, server = server)

Body:
I have never found a situation where having nested reactive functions (observe, reactive, or render*) made any sense (or even worked well). Do not nest them.

Related to this, shinyFileChoose must be outside of other reactive blocks.

getVolumes() returns a function, so in your example, volumes = getVolumes(), your variable volumes is a function ... which does not do what you want. Try getVolumes()(). Perhaps this is confusing ... I don't know enough about the package to understand this design decision, but the docs are clear about this point. (It has something to do with the sentence: "dynamic so that a shinyFiles instance reflects new volumes as they get added", though shinyFilesExample() does not seem to attempt to be dynamic about it? Idk.)

I'm inferring here, but your choice of txt_file as a name suggests that you intend to show the contents of the selected file, not its name or actually the data.frame that the shinyFiles tools are giving you. I'll provide both options, where $selected_file() provides the returned structure (data.frame that includes the file(s) name, path, etc), and $file_contents(), which is the raw contents of the file itself. (I'll truncate to a couple of lines for brevity.)

library(shiny)
library(shinyFiles)

ui <- fluidPage(
  shinyFilesButton("Btn_GetFile", "Choose a file" ,
                   title = "Please select a file:", multiple = FALSE,
                   buttonType = "default", class = NULL),
  tableOutput("selected_file"),
  verbatimTextOutput("file_contents")
)

server <- function(input,output,session){
  volumes = getVolumes()()
  shinyFileChoose(input, "Btn_GetFile", roots = volumes, session = session)
  file_selected <- eventReactive(input$Btn_GetFile, {
    req(input$Btn_GetFile)
    parseFilePaths(volumes, input$Btn_GetFile)
  })
  output$file_contents <- renderText({
    req(nrow(file_selected()) > 0,
        file.exists(file_selected()$datapath))
    readLines(file_selected()$datapath, n = 2)
  })
  # optional, purely informative, can safely be removed along with UI component
  output$selected_file <- renderTable({
    req(nrow(file_selected()) > 0)
    file_selected()
  })
}
shinyApp(ui = ui, server = server)

I found running shinyFilesExample() to be instructive in researching this question.


问:
How to find item in array in React
I want to retrieve data from a json file and then match it with the value of an existing variable and if the variable value matches the data in json it will display a message "a" and if it does not match it will display a message "b".

the json file is like this

```<code>["23435","87567", "34536","45234","34532","65365"]
</code>```

答:
Since this is not a proper JSON format file, you can load it in simply as a string:

```<code>import arrayFile from './arrayFile.txt';
</code>```

Then, if your file is truly just an array hidden with nothing else, you can do something like this to get it into an array format:

```<code>const newArray = JSON.parse(arrayFile);
</code>```

Title: How to find item in array in React

Body:
I want to retrieve data from a json file and then match it with the value of an existing variable and if the variable value matches the data in json it will display a message "a" and if it does not match it will display a message "b".

the json file is like this

["23435","87567", "34536","45234","34532","65365"]

Body:
Since this is not a proper JSON format file, you can load it in simply as a string:

import arrayFile from './arrayFile.txt';

Then, if your file is truly just an array hidden with nothing else, you can do something like this to get it into an array format:

const newArray = JSON.parse(arrayFile);


问:
Compare two Excel workbooks for differences and copy/paste all the information from one to another
On some difficult issue I am bumped in. And i guess it quite out of my knowledge, and I hope it is even possible to solve on some way.

ISSUE:

Two different workbooks: I am having one workbook with 10 sheets inside, with many formulas, dropdowns, calculations etc., and it is main version of the document which has to be filled with information.

Second workbook, or better to say another similar version to this workbook is like obsolete versions of main wb, where might be possible that some cells/format, or even sheet is missing, but in general almost the same from its structure.

PROCESS:

Sometimes the customers are not having the newest version of excel workbook, but still some of the obsolete versions (they are forgetting to use the newest version), and they are filling those fields inside those older versions and sending them back. The problem is, our ERP Software cant read the obsolete versions, because it is so adjusted to read only the newest version of the document. Meaning, it has to be manually checked every time when the document is sent back and finding  discrepancies and copy/paste them into newest version of the document, and then upload it into ERP...

RESULT:

I am looking for some solution, with VBA or even formulas how to check every other workbook against "newest" and if there are any discrepancy and differences just to copy/paste everything from old to new version. When I say "everything" it means, all the fields, sheets, calculations, 1:1.

Unfortunately I am not writing any code or formula, because this is for me super advanced.

On the pic below is one example of one sheet how it looks like. There are lot of columns, calcs and so on.

Explanation:

To clarify bit better the content: inside one workbook is usually 10 sheets. 8x of them are the same (gas chambers from 1-8) and depending on the customer wishes, they can populated from 1-8. Sometimes 1 sometimes 5.
And range is from A1:Q54, full of data, tables, calculations, dropdowns, infos..

One sheet (9th) is customer details and last one (10th) is just instruction sheet with infos and screenshots.

So optimal would be to have macro that is taking everything from older versions, compare it with new one, and populate data that it finds, or on already given workbook or on new one but with the same content. I dont know if that is something possible.

答:
An example of how to scan various cell ranges in a workbook and collate those that have values into a table. Second stage would be to transfer those values to the new format template.

Option Explicit

Sub extractAll()

    Dim myfile As String, wb As Workbook, ws As Worksheet
    Dim n As Long, rng1 As Range, rng2 As Range, msg As String

    ' select workbook to scan
    With Application.FileDialog(msoFileDialogFilePicker)
        .Title = "Please select a file"
        .Show
        .AllowMultiSelect = False
        If .SelectedItems.Count = 0 Then 'If no folder is selected, abort
            MsgBox "You did not select a file"
            Exit Sub
        End If
        myfile = .SelectedItems(1)
    End With

    ' collate data on sheet 1 and 2
    Sheet1.Cells.Clear
    Sheet1.Range("A1:E1") = Array("Sheet", "Addr", "Row", "Column", "Value")
    Set rng1 = Sheet1.Range("A2")

    Sheet2.Cells.Clear
    Sheet2.Range("A1:D1") = Array("Addr", "Row", "Column", "Value")
    Set rng2 = Sheet2.Range("A2")
    ' open workbook and scan worksheets
    Set wb = Workbooks.Open(myfile, ReadOnly:=True)
    For Each ws In wb.Sheets
        If ws.Name Like "CH_recipe_#" Then
            Call scanSheet(ws, rng1)
            msg = msg & vbLf & ws.Name
        ElseIf ws.Name = "Customer Details" Then
            Call scanCustomer(ws, rng2)
            msg = msg & vbLf & ws.Name
        End If
    Next
    wb.Close savechanges:=False
    MsgBox "Sheets scanned" & msg

End Sub

Sub scanSheet(ws As Worksheet, ByRef rng As Range)

    Dim cell As Range, ar, s As String
    Dim i As Long, n As Long

    ' old template layout
    s = "D13,A15,C15,D15,E15,G15,J15,N15," ' process details
    s = s & "E20:P24,E41:P41," ' Carrier, Gas 2-12, usage
    s = s & "C45,D45,E45,G45,I45,K45,M45,N45,P45," ' exhaust line
    s = s & "C48" ' notes and remarks

    ar = Split(s, ",")
    For i = 0 To UBound(ar)
        For Each cell In ws.Range(ar(i))
           If cell.Value <> "" Then
                rng = ws.Name
                rng.Offset(, 1) = cell.Address(0, 0)
                rng.Offset(, 2) = cell.Row
                rng.Offset(, 3) = cell.Column
                rng.Offset(, 4) = cell.Value
                Set rng = rng.Offset(1)
           End If
        Next
    Next

    Debug.Print ws.Name & " Done"
End Sub

Sub scanCustomer(ws As Worksheet, ByRef rng As Range)

    Dim cell As Range, ar, s As String
    Dim i As Long, n As Long

    ' old template layout
    s = "B14:B25," ' contact details
    s = s & "B28:B29," ' existing install
    s = s & "B32:B35," ' hook up
    s = s & "A38" ' remarks

    ar = Split(s, ",")
    For i = 0 To UBound(ar)
        For Each cell In ws.Range(ar(i))
           If cell.Value <> "" Then
                rng = cell.Address(0, 0)
                rng.Offset(, 1) = cell.Row
                rng.Offset(, 2) = cell.Column
                rng.Offset(, 3) = cell.Value
                Set rng = rng.Offset(1)
           End If
        Next
    Next

    Debug.Print ws.Name & " Done"
End Sub
```


问:
Text doesn't wrap inside text box
Text doesn't wrap, instead it infinitely goes to the right. How to I make it so it breaks when it can no longer fit on its line, and start writing on a new line underneath.

CSS

```<code>  #eventDescriptionInput {
padding: 10px;
width: 100%;
box-sizing: border-box;
margin-bottom: 25px;
border-radius: 3px;
outline: none;
border: none;
box-shadow: 0px 0px 3px gray;
padding-bottom: 200px;
}
</code>```

HTML

```<code><input id="eventDescriptionInput" placeholder="Description" />
</code>```

答:
This should work for your purpose:</p>
```<code><textarea id="eventDescriptionInput" placeholder="Description"></textarea>
</code>```

Title: Text doesn't wrap inside text box

Body:
Text doesn't wrap, instead it infinitely goes to the right. How to I make it so it breaks when it can no longer fit on its line, and start writing on a new line underneath.

CSS

  #eventDescriptionInput {
padding: 10px;
width: 100%;
box-sizing: border-box;
margin-bottom: 25px;
border-radius: 3px;
outline: none;
border: none;
box-shadow: 0px 0px 3px gray;
padding-bottom: 200px;
}

HTML

<input id="eventDescriptionInput" placeholder="Description" />

Body:
This should work for your purpose:

<textarea id="eventDescriptionInput" placeholder="Description"></textarea>


问:
xamarin: I can't add anything to the .Android section
In my project I want to add a menu bar. I have downloaded a menu icon now I want to add it under .Android -> Resources. Unfortunately I can't add anything (a prohibition sign appears as a mouse icon). I also tried to add only a png or another file which also does not work.

My project

The downloaded icons:

Does anyone know how I can add the files in the appropriate place?

答: Don't know if this is the case, but some times the projects lacks the actual 'Drawable' folder. Create the folder yourself from fileexlorer</p>


问:
Create a masterpage that fits any screen resolution
I have created a masterpage and I want the ASP.NET pages attached to it to fit any screen resolution. Its a html tables based design.

I read that if you keep tables width and height to 100% then it should fit to any resolution. I have done the same thing, it adjusts its width to any screen resolution but not height. We see a blank space at the bottom for heigher screen resolutions and creates a scroll bar for lower screen resolutions.

Anyone has any idea how to fix this issue?

答:
I think if you want height, you have to use javascript.

```<code>var myHeight = 460;
if (document.body && document.body.offsetWidth) {
 myHeight = document.body.offsetHeight;
}
if (document.compatMode=='CSS1Compat' &&
    document.documentElement &&
    document.documentElement.offsetWidth ) {
 myHeight = document.documentElement.offsetHeight;
}
if (window.innerWidth && window.innerHeight) {
 myHeight = window.innerHeight;
}
</code>```

After that, you can style your outer div's height

```<code>var myDiv = document.getElementById('myDiv');
myDiv.style.height = myHeight + 'px';
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I think if you want height, you have to use javascript.

var myHeight = 460;
if (document.body && document.body.offsetWidth) {
 myHeight = document.body.offsetHeight;
}
if (document.compatMode=='CSS1Compat' &&
    document.documentElement &&
    document.documentElement.offsetWidth ) {
 myHeight = document.documentElement.offsetHeight;
}
if (window.innerWidth && window.innerHeight) {
 myHeight = window.innerHeight;
}

After that, you can style your outer div's height

var myDiv = document.getElementById('myDiv');
myDiv.style.height = myHeight + 'px';


问:
EF Core (LINQ) - The Query expression could not be Translated
I have the following query for searching records by parameter.

```<code>DateTime CurrentDate = DateTime.Now;
var pastDueInvoices =  Context.Invoice.AsNoTracking()
                .Select(i => new InvoiceDTO
                {
                    ID = i.ID,
                    InvoiceNumber = i.InvoiceNumber
                    DaysPastDue =  i.Balance <= 0 ? 0 : CurrentDate.Subtract(i.InvoiceDate.AddDays(i.ProductNav.DiscountDays.GetValueOrDefault())).Days,
                });
</code>```

Then I used this query to display only invoices where DaysPastDue > 0

```<code> if (request.ShowPastDueInvoices)
{
  pastDueInvoices =  pastDueInvoices.Where(pd => pd.DaysPastDue > 0);
}
</code>```

when i search for past due invoices I get the following error

.Join( outer: DbSet, inner: i =>
EF.Property<Nullable>(i, "ProductID"), outerKeySelector: p =>
EF.Property<Nullable>(p, "ID"), innerKeySelector: (o, i) => new
TransparentIdentifier<Invoice, Product>( Outer = o, Inner = i ))
.Where(i =>
__CurrentDate_0.Subtract(i.Outer.InvoiceDate.AddDays((double)i.Inner.DiscountDays.GetValueOrDefault())).Days > 0)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by
inserting a call to either AsEnumerable(), AsAsyncEnumerable(),
ToList(), or ToListAsync().

Any Help?

答:
Most likely EF Core cannot translate the Subtract method to SQL. Accoring to this code EF core has a DateTime.AddDays provider built in but I was unable to find such a provider for Substract or DateDiff in the official documentation. So, you can try using EF.Functions which gives you access to DbFunctions class with helper methods for SQL operations EF.Functions.DateDiffDay i.e.

```<code>DateTime CurrentDate = DateTime.Now;
var pastDueInvoices =  Context.Invoice.AsNoTracking()
            .Select(i => new InvoiceDTO
            {
                ID = i.ID,
                InvoiceNumber = i.InvoiceNumber
                DaysPastDue =  i.Balance <= 0 ? 0 : EF.Functions.DateDiffDay(CurrentDate, i.InvoiceDate.AddDays(i.ProductNav.DiscountDays.GetValueOrDefault())),
            });
</code>```

I'm not sure about this GetValueOrDefault() method if it will be translated to SQL. If it is some custom extension method written by you most likely not. Maybe you should try to replace it with something like i.ProductNav.DiscountDays ?? 0 or maybe you don't need to manually convert nullable days column value to 0, there is a good chance that SQL server will directly translate a null column value to 0 for use in DATEADDSQL function. Try both cases.

Also, the original EF 6 (not core) version of this will use DbFunctions

```<code>DateTime CurrentDate = DateTime.Now;
var pastDueInvoices =  Context.Invoice.AsNoTracking()
        .Select(i => new InvoiceDTO
        {
            ID = i.ID,
            InvoiceNumber = i.InvoiceNumber
            DaysPastDue =  i.Balance <= 0 ? 0 : DbFunctions.DiffDays(CurrentDate, DbFunctions.AddDays(i.InvoiceDate, i.ProductNav.DiscountDays)),
        })
</code>```

Body:
I have the following query for searching records by parameter.

DateTime CurrentDate = DateTime.Now;
var pastDueInvoices =  Context.Invoice.AsNoTracking()
                .Select(i => new InvoiceDTO
                {
                    ID = i.ID,
                    InvoiceNumber = i.InvoiceNumber
                    DaysPastDue =  i.Balance <= 0 ? 0 : CurrentDate.Subtract(i.InvoiceDate.AddDays(i.ProductNav.DiscountDays.GetValueOrDefault())).Days,
                });

Then I used this query to display only invoices where DaysPastDue > 0

 if (request.ShowPastDueInvoices)
{
  pastDueInvoices =  pastDueInvoices.Where(pd => pd.DaysPastDue > 0);
}

when i search for past due invoices I get the following error

.Join( outer: DbSet, inner: i =>
EF.Property<Nullable>(i, "ProductID"), outerKeySelector: p =>
EF.Property<Nullable>(p, "ID"), innerKeySelector: (o, i) => new
TransparentIdentifier<Invoice, Product>( Outer = o, Inner = i ))
.Where(i =>
__CurrentDate_0.Subtract(i.Outer.InvoiceDate.AddDays((double)i.Inner.DiscountDays.GetValueOrDefault())).Days > 0)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by
inserting a call to either AsEnumerable(), AsAsyncEnumerable(),
ToList(), or ToListAsync().

Any Help?

Body:
Most likely EF Core cannot translate the Subtract method to SQL. Accoring to this code EF core has a DateTime.AddDays provider built in but I was unable to find such a provider for Substract or DateDiff in the official documentation. So, you can try using EF.Functions which gives you access to DbFunctions class with helper methods for SQL operations EF.Functions.DateDiffDay i.e.

DateTime CurrentDate = DateTime.Now;
var pastDueInvoices =  Context.Invoice.AsNoTracking()
            .Select(i => new InvoiceDTO
            {
                ID = i.ID,
                InvoiceNumber = i.InvoiceNumber
                DaysPastDue =  i.Balance <= 0 ? 0 : EF.Functions.DateDiffDay(CurrentDate, i.InvoiceDate.AddDays(i.ProductNav.DiscountDays.GetValueOrDefault())),
            });

I'm not sure about this GetValueOrDefault() method if it will be translated to SQL. If it is some custom extension method written by you most likely not. Maybe you should try to replace it with something like i.ProductNav.DiscountDays ?? 0 or maybe you don't need to manually convert nullable days column value to 0, there is a good chance that SQL server will directly translate a null column value to 0 for use in DATEADDSQL function. Try both cases.

Also, the original EF 6 (not core) version of this will use DbFunctions

DateTime CurrentDate = DateTime.Now;
var pastDueInvoices =  Context.Invoice.AsNoTracking()
        .Select(i => new InvoiceDTO
        {
            ID = i.ID,
            InvoiceNumber = i.InvoiceNumber
            DaysPastDue =  i.Balance <= 0 ? 0 : DbFunctions.DiffDays(CurrentDate, DbFunctions.AddDays(i.InvoiceDate, i.ProductNav.DiscountDays)),
        })


问:
Spring Data JPA save child without fetch the parent
How to save child entity with Spring data JPA repositories if you know the parent Id?

For example if we have one to many relation:

```<code>@Entity
public class Customer {
    @Id @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;
    private String firstName;
    private String lastName;
    @ManyToOne
    private CustomerCategory category;
}

@Entity
public class CustomerCategory {
    @Id @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;
    private String name;
}
</code>```

One can do something like:

```<code>CustomerCategory someCategory = customerRepository.findOne(1L);// how to skip that line. The id should be enough.
Customer cust = new Customer("Evgeni", "Dimitrov", someCategory);
customerRepository.save(cust);
</code>```

JPA can do load(just create a proxy and set the Id) instead of 'get'(select from the DB). Is that possible with Spring Data JPA?

答: Forget Id. You are now at the Object level of ORM (ObjectRelationMapping). Objects are composed of other objects. NO IDs.</p>

Body:
How to save child entity with Spring data JPA repositories if you know the parent Id?

For example if we have one to many relation:

@Entity
public class Customer {
    @Id @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;
    private String firstName;
    private String lastName;
    @ManyToOne
    private CustomerCategory category;
}

@Entity
public class CustomerCategory {
    @Id @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;
    private String name;
}

One can do something like:

CustomerCategory someCategory = customerRepository.findOne(1L);// how to skip that line. The id should be enough.
Customer cust = new Customer("Evgeni", "Dimitrov", someCategory);
customerRepository.save(cust);

JPA can do load(just create a proxy and set the Id) instead of 'get'(select from the DB). Is that possible with Spring Data JPA?


问:
Web Map and Web Map Classic Arcade
I am not sure if this is the correct Community ''folder'' where to post this, but I have a question relating to the wonderful workflow as demonstrated in this video Inspection Workflows Part 2: Web Map Creation & Dynamic Symbology

Two questions:

Is it possible to Access the water utilities Symbology also on the new Map Viewer? I see it neatly in the Classic..

Is it just me or when using the same method of IIF+DateDiff as to define symbology for points that have been inspected recently and those that have to be inspected - it works only in the Map Viewer Classic? Is it because the Layer View is added to the map? I tried a workaround - created layer view by Join Analysis and added it to the Map Viewer Map. Used the same Arcade that is in the demonstration. Worked great for the Map Viewer Classic Map. Ignores the second part of the expression in Map Viewer.

I would be happy if anyone could give a comment if this is how it's supposed to be for now.

答:
Glad we're making progress on the first point! But I think I know the error for the second point, it's a tricky one!

According to your Arcade expression, you have two values, right?

"Inspected more than a year ago"

"Recent inspection"

Even though you put these two values correctly into the arcade expression, the map still doesn't technically know that these two values exist... until inpsection records are submitted that meet each of the provided criteria (inspection within the last year OR inspection not in the last year).

So, if you built the arcade epxression and all of your inspections are within the last year, you can symbolize everything by "Recent inspection" because the map has data that supports this first part fo the expression. Until you add an inspection record that occured "more than a year ago", the map won't register this value in the symbology and it will ignore that second part fo the arcade expression. However, once you add an inspection record that meets the second criteria, you'll still have to go into the symbology and manually turn on the "Inspected more than a year ago" symbology. But it will work since a record meeting this criteria is available for the arcade expression to consume.

I ran through the symbology workflow and when I had no inspection records submitted, I couldn't use either of your two values. I got a generic "Other" value. I added an inspection record with today's date and was able to add the "Recent inspection" value. Then, I added an inspection record and falsified the date to be three years ago; this allowed me to add the "Inspected more than a year ago" symbology color.

Here's my suggestion: when using an arcade expression like this to drive symbology, create "fake" inspections records that will trick the map to thinking that all of your different criteria are met. This way you can apply your: "Inspected more than a year ago" and "Recent inspection" symbologies.

Finally, it makes sense that the symbology from the Map Viewer Classic pulled into the New Map Viewer. Just like the utility symbology, the New Map Viewer will pull on that Map Viewer Classic's symbology.

Title: Web Map and Web Map Classic Arcade


问:
"The selection cannot be run on any server"
I've been working on a dynamic web project in Eclipse. I am getting this error.

"The selection cannot be run on any server".

Earlier it was working fine but now I'm getting this error. I removed the server and added it again.

Project->Right Click-> Properties->Server No server is showing here and two options are there Restore Default and Apply. I am not able to add server here.

Please tell me want is the problem with this.

POM.XML

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>try</groupId>
<artifactId>try</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>try Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
    <spring.version>3.2.0.RELEASE</spring.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.7</version>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.7</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>3.0.3.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <type>maven-plugin</type>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20140107</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>3.6.0.Final</version>
    </dependency>

    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <version>1.2.132</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>3.1.2.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>3.0.5.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-web</artifactId>
        <version>3.2.5.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-config</artifactId>
        <version>3.2.5.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-taglibs</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
    </dependency>

    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.1</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${spring.version}</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-core-asl</artifactId>
        <version>1.8.5</version>
    </dependency>
    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.8.5</version>
    </dependency>

    <dependency>
        <groupId>com.googlecode.json-simple</groupId>
        <artifactId>json-simple</artifactId>
        <version>1.1</version>
    </dependency>

    <dependency>
        <groupId>org.quartz-scheduler</groupId>
        <artifactId>quartz</artifactId>
        <version>1.8.6</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.6</version>
    </dependency>

    <dependency>
        <groupId>commons-dbcp</groupId>
        <artifactId>commons-dbcp</artifactId>
        <version>1.4</version>
    </dependency>

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.8.2</version>
        <scope>test</scope>
    </dependency>
</dependencies>
<build>
    <finalName>try</finalName>
    <pluginManagement>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
                <source>1.7</source>
                <target>1.7</target>
            </configuration>
        </plugin>
    </plugins>
    </pluginManagement>
</build>
```

答:
Sometimes the server might not be selected in project. Go to properties -> Server
Select the server you want to run this project on.</p>


问:
How to use Jquery to print each value from an XML file?
Anyone know how to go through an XML file using Jquery and print the tag names and text values from only the tags that have a text value in them?

Example, html that outputs like:

```<code>id: 00130000004EQCpAAO
updated: 2011-08-16 19:40:51
account_type: Vendor Other
active: 1
someprop_d: 0
</code>```

that comes from XML like:

```<code><accounts>
    <id>00130000004EQCpAAO</id>
    <updated>2011-08-16 19:40:51</updated>
    <account_type>Vendor Other</account_type>
    <someprop_a/>
    <active_c>1</active_c>
    <someprob_b/>
    <someprop_c/>
    <someprop_d>0</someprop_d>
</accounts>
</code>```

The Jquery:

```<code>var mystr = $.ajax({
    type: 'GET',
    url: '/js/data_account.xml',
    async: false,
    data: {
        key: "value"
    },
    dataType: "xml",
    success: function(data) {
        var xml = $(data)
        //var $accountid = xml.find("id").text();
        // do something relevant here
        //return something;
    },
    error: function() {
        alert("error: call failed");
    }
});
$('parentElement').append(mystr);
</code>```

答:
I think you can use the contents method on jquery and check the nodetype for text nodes. You can learn about the contents method here: http://api.jquery.com/contents/

Also the nodeType definitions can be found here: https://developer.mozilla.org/en/nodeType

Something like:

```<code>var textNodes = $(data).contents().filter(function() {
  return this.nodeType == 3;
})
</code>```

Body:
Anyone know how to go through an XML file using Jquery and print the tag names and text values from only the tags that have a text value in them?

Example, html that outputs like:

id: 00130000004EQCpAAO
updated: 2011-08-16 19:40:51
account_type: Vendor Other
active: 1
someprop_d: 0

that comes from XML like:

<accounts>
    <id>00130000004EQCpAAO</id>
    <updated>2011-08-16 19:40:51</updated>
    <account_type>Vendor Other</account_type>
    <someprop_a/>
    <active_c>1</active_c>
    <someprob_b/>
    <someprop_c/>
    <someprop_d>0</someprop_d>
</accounts>

The Jquery:

var mystr = $.ajax({
    type: 'GET',
    url: '/js/data_account.xml',
    async: false,
    data: {
        key: "value"
    },
    dataType: "xml",
    success: function(data) {
        var xml = $(data)
        //var $accountid = xml.find("id").text();
        // do something relevant here
        //return something;
    },
    error: function() {
        alert("error: call failed");
    }
});
$('parentElement').append(mystr);

Body:
I think you can use the contents method on jquery and check the nodetype for text nodes. You can learn about the contents method here: http://api.jquery.com/contents/

Also the nodeType definitions can be found here: https://developer.mozilla.org/en/nodeType

Something like:

var textNodes = $(data).contents().filter(function() {
  return this.nodeType == 3;
})


问:
"primaryColor" property in "ThemeData" does not work in Flutter
I'm currently investigating how to use ThemeData in the Flutter application.
It should work with the code below, but the color theme doesn't apply as expected.

Curiously, using the "primarySwatch" option instead of the "primaryColor" option applies the theme as expected.

The execution environment is Chrome on Windows10. Neither has a dark theme applied.
In addition, the results were the same in the Android11 environment of the real machine and the virtual environment.

```<code>import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(primaryColor: Colors.purple), // This "primaryColor" option does not working.
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Test App'),
        ),
        body: Container(),
      ),
    );
  }
}

</code>```

Below is my flutter environments.

```<code>Flutter 2.5.1 • channel stable • https://github.com/flutter/flutter.git
Framework • revision ffb2ecea52 (5 days ago) • 2021-09-17 15:26:33 -0400
Engine • revision b3af521a05
Tools • Dart 2.14.2
</code>```

What did I make a mistake in the code?

Thanks for your help.

答:
I don't think everything is deprecated like :

```<code>scaffoldBackgroundColor: Color(0x0FF0A0E21),    // just an example
// works perfectly.
</code>```

This color is applied to the body part.

Body:
I'm currently investigating how to use ThemeData in the Flutter application.
It should work with the code below, but the color theme doesn't apply as expected.

Curiously, using the "primarySwatch" option instead of the "primaryColor" option applies the theme as expected.

The execution environment is Chrome on Windows10. Neither has a dark theme applied.
In addition, the results were the same in the Android11 environment of the real machine and the virtual environment.

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(primaryColor: Colors.purple), // This "primaryColor" option does not working.
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Test App'),
        ),
        body: Container(),
      ),
    );
  }
}

Below is my flutter environments.

Flutter 2.5.1 • channel stable • https://github.com/flutter/flutter.git
Framework • revision ffb2ecea52 (5 days ago) • 2021-09-17 15:26:33 -0400
Engine • revision b3af521a05
Tools • Dart 2.14.2

What did I make a mistake in the code?

Thanks for your help.

Body:
I don't think everything is deprecated like :

scaffoldBackgroundColor: Color(0x0FF0A0E21),    // just an example
// works perfectly.

This color is applied to the body part.


问:
How do you call Square's APIs to Google Sheets using Google Apps Script?
Hello! I'd appreciate any help in making a connection. Here's what I'm trying to 'Get' info from:

curl https://connect.squareup.com/v2/locations

-H 'Square-Version: 2022-01-20'

-H 'Authorization: Bearer ACCESS_TOKEN'

-H 'Content-Type: application/json'

Setting the Scopes:
First I set the following scopes in the manifest file (here's a picture). I followed a similar notation as google's.

The Apps Script:

```<code>function squareLocations() {
  var url = "https://connect.squareup.com/v2/locations";
  var headers = {
    "contentType":"application/json",
    "headers": {"Square-Version": "2022-01-20",
                "Authorization": "Bearer <TOKEN>"}
                };
  var data =
  {
     'locations':
                {
                'id': locationID,
                'name': locationName,
                'address': locationAdress,
                }
  }
  var response = UrlFetchApp.fetch(url, headers);
  var text = response.getResponseCode();
  var json = JSON.parse(response.getContextText());
  Logger.log (text);
  Logger.log (json);

  }
</code>```

response returns a 400 error: invalid scope (lists all scopes).

答:
Background: why the manifest scopes are not relevant to the Square API##

The Square API uses the Oauth2 protocol. The idea of this protocol is as follows: you provide the user an opportunity to log in to their Square account, and in the process, you capture an oauth token that represents that user's login.  This token allows your script to take action on the user's behalf.  The scopes you specify tell the user what types of actions you'll be performing on their behalf, and you are limited to only those actions when calling the API.

The scopes listed in the Apps Script manifest represent the same idea, but for Google's services, not any external services like Square.  When you call ScriptApp.getOauthToken(), you get a token for performing actions within the Google account of the user currently running the Apps Script script.  (The reason you can do this for Google services without presenting a login screen is that the Google user has already logged in in order to run the script in the first place.)

But for any non-Google API like Square, you need to set up a full OAuth2 process, as detailed below:

The main question: How to access Square's API from Google Apps Script

There is an OAuth2 library for Apps Script that handles most of the mechanics of obtaining and storing the token for any API that uses OAuth2.  Start by adding the library to your script (the library's script id is 1B7FSrk5Zi6L1rSxxTDgDEUsPzlukDsi4KGuTMorsTQHhGBzBkMun4iDF).

Then obtain the callback uri for your project.  Do this by executing the following function from the script editor:

```<code>function logRedirectUri()
{
  console.log(
    OAuth2.getRedirectUri()
  )
}
</code>```

Now go to the Square developer dashboard, and create a new application.  There's an OAuth link on the left side of the app's main screen.  Go to that link and you'll get the app's Application ID and Application Secret.  You'll need those for your script.  In addition, on this screen you should add the redirect uri you obtained above (when the user logs in to Square, the Square API will now know to redirect to this uri, which your script uses to record the oauth token).

Now you're ready to use the OAuth library to provide the Square sign-in process and then call the API.  I've created a repo of the code I use for doing this, which you should be able to drop in to your script, but the relevant points are:

In the getSquareService function, set SQUARE_CLIENT_ID and SQUARE_CLIENT_SECRET to the id and secret you got from the Square developer dashboard.

getSquareService is also where you list the scopes you want for the Square API.

```<code> function getSquareService()
 {
   var SQUARE_CLIENT_SECRET = '{your square application secret}'
   var SQUARE_CLIENT_ID = '{your square application id}'

   return OAuth2.createService('Square')
     // Set the endpoint URLs.
     .setAuthorizationBaseUrl('https://connect.squareup.com/oauth2/authorize')
     .setTokenUrl('https://connect.squareup.com/oauth2/token')

     // Set the client ID and secret.
     .setClientId(SQUARE_CLIENT_ID)
     .setClientSecret(SQUARE_CLIENT_SECRET)

     // Set the name of the callback function that should be invoked to
     // complete the OAuth flow.
     .setCallbackFunction('authCallbackSquare')

     // Set the property store where authorized tokens should be persisted.
     // Change this to .getUserProperties() if you are having multiple google users authorize the service:
     // this will prevent one user's token from being visible to others.
     .setPropertyStore(PropertiesService.getScriptProperties())

     // Set the scopes needed.  For a full list see https://developer.squareup.com/docs/oauth-api/square-permissions
     .setScope(
       [
         'ORDERS_WRITE',
         'PAYMENTS_WRITE',
         'PAYMENTS_READ',
         'ORDERS_READ',
         'MERCHANT_PROFILE_READ'
       ]
         .join(" ")
     )
     // Set grant type
     .setGrantType('authorization_code')
 }
</code>```

And include the callback function that will store the token:

```<code>function authCallbackSquare(request)
{
  var service = getSquareService();

  // Now process request
  var authorized = service.handleCallback(request);
  if (authorized)
  {
    return HtmlService.createHtmlOutput('Success! You can close this tab.');
  } else
  {
    return HtmlService.createHtmlOutput('Denied. You can close this tab.');
  }
}
</code>```

If your script is bound to a spreadsheet, you can run authorizeSquareUser() in the repo to get a sidebar that initiates the authorization flow.  Otherwise, run this modified version:

```<code> function authorizeSquareUser()
 {
   var service = getSquareService();
   var authorizationUrl = service.getAuthorizationUrl();
   console.log("Auth URL is %s", authorizationUrl);
 }
</code>```

and then visit the url that is logged. At this url you will log in to your square account, and then you should be redirected to a page that says "Success! You can close this tab."

At this point, the Square user's OAuth token has been stored in the script properties of your project.  You are now ready to make a call to the Square API.  When doing this, you access the stored token using getSquareService().getAccessToken(), so your headers will look like

```<code>var headers = {
  'Authorization': 'Bearer ' + getSquareService().getAccessToken(),
  'Square-Version': '2022-01-20',
  'Content-Type': 'application/json'
}
</code>```

Then you can call

```<code>UrlFetchApp.fetch(url, {'method': 'GET', 'headers': headers}) // Change GET method depending on the action you are performing
</code>```

Body:
Hello! I'd appreciate any help in making a connection. Here's what I'm trying to 'Get' info from:

curl https://connect.squareup.com/v2/locations

-H 'Square-Version: 2022-01-20'

-H 'Authorization: Bearer ACCESS_TOKEN'

-H 'Content-Type: application/json'

Setting the Scopes:
First I set the following scopes in the manifest file (here's a picture). I followed a similar notation as google's.

The Apps Script:

function squareLocations() {
  var url = "https://connect.squareup.com/v2/locations";
  var headers = {
    "contentType":"application/json",
    "headers": {"Square-Version": "2022-01-20",
                "Authorization": "Bearer <TOKEN>"}
                };
  var data =
  {
     'locations':
                {
                'id': locationID,
                'name': locationName,
                'address': locationAdress,
                }
  }
  var response = UrlFetchApp.fetch(url, headers);
  var text = response.getResponseCode();
  var json = JSON.parse(response.getContextText());
  Logger.log (text);
  Logger.log (json);

  }

response returns a 400 error: invalid scope (lists all scopes).

Body:
Background: why the manifest scopes are not relevant to the Square API##

The Square API uses the Oauth2 protocol. The idea of this protocol is as follows: you provide the user an opportunity to log in to their Square account, and in the process, you capture an oauth token that represents that user's login.  This token allows your script to take action on the user's behalf.  The scopes you specify tell the user what types of actions you'll be performing on their behalf, and you are limited to only those actions when calling the API.

The scopes listed in the Apps Script manifest represent the same idea, but for Google's services, not any external services like Square.  When you call ScriptApp.getOauthToken(), you get a token for performing actions within the Google account of the user currently running the Apps Script script.  (The reason you can do this for Google services without presenting a login screen is that the Google user has already logged in in order to run the script in the first place.)

But for any non-Google API like Square, you need to set up a full OAuth2 process, as detailed below:

The main question: How to access Square's API from Google Apps Script

There is an OAuth2 library for Apps Script that handles most of the mechanics of obtaining and storing the token for any API that uses OAuth2.  Start by adding the library to your script (the library's script id is 1B7FSrk5Zi6L1rSxxTDgDEUsPzlukDsi4KGuTMorsTQHhGBzBkMun4iDF).

Then obtain the callback uri for your project.  Do this by executing the following function from the script editor:

function logRedirectUri()
{
  console.log(
    OAuth2.getRedirectUri()
  )
}

Now go to the Square developer dashboard, and create a new application.  There's an OAuth link on the left side of the app's main screen.  Go to that link and you'll get the app's Application ID and Application Secret.  You'll need those for your script.  In addition, on this screen you should add the redirect uri you obtained above (when the user logs in to Square, the Square API will now know to redirect to this uri, which your script uses to record the oauth token).

Now you're ready to use the OAuth library to provide the Square sign-in process and then call the API.  I've created a repo of the code I use for doing this, which you should be able to drop in to your script, but the relevant points are:

In the getSquareService function, set SQUARE_CLIENT_ID and SQUARE_CLIENT_SECRET to the id and secret you got from the Square developer dashboard.

getSquareService is also where you list the scopes you want for the Square API.

 function getSquareService()
 {
   var SQUARE_CLIENT_SECRET = '{your square application secret}'
   var SQUARE_CLIENT_ID = '{your square application id}'

   return OAuth2.createService('Square')
     // Set the endpoint URLs.
     .setAuthorizationBaseUrl('https://connect.squareup.com/oauth2/authorize')
     .setTokenUrl('https://connect.squareup.com/oauth2/token')

     // Set the client ID and secret.
     .setClientId(SQUARE_CLIENT_ID)
     .setClientSecret(SQUARE_CLIENT_SECRET)

     // Set the name of the callback function that should be invoked to
     // complete the OAuth flow.
     .setCallbackFunction('authCallbackSquare')

     // Set the property store where authorized tokens should be persisted.
     // Change this to .getUserProperties() if you are having multiple google users authorize the service:
     // this will prevent one user's token from being visible to others.
     .setPropertyStore(PropertiesService.getScriptProperties())

     // Set the scopes needed.  For a full list see https://developer.squareup.com/docs/oauth-api/square-permissions
     .setScope(
       [
         'ORDERS_WRITE',
         'PAYMENTS_WRITE',
         'PAYMENTS_READ',
         'ORDERS_READ',
         'MERCHANT_PROFILE_READ'
       ]
         .join(" ")
     )
     // Set grant type
     .setGrantType('authorization_code')
 }

And include the callback function that will store the token:

function authCallbackSquare(request)
{
  var service = getSquareService();

  // Now process request
  var authorized = service.handleCallback(request);
  if (authorized)
  {
    return HtmlService.createHtmlOutput('Success! You can close this tab.');
  } else
  {
    return HtmlService.createHtmlOutput('Denied. You can close this tab.');
  }
}

If your script is bound to a spreadsheet, you can run authorizeSquareUser() in the repo to get a sidebar that initiates the authorization flow.  Otherwise, run this modified version:

 function authorizeSquareUser()
 {
   var service = getSquareService();
   var authorizationUrl = service.getAuthorizationUrl();
   console.log("Auth URL is %s", authorizationUrl);
 }

and then visit the url that is logged. At this url you will log in to your square account, and then you should be redirected to a page that says "Success! You can close this tab."

At this point, the Square user's OAuth token has been stored in the script properties of your project.  You are now ready to make a call to the Square API.  When doing this, you access the stored token using getSquareService().getAccessToken(), so your headers will look like

var headers = {
  'Authorization': 'Bearer ' + getSquareService().getAccessToken(),
  'Square-Version': '2022-01-20',
  'Content-Type': 'application/json'
}

Then you can call

UrlFetchApp.fetch(url, {'method': 'GET', 'headers': headers}) // Change GET method depending on the action you are performing


答:
What you want is to find a value in an array.

You can use includes

```<code>    const array = ["23435","87567", "34536","45234","34532","65365"]

    const aConstant = "23435"

    return (<div>{ array.includes(aConstant) ? 'a' : 'b' }</div>)
</code>```

Same thing with indexOf

```<code>    const array = ["23435","87567", "34536","45234","34532","65365"]

    const aConstant = "23435"

    return (<div>{ array.indexOf(aConstant) !== -1 ? 'a' : 'b' }</div>)
</code>```

You can also try filter

```<code>    const array = ["23435","87567", "34536","45234","34532","65365"]

    const aConstant = "23435"

    return (<div>{ Boolean(array.filter( x => x === aConstant)) ? 'a' : 'b' }</div>)
</code>```

And even find

```<code>    const array = ["23435","87567", "34536","45234","34532","65365"]

    const aConstant = "23435"

    return (<div>{ array.find( x => x === aConstant) ? 'a' : 'b' }</div>)
</code>```

Title: How to find item in array in React

Body:
What you want is to find a value in an array.

You can use includes

    const array = ["23435","87567", "34536","45234","34532","65365"]

    const aConstant = "23435"

    return (<div>{ array.includes(aConstant) ? 'a' : 'b' }</div>)

Same thing with indexOf

    const array = ["23435","87567", "34536","45234","34532","65365"]

    const aConstant = "23435"

    return (<div>{ array.indexOf(aConstant) !== -1 ? 'a' : 'b' }</div>)

You can also try filter

    const array = ["23435","87567", "34536","45234","34532","65365"]

    const aConstant = "23435"

    return (<div>{ Boolean(array.filter( x => x === aConstant)) ? 'a' : 'b' }</div>)

And even find

    const array = ["23435","87567", "34536","45234","34532","65365"]

    const aConstant = "23435"

    return (<div>{ array.find( x => x === aConstant) ? 'a' : 'b' }</div>)


问:
JQuery Select a radio button (onclick)
I have a function using jquery that updates a form when an image is click.

I need to add to that function so that a specified radio button is selected.

How can I select a radio button using jquery please?

UPDATE:

I'll explain further...I have overlayed an image and hid the radio button...so what the user clicks on an image it will check the selected radio.

Here's how each radio looks like:

```<code><label style="display: inline; " for="select_theme_a">
<img src="images/icons/theme1.png" />
<input checked="checked" class="select_control" id="select_theme_a" name="select_theme" type="radio" value="a" onclick="return submitForm();" style="display:none" />
</label>
</code>```

There's 4 radio buttons .. 4 different images to click  on.

Hope this helps

答:
If radio element is inside same parent element as image than you can use this piece of code inside function that handles image click event:</p>

```<code>$(this).parent().find(":radio").attr('checked', true);
</code>```

Title: JQuery Select a radio button (onclick)

Body:
I have a function using jquery that updates a form when an image is click.

I need to add to that function so that a specified radio button is selected.

How can I select a radio button using jquery please?

UPDATE:

I'll explain further...I have overlayed an image and hid the radio button...so what the user clicks on an image it will check the selected radio.

Here's how each radio looks like:

<input checked="checked" class="select_control" id="select_theme_a" name="select_theme" type="radio" value="a" onclick="return submitForm();" style="display:none" />

There's 4 radio buttons .. 4 different images to click  on.

Hope this helps

Body:
If radio element is inside same parent element as image than you can use this piece of code inside function that handles image click event:

$(this).parent().find(":radio").attr('checked', true);


问:
Python 3.9 open file as binary
I would like to open a file in Python 3.9 in binary format, but it looks like the ASCII signs are not getting interpreted as bytes.

My code:

```<code>f = open("Unbenannt.png",'rb').read()[0:10]

print(f)
</code>```

I get this output:

```<code>b'\x89PNG\r\n\x1a\n\x00\x00'
</code>```

How do I get it like this?

```<code>b'\x89\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00'
</code>```

答:
you are confusing representation with the thing being represented... you have bytes

by default a bytestring representation converts printable ascii characters to their printable ascii character

if you want to interpret it as integers from 0-255

```<code>file_bytes = b'1234567\x119A'
print([b for b in file_bytes])
# [49, 50, 51, 52, 53, 54, 55, 17, 57, 65]
</code>```

if you want to have a list of hex strings

```<code>print([f'{b:02x}' for b in file_bytes])
# ['31', '32', '33', '34', '35', '36', '37', '11', '39', '41']
</code>```

if you want just a single string with \xXX instead of any ascii you can do almost the same

```<code>print(''.join([f'\\x{b:02x}' for b in file_bytes]))
# '\x31\x32\x33\x34\x35\x36\x37\x11\x39\x41'
</code>```

Title: Python 3.9 open file as binary

Body:
I would like to open a file in Python 3.9 in binary format, but it looks like the ASCII signs are not getting interpreted as bytes.

My code:

f = open("Unbenannt.png",'rb').read()[0:10]

print(f)

I get this output:

b'\x89PNG\r\n\x1a\n\x00\x00'

How do I get it like this?

b'\x89\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00'

Body:
you are confusing representation with the thing being represented... you have bytes

by default a bytestring representation converts printable ascii characters to their printable ascii character

if you want to interpret it as integers from 0-255

file_bytes = b'1234567\x119A'
print([b for b in file_bytes])
# [49, 50, 51, 52, 53, 54, 55, 17, 57, 65]

if you want to have a list of hex strings

print([f'{b:02x}' for b in file_bytes])
# ['31', '32', '33', '34', '35', '36', '37', '11', '39', '41']

if you want just a single string with \xXX instead of any ascii you can do almost the same

print(''.join([f'\\x{b:02x}' for b in file_bytes]))
# '\x31\x32\x33\x34\x35\x36\x37\x11\x39\x41'


问:
Flutter Cannot run Project.afterEvaluate(Closure) when the project is already evaluated
Workaround way: Looks like there is dependecy of onesignal plugin on flutter_tools. The solution is to place onesignal plugin after it in the sequence in the "android/app/build.gradle":

```<code>apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
apply plugin: 'com.onesignal.androidsdk.onesignal-gradle-plugin'
</code>```

After upgrading Flutter version from 2.8.1 to 2.10, I started getting the following error. I reinstalled Flutter but the result did not change. When I downgrade Flutter to 2.8.1, it works fine, but when I upgrade to 2.10 it doesn't.

```<code>
Running Gradle task 'assembleDebug'...

FAILURE: Build failed with an exception.

* Where:
Script '/Users/aksoyhlc/flutter/flutter/packages/flutter_tools/gradle/flutter.gradle' line: 421

 What went wrong:
A problem occurred evaluating root project 'android'.
> A problem occurred configuring project ':app'.
   > **Cannot run Project.afterEvaluate(Closure) when the project is already evaluated.**

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUİLD FAILED in 798ms
Exception: Gradle task assembleDebug failed with exit code 1
</code>```

part of android/app/build.gradle file

```<code>buildscript {
    repositories {

        google()  // Google's Maven repository
        maven { url 'https://plugins.gradle.org/m2/' }
    }
    dependencies {

        classpath 'gradle.plugin.com.onesignal:onesignal-gradle-plugin:[0.12.6, 0.99.99]'
        classpath 'com.google.gms:google-services:4.3.8'
    }
}
allprojects {

    repositories {
        // Check that you have the following line (if not, add it):
        google()  // Google's Maven repository

    }
}
apply plugin: 'com.onesignal.androidsdk.onesignal-gradle-plugin'
</code>```

android/build.gradle file

```<code>buildscript {
    ext.kotlin_version = '1.6.10'
    repositories {
        google()
        mavenCentral()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:4.1.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.google.gms:google-services:4.3.8'

    }

}

allprojects {
    repositories {
        google()
        mavenCentral()
       /* maven {
            url "${project(':background_fetch').projectDir}/libs"
        }*/
    }
}

rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
    project.evaluationDependsOn(':app')
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

</code>```
```<code>[✓] Flutter (Channel stable, 2.10.0, on macOS 12.0.1 21A559 darwin-x64, locale
    tr-TR)
    • Flutter version 2.10.0 at /Users/aksoyhlc/flutter/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 5f105a6ca7 (4 days ago), 2022-02-01 14:15:42 -0800
    • Engine revision 776efd2034
    • Dart version 2.16.0
    • DevTools version 2.9.2

[✓] Android toolchain - develop for Android devices (Android SDK version
    32.1.0-rc1)
    • Android SDK at /Users/aksoyhlc/Library/Android/sdk
    • Platform android-32, build-tools 32.1.0-rc1
    • Java binary at: /Applications/Android
      Studio.app/Contents/jre/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.11+0-b60-7590822)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 13.2.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • CocoaPods version 1.11.2

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2021.1)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.11+0-b60-7590822)

[✓] VS Code (version 1.64.0)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.34.0

[✓] Connected device (2 available)
    • Redmi Note 8 Pro (mobile) • ------- • android-arm64  • Android 11
      (API 30)
    • Chrome (web)              • chrome           • web-javascript • Google
      Chrome 98.0.4758.80

[✓] HTTP Host Availability
    • All required HTTP hosts are available
</code>```

答:
Have the same issue.
Still didn't solve it, but looks like something wrong with an onesignal plugin. If you will remove it, everything works. At least for me.

Issue opened in the OneSignal-Gradle-Plugin repo:
https://github.com/OneSignal/OneSignal-Gradle-Plugin/issues/184

Body:
Workaround way: Looks like there is dependecy of onesignal plugin on flutter_tools. The solution is to place onesignal plugin after it in the sequence in the "android/app/build.gradle":

apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
apply plugin: 'com.onesignal.androidsdk.onesignal-gradle-plugin'

After upgrading Flutter version from 2.8.1 to 2.10, I started getting the following error. I reinstalled Flutter but the result did not change. When I downgrade Flutter to 2.8.1, it works fine, but when I upgrade to 2.10 it doesn't.

Running Gradle task 'assembleDebug'...

FAILURE: Build failed with an exception.

* Where:
Script '/Users/aksoyhlc/flutter/flutter/packages/flutter_tools/gradle/flutter.gradle' line: 421

 What went wrong:
A problem occurred evaluating root project 'android'.
> A problem occurred configuring project ':app'.
   > **Cannot run Project.afterEvaluate(Closure) when the project is already evaluated.**

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUİLD FAILED in 798ms
Exception: Gradle task assembleDebug failed with exit code 1

part of android/app/build.gradle file

buildscript {
    repositories {

        google()  // Google's Maven repository
        maven { url 'https://plugins.gradle.org/m2/' }
    }
    dependencies {

        classpath 'gradle.plugin.com.onesignal:onesignal-gradle-plugin:[0.12.6, 0.99.99]'
        classpath 'com.google.gms:google-services:4.3.8'
    }
}
allprojects {

    repositories {
        // Check that you have the following line (if not, add it):
        google()  // Google's Maven repository

    }
}
apply plugin: 'com.onesignal.androidsdk.onesignal-gradle-plugin'

android/build.gradle file

buildscript {
    ext.kotlin_version = '1.6.10'
    repositories {
        google()
        mavenCentral()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:4.1.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.google.gms:google-services:4.3.8'

    }

}

allprojects {
    repositories {
        google()
        mavenCentral()
       /* maven {
            url "${project(':background_fetch').projectDir}/libs"
        }*/
    }
}

rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
    project.evaluationDependsOn(':app')
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

[✓] Flutter (Channel stable, 2.10.0, on macOS 12.0.1 21A559 darwin-x64, locale
    tr-TR)
    • Flutter version 2.10.0 at /Users/aksoyhlc/flutter/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 5f105a6ca7 (4 days ago), 2022-02-01 14:15:42 -0800
    • Engine revision 776efd2034
    • Dart version 2.16.0
    • DevTools version 2.9.2

[✓] Android toolchain - develop for Android devices (Android SDK version
    32.1.0-rc1)
    • Android SDK at /Users/aksoyhlc/Library/Android/sdk
    • Platform android-32, build-tools 32.1.0-rc1
    • Java binary at: /Applications/Android
      Studio.app/Contents/jre/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.11+0-b60-7590822)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 13.2.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • CocoaPods version 1.11.2

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2021.1)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.11+0-b60-7590822)

[✓] VS Code (version 1.64.0)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.34.0

[✓] Connected device (2 available)
    • Redmi Note 8 Pro (mobile) • ------- • android-arm64  • Android 11
      (API 30)
    • Chrome (web)              • chrome           • web-javascript • Google
      Chrome 98.0.4758.80

[✓] HTTP Host Availability
    • All required HTTP hosts are available


问:
Initializing from a pair in constructur intializer list
I have a function f returning a pair of objects of classes A and B:

```<code>auto f() -> std::pair<A,B>;
</code>```

Furthermore, I have a class C that has A and B as members:

```<code>class C {
  public:
    C();
  private:
    A a;
    B b;
};
</code>```

In the constructor of C, I want to use the member initalizer list and initialize with the output of f:

```<code>C(): a(f().first), b(f().second) {}
</code>```

This calls f twice though and it is a quite complicated function.
Is there a way to achieve this using the member-initializer list without calling f twice? The internal structure of C can unfortunately not be changed.

答:
Improving on the idea from AnkitKumar's answer:</p>
```<code>class C
{
    A a;
    B b;

    C(std::pair<A,B> &&pair) : a(std::move(pair.first)), b(std::move(pair.second)) {}

  public:
    C() : C(f()) {}
};
</code>```

Body:
I have a function f returning a pair of objects of classes A and B:

auto f() -> std::pair;

Furthermore, I have a class C that has A and B as members:

class C {
  public:
    C();
  private:
    A a;
    B b;
};

In the constructor of C, I want to use the member initalizer list and initialize with the output of f:

C(): a(f().first), b(f().second) {}

This calls f twice though and it is a quite complicated function.
Is there a way to achieve this using the member-initializer list without calling f twice? The internal structure of C can unfortunately not be changed.

Body:
Improving on the idea from AnkitKumar's answer:

class C
{
    A a;
    B b;

    C(std::pair<A,B> &&pair) : a(std::move(pair.first)), b(std::move(pair.second)) {}

  public:
    C() : C(f()) {}
};


问:
Finding the maximum product of a path in binary tree
I need some help to come up with an algorithm to calculate maximum product of the values along any path from leaf to root of a binary tree. So far I have:

```<code>int max_path_prod_rec(Tree* t, int max_so_far, int path_prod) {
    if (is_leaf(t))
        return t->value;

    int left = max_path_prod_rec(t->left, max_so_far, path_prod);
    int right = max_path_prod_rec(t->right, max_so_far, path_prod);

    if (left > right)
        return left * t->value;
    else
        return right * t->value;
}

int max_path_prod(Tree* t) {
    require("path product only defined for non-empty trees", t != NULL);
    return max_path_prod_rec(t, INT_MIN, 1);
}
</code>```

The problem is this function doesn't work when there are 2 negative numbers in a row, like 10 * (-3) * (-6). How can I improve upon this?

Edit: examples:

```<code>    //   10
    //  2   5
    // 1 -3 4 -6
    t = node(node(leaf(1), 2, leaf(-3)), 10, node(leaf(4), 5, leaf(-6)));
    printf("%i\n", max_path_prod(t));
</code>```

Will return 10 * 5 * 4 == 200. But

```<code>    //   10
    //  2   -5
    // 1 -3 4 -6
    t = node(node(leaf(1), 2, leaf(-3)), 10, node(leaf(4), -5, leaf(-6)));
    printf("%i\n", max_path_prod(t));
</code>```

Returns 10 * 2 * 1 == 20 instead of 10 * (-5) * (-6) == 300

答:
The product of a path can only be known when all its nodes have been visited and no partial path is decisive. So you have to traverse the entire tree. Arrange a standard tree traversal, but keep a trace of the products along the partial paths, and on every node update the maximum so far.

(Your solution abandons some paths prematurely.)

A simple solution:

```<code>if (is_leaf(t))
    return t->value;
else
    return max(t->value * product(t->left), t->value * product(t->right));
</code>```

Body:
I need some help to come up with an algorithm to calculate maximum product of the values along any path from leaf to root of a binary tree. So far I have:

int max_path_prod_rec(Tree* t, int max_so_far, int path_prod) {
    if (is_leaf(t))
        return t->value;

    int left = max_path_prod_rec(t->left, max_so_far, path_prod);
    int right = max_path_prod_rec(t->right, max_so_far, path_prod);

    if (left > right)
        return left * t->value;
    else
        return right * t->value;
}

int max_path_prod(Tree* t) {
    require("path product only defined for non-empty trees", t != NULL);
    return max_path_prod_rec(t, INT_MIN, 1);
}

The problem is this function doesn't work when there are 2 negative numbers in a row, like 10 * (-3) * (-6). How can I improve upon this?

Edit: examples:

    //   10
    //  2   5
    // 1 -3 4 -6
    t = node(node(leaf(1), 2, leaf(-3)), 10, node(leaf(4), 5, leaf(-6)));
    printf("%i\n", max_path_prod(t));

Will return 10 * 5 * 4 == 200. But

    //   10
    //  2   -5
    // 1 -3 4 -6
    t = node(node(leaf(1), 2, leaf(-3)), 10, node(leaf(4), -5, leaf(-6)));
    printf("%i\n", max_path_prod(t));

Returns 10 * 2 * 1 == 20 instead of 10 * (-5) * (-6) == 300

Body:
The product of a path can only be known when all its nodes have been visited and no partial path is decisive. So you have to traverse the entire tree. Arrange a standard tree traversal, but keep a trace of the products along the partial paths, and on every node update the maximum so far.

(Your solution abandons some paths prematurely.)

A simple solution:

if (is_leaf(t))
    return t->value;
else
    return max(t->value * product(t->left), t->value * product(t->right));