问:
FosUserBundle Registration, which saves data into 2 different tables
I am using FOSUserbundle in symfony 3 and want to use a second table,
where I save the address data.

Therefore I use the extended User Entity and the addresses Entity.

Workflow:

f.e. first_name,last_name,company and all other Formdata should go to md_user table.

copy of first_name,last_name,company etc should go to md_addresses table, which has got the "customer_id" field of md_user.id

To get it working I use the Eventlistener in RegistrationType:

```<code>->addEventListener(FormEvents::POST_SUBMIT, array($this, 'onPreSetData'));
</code>```

and the method:

```<code> public function onPreSetData(FormEvent $event)
{
    $user = $event->getData();
    $user->addAddress(new Addresses());
    $event->setData($user);

}
</code>```

Before I use $event->setData($user) in RegistrationType, the $user looks like:

My Questions are:

1) How to get the back the field id of md_user from doctrine

2) How to save the other data with this id to md_addresses

Thats what I have done right now.

User Entity:

```<code>namespace AppBundle\Entity;

 class User extends BaseUser
{

   /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * Different Logins for One Customer
     * @ORM\Column(name="customer_id",type="integer",nullable=true,options={"default":null})
     * @ORM\OneToMany(targetEntity="Addresses", mappedBy="user", cascade={"persist","remove"})
     **/
    protected $customer_id;

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

     /**
      * @ORM\Column(name="mandant",type="integer")
      */
    protected $mandant;

     /**
      * @var string
      * @ORM\Column(name="salutation", type="string", length=1)
      */
     protected $salutation;

     /**
      * @var string
      * @ORM\Column(name="first_name", type="string", length=120)
      * @Assert\Length(
      *     min=2,
      *     max=120,
      *     minMessage="The name is too short.",
      *     maxMessage="The name is too long.",
      *     groups={"Registration", "Profile"}
      * )
      */
     protected $first_name;

     /**
      * @var string
      * @ORM\Column(name="last_name", type="string", length=255)
      * @Assert\Length(
      *     min=2,
      *     max=255,
      *     minMessage="The name is too short.",
      *     maxMessage="The name is too long.",
      *     groups={"Registration", "Profile"}
      * )
      */
     protected $last_name;

     /**
      * @var string
      * @ORM\Column(name="company", type="string", length=255)
      */
     protected $company;

     /**
      * @var string
      * @ORM\Column(type="string", type="string", length=150)
      */
     protected $street;

     /**
      * @var string
      * @ORM\Column(type="string", type="string", length=30)
      */
     protected $street_number;

     /**
      * @var string
      * @ORM\Column(type="string", type="string", length=150)
      */
     protected $city;

     /**
      * @var string
      * @ORM\Column(type="string", type="string", length=150)
      */
     protected $plz;

     /**
      * @var string
      * @ORM\Column(name="ustid", type="string", length=30)
      */
     protected $ustid;

     /**
      * @var string
      * @ORM\Column(name="country", type="string", length=6)
      */
     protected $country;

     /**
      * @ORM\Column(name="telephone",type="string",length=120)
      */
     protected $telephone;

     /**
      * @ORM\Column(name="email_info", type="string",length=255,nullable=true)
      */
     protected $email_info;
     /**
      * @ORM\Column(name="email_invoice", type="string",length=255,nullable=true)
      */
     protected $email_invoice;

     /**
      * @ORM\Column(name="send_info", type="boolean",nullable=true)
      */
     protected $send_info = true;

     /**
      * @ORM\Column(name="invoice_pdf", type="boolean",nullable=true)
      */
     protected $invoice_pdf = true;

     /**
      * @ORM\OneToMany(targetEntity="AppBundle\Entity\Addresses", mappedBy="customer_id", cascade={"persist","remove"})
      */
     protected $addresses;
     /**
      * @var bool
      * @ORM\Column(name="newsletter", type="boolean")
      */
     protected $newsletter=true;

     public function __construct()
     {
         parent::__construct();
         $this->created         = new \DateTime();
//         $this->addresses              = new ArrayCollection();
     }

     /**
      * @return mixed
      */
     public function getEmailInfo()
     {
         return $this->email_info;
     }

     public function setEmailInfo($email_info)
     {
         $this->email_info = is_null($email_info) ? $this->email : $email_info;
         return $this;
     }

     public function getEmailInvoice()
     {
         return $this->email_invoice;
     }

     /**
      * @param mixed $email_invoice
      * @return User
      */
     public function setEmailInvoice($email_invoice)
     {
         $this->email_invoice = is_null($email_invoice) ? $this->email : $email_invoice;
         return $this;
     }

     /**
      * @return mixed
      */
     public function getInvoicePdf()
     {
         return $this->invoice_pdf;
     }

     /**
      * @param mixed $invoice_pdf
      * @return User
      */
     public function setInvoicePdf($invoice_pdf)
     {
         $this->invoice_pdf = $invoice_pdf;
         return $this;
     }

     /**
      * @return mixed
      */
     public function getSendInfo()
     {
         return $this->send_info;
     }

     /**
      * @param mixed $send_info
      * @return User
      */
     public function setSendInfo($send_info)
     {
         $this->send_info = $send_info;
         return $this;
     }

     public function getTelephone()
     {
         return $this->telephone;
     }

     /**
      * @param mixed $telephone
      * @return User
      */
     public function setTelephone($telephone)
     {
         $this->telephone = $telephone;
         return $this;
     }

     public function setEmail($email)
     {
         $email = is_null($email) ? '' : $email;
         parent::setEmail($email);
         $this->setUsername($email);
         return $this;
     }

     /**
      * @return string
      */
     public function getSalutation()
     {
         return $this->salutation;
     }

     /**
      * @param string $saluation
      * @return User
      */
     public function setSalutation($salutation)
     {
         $this->salutation = $salutation;
         return $this;
     }

     /**
      * @return string
      */
     public function getFirstName()
     {
         return $this->first_name;
     }

     /**
      * @param string $first_name
      * @return User
      */
     public function setFirstName($first_name)
     {

         $this->first_name = $first_name;
         return $this;
     }

     /**
      * @return string
      */
     public function getLastName()
     {
         return $this->last_name;
     }

     /**
      * @param string $last_name
      * @return User
      */
     public function setLastName($last_name)
     {
         $this->last_name = $last_name;
         return $this;
     }

     /**
      * @return string
      */
     public function getCompany()
     {
         return $this->company;
     }

     /**
      * @param string $company
      * @return User
      */
     public function setCompany($company)
     {
         $this->company = $company;
         return $this;
     }

     /**
      * @return string
      */
     public function getUstid()
     {
         return $this->ustid;
     }

     /**
      * @param string $ustid
      * @return User
      */
     public function setUstid($ustid)
     {
         $this->ustid = $ustid;
         return $this;
     }

     public function getName()
     {
         return 'user';
     }

     /**
      * @return mixed
      */
     public function getMandant()
     {
         return $this->mandant;
     }

     /**
      * @param mixed $mandant
      * @return User
      */
     public function setMandant($mandant)
     {
         $this->mandant = $mandant;
         return $this;
     }

     /**
      * @return string
      */
     public function getCity()
     {
         return $this->city;
     }

     /**
      * @param string $city
      * @return User
      */
     public function setCity($city)
     {
         $this->city = $city;
         return $this;
     }

     /**
      * @return string
      */
     public function getCountry()
     {
         return $this->country;
     }

     /**
      * @param string $country
      * @return User
      */
     public function setCountry($country)
     {
         $this->country = $country;
         return $this;
     }

     /**
      * @return string
      */
     public function getStreet()
     {
         return $this->street;
     }

     /**
      * @param string $street
      * @return User
      */
     public function setStreet($street)
     {
         $this->street = $street;
         return $this;
     }

     /**
      * @return string
      */
     public function getStreetNumber()
     {
         return $this->street_number;
     }

     /**
      * @param string $street_number
      * @return User
      */
     public function setStreetNumber($street_number)
     {
         $this->street_number = $street_number;
         return $this;
     }

     /**
      * @return string
      */
     public function getPlz()
     {
         return $this->plz;
     }

     /**
      * @param string $plz
      * @return User
      */
     public function setPlz($plz)
     {
         $this->plz = $plz;
         return $this;
     }

     /**
      * Set created
      *
      * @param \DateTime $created
      *
      * @return User
      */
     public function setCreated($created)
     {
         $this->created = $created;

         return $this;
     }

     /**
      * Get created
      *
      * @return \DateTime
      */
     public function getCreated()
     {
         return $this->created;
     }

     /**
      * @return mixed
      */
     public function getCustomerId()
     {
         return $this->customer_id;
     }

     /**
      * @param mixed $customer_id
      * @return User
      */
     public function setCustomerId($customer_id)
     {
         $this->customer_id = $customer_id;
         return $this;
     }

     /**
      * @return mixed
      */
     public function getId()
     {
         return $this->id;
     }

     /**
      * Set newsletter
      * @param boolean $newsletter
      * @return User
      */
     public function setNewsletter($newsletter)
     {
         $this->newsletter = $newsletter;

         return $this;
     }

     /**
      * Get newsletter
      * @return bool
      */
     public function getNewsletter()
     {
         return $this->newsletter;
     }

     /**
      * Add professional
      *
      * @param \AppBundle\Entity\Addresses $addresses
      *
      * @return User
      */
     public function addAddress(\AppBundle\Entity\Addresses $addresses)
     {
         $addresses->setSalutation($this->salutation);
         $addresses->setFirstName($this->first_name);
         $addresses->setLastName($this->last_name);
         $addresses->setEmail($this->email);
         $addresses->setTelephone($this->telephone);
         $addresses->setStreet($this->street);
         $addresses->setStreetNumber($this->street_number);
         $addresses->setPlz($this->plz);
         $addresses->setCity($this->city);
         $addresses->setCountry($this->country);
         $addresses->setCompany($this->company);
         $addresses->setInvoice(true);
         $addresses->setDelivery(true);
         $addresses->setCustomerId($this->id);
         return $this->addresses = $addresses;
     }
     /**
      * Get addresses
      *
      * @return \Doctrine\Common\Collections\Collection
      */
     public function getAddresses()
     {
         return $this->addresses;
     }

     public function getFullName()
     {
         return $this->first_name.' '.$this->last_name;
     }
 }
</code>```

Addresses Entity:

```<code>namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Table(name="md_addresses")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\AddressesRepository")
 */

class Addresses
{
    /**
     * @var id

     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Id
     */
    protected $id;

    /**
     * @ORM\Column(name="customer_id", type="integer")
     * @ORM\ManyToOne(targetEntity="User", inversedBy="addresses", cascade={"persist"})
     * @ORM\JoinColumn(name="customer_id", referencedColumnName="id")
     */
    protected $customer_id;

    /**
     * @ORM\Column(name="salutation", type="string",length=1)
     */
    protected $salutation;
    /**
     * @var string
     * @ORM\Column(name="first_name", type="string", length=120)
     */

    protected $first_name;

    /**
     * @var string
     * @ORM\Column(name="last_name", type="string", length=255)
     */

    protected $last_name;

    /**
     * @ORM\Column(name="telephone",type="string",length=120)
     */
    protected $telephone;

    /**
     * @ORM\Column(name="email",type="string",length=255)
     */
    protected $email;

    /**
     * @var string
     * @ORM\Column(name="company", type="string", length=255)
     */
    protected $company;

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

    /**
     * @ORM\Column(type="string", length=30)
     */
    protected $street_number;

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

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

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

    /**
     * @ORM\Column(type="string", length=30)
     */
    protected $plz;
    /**
     * @ORM\Column(type="string", length=100)
     */
    protected $city;

    /**
     * @ORM\Column(type="string", length=10)
     */

    protected $country;
    /**
     * @ORM\Column(type="boolean", options={"default":true})
     */

    protected $invoice;
    /**
     * @ORM\Column(type="boolean", options={"default":true})
     */

    protected $sender;
    /**
     * @ORM\Column(type="boolean", options={"default":true})
     */
    protected $delivery;

      /**
     * @return mixed
     */
    public function getSalutation()
    {
        return $this->salutation;
    }

    /**
     * @param mixed $salutation
     * @return Addresses
     */
    public function setSalutation($salutation)
    {
        $this->salutation = $salutation;
        return $this;
    }

    /**
     * @return string
     */
    public function getCompany()
    {
        return $this->company;
    }

    /**
     * @param string $company
     * @return Addresses
     */
    public function setCompany($company)
    {
        $this->company = $company;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getStreet()
    {
        return $this->street;
    }

    /**
     * @param mixed $street
     * @return Addresses
     */
    public function setStreet($street)
    {
        $this->street = $street;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getStreetNumber()
    {
        return $this->street_number;
    }

    /**
     * @param mixed $street_number
     * @return Addresses
     */
    public function setStreetNumber($street_number)
    {
        $this->street_number = $street_number;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getAdditional1()
    {
        return $this->additional_1;
    }

    /**
     * @param mixed $additional_1
     * @return Addresses
     */
    public function setAdditional1($additional_1)
    {
        $this->additional_1 = $additional_1;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getAdditional2()
    {
        return $this->additional_2;
    }

    /**
     * @param mixed $additional_2
     * @return Addresses
     */
    public function setAdditional2($additional_2)
    {
        $this->additional_2 = $additional_2;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getAdditional3()
    {
        return $this->additional_3;
    }

    /**
     * @param mixed $additional_3
     * @return Addresses
     */
    public function setAdditional3($additional_3)
    {
        $this->additional_3 = $additional_3;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getPlz()
    {
        return $this->plz;
    }

    /**
     * @param mixed $plz
     * @return Addresses
     */
    public function setPlz($plz)
    {
        $this->plz = $plz;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getCity()
    {
        return $this->city;
    }

    /**
     * @param mixed $city
     * @return Addresses
     */
    public function setCity($city)
    {
        $this->city = $city;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getCountry()
    {
        return $this->country;
    }

    /**
     * @param mixed $country
     * @return Addresses
     */
    public function setCountry($country)
    {
        $this->country = $country;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getInvoice()
    {
        return $this->invoice;
    }

    /**
     * @param mixed $invoice
     * @return Addresses
     */
    public function setInvoice($invoice)
    {
        $this->invoice = $invoice;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getSender()
    {
        return $this->sender;
    }

    /**
     * @param mixed $sender
     * @return Addresses
     */
    public function setSender($sender)
    {
        $this->sender = $sender;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getDelivery()
    {
        return $this->delivery;
    }

    /**
     * @param mixed $delivery
     * @return Addresses
     */
    public function setDelivery($delivery)
    {
        $this->delivery = $delivery;
        return $this;
    }

    /**
     * Set user
     * @param \AppBundle\Entity\User $user
     * @return Addresses
     */
    public function setCustomerId(\AppBundle\Entity\User $customer_id = null)
    {
        $this->customer_id = $customer_id;

        return $this;
    }

    /**
     * Get user
     * @return \AppBundle\Entity\User
     */
    public function getCustomerId()
    {
        return $this->customer_id;
    }

    /**
     * @return string
     */
    public function getFirstName()
    {
        return $this->first_name;
    }

    /**
     * @param string $first_name
     * @return Addresses
     */
    public function setFirstName($first_name)
    {
        $this->first_name = $first_name;
        return $this;
    }

    /**
     * @return string
     */
    public function getLastName()
    {
        return $this->last_name;
    }

    /**
     * @param string $last_name
     * @return Addresses
     */
    public function setLastName($last_name)
    {
        $this->last_name = $last_name;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getTelephone()
    {
        return $this->telephone;
    }

    /**
     * @param mixed $telephone
     * @return Addresses
     */
    public function setTelephone($telephone)
    {
        $this->telephone = $telephone;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getEmail()
    {
        return $this->email;
    }

    /**
     * @param mixed $email
     * @return Addresses
     */
    public function setEmail($email)
    {
        $this->email = $email;
        return $this;
    }

}
</code>```

RegistrationType:

```<code>class RegistrationType extends AbstractType
{

    private $session;
    public function __construct(Session $session)
    {
        $this->session = $session;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {

        parent::buildForm($builder, $options);

        $builder ->add('salutation', SalutationType::class,
                        array('placeholder'   => 'form.choice'))
                 ->add('telephone',     TextType::class,array('required' => false))
                 ->remove('username')
                 ->add('first_name',    TextType::class)
                 ->add('mandant',    HiddenType::class,array('data'=>$this->session->get('mandantId')))
                 ->add('last_name',     TextType::class)
                 ->add('company',       TextType::class,array('required' => false))
                 ->add('street',         TextType::class)
                 ->add('street_number',  TextType::class)
                 ->add('ustid',         TextType::class,array('required' => false))
                 ->add('plz', TextType::class)
                 ->add('city', TextType::class)
                 ->add('newsletter',CheckboxType::class,array('label' => false,'required' => false))
                 ->add('country', CountryType::class, [
                    'required' => true,
                    'placeholder' => 'form.choice',
                    'preferred_choices' => [
                        'DE', 'NL', 'BE', 'CH', 'AUT',
                    ]])
                  ->addEventListener(FormEvents::POST_SUBMIT, array($this, 'onPreSetData'));

    }

    public function onPreSetData(FormEvent $event)
    {
        $user = $event->getData();
        $user->addAddress(new Addresses());

        $event->setData($user);

    }

    public function getParent()

    {
        return 'FOS\UserBundle\Form\Type\RegistrationFormType';
    }

    public function getBlockPrefix()

    {
        return 'app_user_registration';
    }

    public function getName()

    {
        return $this->getBlockPrefix();
    }

}
</code>```

UPDATE:

```<code>class RegistrationSubscriber implements EventSubscriberInterface
{

    private $em;

    public function __construct(EntityManager $em)
    {
        $this->em = $em;
    }

    public static function getSubscribedEvents()
    {
        return [
            FOSUserEvents::REGISTRATION_COMPLETED => [
                ['onRegistrationSuccess']
                ],
            ];
    }

    public function onRegistrationSuccess(FilterUserResponseEvent $event)
    {
        $user = $event->getUser();
        $address = new Address();
        $address->setSalutation($user->getSalutation());
        $address->setFirstName($user->getFirstName());
        $address->setLastName($user->getLastName());
        $address->setEmail($user->getEmail());
        $address->setTelephone($user->getTelephone());
        $address->setStreet($user->getStreet());
        $address->setStreetNumber($user->getStreetNumber());
        $address->setPlz($user->getPlz());
        $address->setCity($user->getCity());
        $address->setCountry($user->getCountry());
        $address->setCompany($user->getCompany());
        $address->setCustomerId($user->getId());
        $user->addAddress($address);
        $this->em->persist($user);
        $this->em->flush();
    }

}
</code>```

答:
As Greg said it's easy to get the id from doctrine through the FOSUserBundle

Now, for the second part I would suggest you use a  Collection
In your User entity add an ArrayCollection property for your addresses.
And declare the methods to add a new collection to the user object.

```<code><?php

namespace AppBundle\Entity;

/**
 * User
 */
class User
{

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

    /**
     * Constructor
     */
    public function __construct()
    {

        $this->addresses = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Add address
     *
     * @param \AppBundle\Entity\Address $address
     *
     * @return User
     */
    public function addAddress(\AppBundle\Entity\Address $address)
    {
        $this->addresses[] = $address;

        return $this;
    }

    /**
     * Remove address
     *
     * @param \AppBundle\Entity\Address $address
     */
    public function removeAddress(\AppBundle\Entity\Address $address)
    {
        $this->addresses->removeElement($address);
    }

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

}
</code>```

Now when you create a new User you can call the addAddresses method to add a new address.

Example:

```<code>$user = new User;
$address = new Address;
... // copy of first_name,last_name,company to the address object

$address->setLastName($user->getLastName()); // or whatever field you want
$user->addAddress($address);

$em->persist($user);
$em->flush();
</code>```

Now you call the $user->getAddresses() method, and get all the addresses.

Body:
I am using FOSUserbundle in symfony 3 and want to use a second table,
where I save the address data.

Therefore I use the extended User Entity and the addresses Entity.

Workflow:

f.e. first_name,last_name,company and all other Formdata should go to md_user table.

copy of first_name,last_name,company etc should go to md_addresses table, which has got the "customer_id" field of md_user.id

To get it working I use the Eventlistener in RegistrationType:

->addEventListener(FormEvents::POST_SUBMIT, array($this, 'onPreSetData'));

and the method:

 public function onPreSetData(FormEvent $event)
{
    $user = $event->getData();
    $user->addAddress(new Addresses());
    $event->setData($user);

}

Before I use $event->setData($user) in RegistrationType, the $user looks like:

My Questions are:

1) How to get the back the field id of md_user from doctrine

2) How to save the other data with this id to md_addresses

Thats what I have done right now.

User Entity:

namespace AppBundle\Entity;

 class User extends BaseUser
{

   /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * Different Logins for One Customer
     * @ORM\Column(name="customer_id",type="integer",nullable=true,options={"default":null})
     * @ORM\OneToMany(targetEntity="Addresses", mappedBy="user", cascade={"persist","remove"})
     **/
    protected $customer_id;

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

     /**
      * @ORM\Column(name="mandant",type="integer")
      */
    protected $mandant;

     /**
      * @var string
      * @ORM\Column(name="salutation", type="string", length=1)
      */
     protected $salutation;

     /**
      * @var string
      * @ORM\Column(name="first_name", type="string", length=120)
      * @Assert\Length(
      *     min=2,
      *     max=120,
      *     minMessage="The name is too short.",
      *     maxMessage="The name is too long.",
      *     groups={"Registration", "Profile"}
      * )
      */
     protected $first_name;

     /**
      * @var string
      * @ORM\Column(name="last_name", type="string", length=255)
      * @Assert\Length(
      *     min=2,
      *     max=255,
      *     minMessage="The name is too short.",
      *     maxMessage="The name is too long.",
      *     groups={"Registration", "Profile"}
      * )
      */
     protected $last_name;

     /**
      * @var string
      * @ORM\Column(name="company", type="string", length=255)
      */
     protected $company;

     /**
      * @var string
      * @ORM\Column(type="string", type="string", length=150)
      */
     protected $street;

     /**
      * @var string
      * @ORM\Column(type="string", type="string", length=30)
      */
     protected $street_number;

     /**
      * @var string
      * @ORM\Column(type="string", type="string", length=150)
      */
     protected $city;

     /**
      * @var string
      * @ORM\Column(type="string", type="string", length=150)
      */
     protected $plz;

     /**
      * @var string
      * @ORM\Column(name="ustid", type="string", length=30)
      */
     protected $ustid;

     /**
      * @var string
      * @ORM\Column(name="country", type="string", length=6)
      */
     protected $country;

     /**
      * @ORM\Column(name="telephone",type="string",length=120)
      */
     protected $telephone;

     /**
      * @ORM\Column(name="email_info", type="string",length=255,nullable=true)
      */
     protected $email_info;
     /**
      * @ORM\Column(name="email_invoice", type="string",length=255,nullable=true)
      */
     protected $email_invoice;

     /**
      * @ORM\Column(name="send_info", type="boolean",nullable=true)
      */
     protected $send_info = true;

     /**
      * @ORM\Column(name="invoice_pdf", type="boolean",nullable=true)
      */
     protected $invoice_pdf = true;

     /**
      * @ORM\OneToMany(targetEntity="AppBundle\Entity\Addresses", mappedBy="customer_id", cascade={"persist","remove"})
      */
     protected $addresses;
     /**
      * @var bool
      * @ORM\Column(name="newsletter", type="boolean")
      */
     protected $newsletter=true;

     public function __construct()
     {
         parent::__construct();
         $this->created         = new \DateTime();
//         $this->addresses              = new ArrayCollection();
     }

     /**
      * @return mixed
      */
     public function getEmailInfo()
     {
         return $this->email_info;
     }

     public function setEmailInfo($email_info)
     {
         $this->email_info = is_null($email_info) ? $this->email : $email_info;
         return $this;
     }

     public function getEmailInvoice()
     {
         return $this->email_invoice;
     }

     /**
      * @param mixed $email_invoice
      * @return User
      */
     public function setEmailInvoice($email_invoice)
     {
         $this->email_invoice = is_null($email_invoice) ? $this->email : $email_invoice;
         return $this;
     }

     /**
      * @return mixed
      */
     public function getInvoicePdf()
     {
         return $this->invoice_pdf;
     }

     /**
      * @param mixed $invoice_pdf
      * @return User
      */
     public function setInvoicePdf($invoice_pdf)
     {
         $this->invoice_pdf = $invoice_pdf;
         return $this;
     }

     /**
      * @return mixed
      */
     public function getSendInfo()
     {
         return $this->send_info;
     }

     /**
      * @param mixed $send_info
      * @return User
      */
     public function setSendInfo($send_info)
     {
         $this->send_info = $send_info;
         return $this;
     }

     public function getTelephone()
     {
         return $this->telephone;
     }

     /**
      * @param mixed $telephone
      * @return User
      */
     public function setTelephone($telephone)
     {
         $this->telephone = $telephone;
         return $this;
     }

     public function setEmail($email)
     {
         $email = is_null($email) ? '' : $email;
         parent::setEmail($email);
         $this->setUsername($email);
         return $this;
     }

     /**
      * @return string
      */
     public function getSalutation()
     {
         return $this->salutation;
     }

     /**
      * @param string $saluation
      * @return User
      */
     public function setSalutation($salutation)
     {
         $this->salutation = $salutation;
         return $this;
     }

     /**
      * @return string
      */
     public function getFirstName()
     {
         return $this->first_name;
     }

     /**
      * @param string $first_name
      * @return User
      */
     public function setFirstName($first_name)
     {

         $this->first_name = $first_name;
         return $this;
     }

     /**
      * @return string
      */
     public function getLastName()
     {
         return $this->last_name;
     }

     /**
      * @param string $last_name
      * @return User
      */
     public function setLastName($last_name)
     {
         $this->last_name = $last_name;
         return $this;
     }

     /**
      * @return string
      */
     public function getCompany()
     {
         return $this->company;
     }

     /**
      * @param string $company
      * @return User
      */
     public function setCompany($company)
     {
         $this->company = $company;
         return $this;
     }

     /**
      * @return string
      */
     public function getUstid()
     {
         return $this->ustid;
     }

     /**
      * @param string $ustid
      * @return User
      */
     public function setUstid($ustid)
     {
         $this->ustid = $ustid;
         return $this;
     }

     public function getName()
     {
         return 'user';
     }

     /**
      * @return mixed
      */
     public function getMandant()
     {
         return $this->mandant;
     }

     /**
      * @param mixed $mandant
      * @return User
      */
     public function setMandant($mandant)
     {
         $this->mandant = $mandant;
         return $this;
     }

     /**
      * @return string
      */
     public function getCity()
     {
         return $this->city;
     }

     /**
      * @param string $city
      * @return User
      */
     public function setCity($city)
     {
         $this->city = $city;
         return $this;
     }

     /**
      * @return string
      */
     public function getCountry()
     {
         return $this->country;
     }

     /**
      * @param string $country
      * @return User
      */
     public function setCountry($country)
     {
         $this->country = $country;
         return $this;
     }

     /**
      * @return string
      */
     public function getStreet()
     {
         return $this->street;
     }

     /**
      * @param string $street
      * @return User
      */
     public function setStreet($street)
     {
         $this->street = $street;
         return $this;
     }

     /**
      * @return string
      */
     public function getStreetNumber()
     {
         return $this->street_number;
     }

     /**
      * @param string $street_number
      * @return User
      */
     public function setStreetNumber($street_number)
     {
         $this->street_number = $street_number;
         return $this;
     }

     /**
      * @return string
      */
     public function getPlz()
     {
         return $this->plz;
     }

     /**
      * @param string $plz
      * @return User
      */
     public function setPlz($plz)
     {
         $this->plz = $plz;
         return $this;
     }

     /**
      * Set created
      *
      * @param \DateTime $created
      *
      * @return User
      */
     public function setCreated($created)
     {
         $this->created = $created;

         return $this;
     }

     /**
      * Get created
      *
      * @return \DateTime
      */
     public function getCreated()
     {
         return $this->created;
     }

     /**
      * @return mixed
      */
     public function getCustomerId()
     {
         return $this->customer_id;
     }

     /**
      * @param mixed $customer_id
      * @return User
      */
     public function setCustomerId($customer_id)
     {
         $this->customer_id = $customer_id;
         return $this;
     }

     /**
      * @return mixed
      */
     public function getId()
     {
         return $this->id;
     }

     /**
      * Set newsletter
      * @param boolean $newsletter
      * @return User
      */
     public function setNewsletter($newsletter)
     {
         $this->newsletter = $newsletter;

         return $this;
     }

     /**
      * Get newsletter
      * @return bool
      */
     public function getNewsletter()
     {
         return $this->newsletter;
     }

     /**
      * Add professional
      *
      * @param \AppBundle\Entity\Addresses $addresses
      *
      * @return User
      */
     public function addAddress(\AppBundle\Entity\Addresses $addresses)
     {
         $addresses->setSalutation($this->salutation);
         $addresses->setFirstName($this->first_name);
         $addresses->setLastName($this->last_name);
         $addresses->setEmail($this->email);
         $addresses->setTelephone($this->telephone);
         $addresses->setStreet($this->street);
         $addresses->setStreetNumber($this->street_number);
         $addresses->setPlz($this->plz);
         $addresses->setCity($this->city);
         $addresses->setCountry($this->country);
         $addresses->setCompany($this->company);
         $addresses->setInvoice(true);
         $addresses->setDelivery(true);
         $addresses->setCustomerId($this->id);
         return $this->addresses = $addresses;
     }
     /**
      * Get addresses
      *
      * @return \Doctrine\Common\Collections\Collection
      */
     public function getAddresses()
     {
         return $this->addresses;
     }

     public function getFullName()
     {
         return $this->first_name.' '.$this->last_name;
     }
 }

Addresses Entity:

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Table(name="md_addresses")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\AddressesRepository")
 */

class Addresses
{
    /**
     * @var id

     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Id
     */
    protected $id;

    /**
     * @ORM\Column(name="customer_id", type="integer")
     * @ORM\ManyToOne(targetEntity="User", inversedBy="addresses", cascade={"persist"})
     * @ORM\JoinColumn(name="customer_id", referencedColumnName="id")
     */
    protected $customer_id;

    /**
     * @ORM\Column(name="salutation", type="string",length=1)
     */
    protected $salutation;
    /**
     * @var string
     * @ORM\Column(name="first_name", type="string", length=120)
     */

    protected $first_name;

    /**
     * @var string
     * @ORM\Column(name="last_name", type="string", length=255)
     */

    protected $last_name;

    /**
     * @ORM\Column(name="telephone",type="string",length=120)
     */
    protected $telephone;

    /**
     * @ORM\Column(name="email",type="string",length=255)
     */
    protected $email;

    /**
     * @var string
     * @ORM\Column(name="company", type="string", length=255)
     */
    protected $company;

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

    /**
     * @ORM\Column(type="string", length=30)
     */
    protected $street_number;

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

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

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

    /**
     * @ORM\Column(type="string", length=30)
     */
    protected $plz;
    /**
     * @ORM\Column(type="string", length=100)
     */
    protected $city;

    /**
     * @ORM\Column(type="string", length=10)
     */

    protected $country;
    /**
     * @ORM\Column(type="boolean", options={"default":true})
     */

    protected $invoice;
    /**
     * @ORM\Column(type="boolean", options={"default":true})
     */

    protected $sender;
    /**
     * @ORM\Column(type="boolean", options={"default":true})
     */
    protected $delivery;

      /**
     * @return mixed
     */
    public function getSalutation()
    {
        return $this->salutation;
    }

    /**
     * @param mixed $salutation
     * @return Addresses
     */
    public function setSalutation($salutation)
    {
        $this->salutation = $salutation;
        return $this;
    }

    /**
     * @return string
     */
    public function getCompany()
    {
        return $this->company;
    }

    /**
     * @param string $company
     * @return Addresses
     */
    public function setCompany($company)
    {
        $this->company = $company;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getStreet()
    {
        return $this->street;
    }

    /**
     * @param mixed $street
     * @return Addresses
     */
    public function setStreet($street)
    {
        $this->street = $street;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getStreetNumber()
    {
        return $this->street_number;
    }

    /**
     * @param mixed $street_number
     * @return Addresses
     */
    public function setStreetNumber($street_number)
    {
        $this->street_number = $street_number;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getAdditional1()
    {
        return $this->additional_1;
    }

    /**
     * @param mixed $additional_1
     * @return Addresses
     */
    public function setAdditional1($additional_1)
    {
        $this->additional_1 = $additional_1;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getAdditional2()
    {
        return $this->additional_2;
    }

    /**
     * @param mixed $additional_2
     * @return Addresses
     */
    public function setAdditional2($additional_2)
    {
        $this->additional_2 = $additional_2;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getAdditional3()
    {
        return $this->additional_3;
    }

    /**
     * @param mixed $additional_3
     * @return Addresses
     */
    public function setAdditional3($additional_3)
    {
        $this->additional_3 = $additional_3;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getPlz()
    {
        return $this->plz;
    }

    /**
     * @param mixed $plz
     * @return Addresses
     */
    public function setPlz($plz)
    {
        $this->plz = $plz;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getCity()
    {
        return $this->city;
    }

    /**
     * @param mixed $city
     * @return Addresses
     */
    public function setCity($city)
    {
        $this->city = $city;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getCountry()
    {
        return $this->country;
    }

    /**
     * @param mixed $country
     * @return Addresses
     */
    public function setCountry($country)
    {
        $this->country = $country;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getInvoice()
    {
        return $this->invoice;
    }

    /**
     * @param mixed $invoice
     * @return Addresses
     */
    public function setInvoice($invoice)
    {
        $this->invoice = $invoice;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getSender()
    {
        return $this->sender;
    }

    /**
     * @param mixed $sender
     * @return Addresses
     */
    public function setSender($sender)
    {
        $this->sender = $sender;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getDelivery()
    {
        return $this->delivery;
    }

    /**
     * @param mixed $delivery
     * @return Addresses
     */
    public function setDelivery($delivery)
    {
        $this->delivery = $delivery;
        return $this;
    }

    /**
     * Set user
     * @param \AppBundle\Entity\User $user
     * @return Addresses
     */
    public function setCustomerId(\AppBundle\Entity\User $customer_id = null)
    {
        $this->customer_id = $customer_id;

        return $this;
    }

    /**
     * Get user
     * @return \AppBundle\Entity\User
     */
    public function getCustomerId()
    {
        return $this->customer_id;
    }

    /**
     * @return string
     */
    public function getFirstName()
    {
        return $this->first_name;
    }

    /**
     * @param string $first_name
     * @return Addresses
     */
    public function setFirstName($first_name)
    {
        $this->first_name = $first_name;
        return $this;
    }

    /**
     * @return string
     */
    public function getLastName()
    {
        return $this->last_name;
    }

    /**
     * @param string $last_name
     * @return Addresses
     */
    public function setLastName($last_name)
    {
        $this->last_name = $last_name;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getTelephone()
    {
        return $this->telephone;
    }

    /**
     * @param mixed $telephone
     * @return Addresses
     */
    public function setTelephone($telephone)
    {
        $this->telephone = $telephone;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getEmail()
    {
        return $this->email;
    }

    /**
     * @param mixed $email
     * @return Addresses
     */
    public function setEmail($email)
    {
        $this->email = $email;
        return $this;
    }

}

RegistrationType:

class RegistrationType extends AbstractType
{

    private $session;
    public function __construct(Session $session)
    {
        $this->session = $session;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {

        parent::buildForm($builder, $options);

        $builder ->add('salutation', SalutationType::class,
                        array('placeholder'   => 'form.choice'))
                 ->add('telephone',     TextType::class,array('required' => false))
                 ->remove('username')
                 ->add('first_name',    TextType::class)
                 ->add('mandant',    HiddenType::class,array('data'=>$this->session->get('mandantId')))
                 ->add('last_name',     TextType::class)
                 ->add('company',       TextType::class,array('required' => false))
                 ->add('street',         TextType::class)
                 ->add('street_number',  TextType::class)
                 ->add('ustid',         TextType::class,array('required' => false))
                 ->add('plz', TextType::class)
                 ->add('city', TextType::class)
                 ->add('newsletter',CheckboxType::class,array('label' => false,'required' => false))
                 ->add('country', CountryType::class, [
                    'required' => true,
                    'placeholder' => 'form.choice',
                    'preferred_choices' => [
                        'DE', 'NL', 'BE', 'CH', 'AUT',
                    ]])
                  ->addEventListener(FormEvents::POST_SUBMIT, array($this, 'onPreSetData'));

    }

    public function onPreSetData(FormEvent $event)
    {
        $user = $event->getData();
        $user->addAddress(new Addresses());

        $event->setData($user);

    }

    public function getParent()

    {
        return 'FOS\UserBundle\Form\Type\RegistrationFormType';
    }

    public function getBlockPrefix()

    {
        return 'app_user_registration';
    }

    public function getName()

    {
        return $this->getBlockPrefix();
    }

}

UPDATE:

class RegistrationSubscriber implements EventSubscriberInterface
{

    private $em;

    public function __construct(EntityManager $em)
    {
        $this->em = $em;
    }

    public static function getSubscribedEvents()
    {
        return [
            FOSUserEvents::REGISTRATION_COMPLETED => [
                ['onRegistrationSuccess']
                ],
            ];
    }

    public function onRegistrationSuccess(FilterUserResponseEvent $event)
    {
        $user = $event->getUser();
        $address = new Address();
        $address->setSalutation($user->getSalutation());
        $address->setFirstName($user->getFirstName());
        $address->setLastName($user->getLastName());
        $address->setEmail($user->getEmail());
        $address->setTelephone($user->getTelephone());
        $address->setStreet($user->getStreet());
        $address->setStreetNumber($user->getStreetNumber());
        $address->setPlz($user->getPlz());
        $address->setCity($user->getCity());
        $address->setCountry($user->getCountry());
        $address->setCompany($user->getCompany());
        $address->setCustomerId($user->getId());
        $user->addAddress($address);
        $this->em->persist($user);
        $this->em->flush();
    }

}

Body:
As Greg said it's easy to get the id from doctrine through the FOSUserBundle

Now, for the second part I would suggest you use a  Collection
In your User entity add an ArrayCollection property for your addresses.
And declare the methods to add a new collection to the user object.

<?php

namespace AppBundle\Entity;

/**
 * User
 */
class User
{

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

    /**
     * Constructor
     */
    public function __construct()
    {

        $this->addresses = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Add address
     *
     * @param \AppBundle\Entity\Address $address
     *
     * @return User
     */
    public function addAddress(\AppBundle\Entity\Address $address)
    {
        $this->addresses[] = $address;

        return $this;
    }

    /**
     * Remove address
     *
     * @param \AppBundle\Entity\Address $address
     */
    public function removeAddress(\AppBundle\Entity\Address $address)
    {
        $this->addresses->removeElement($address);
    }

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

}

Now when you create a new User you can call the addAddresses method to add a new address.

Example:

$user = new User;
$address = new Address;
... // copy of first_name,last_name,company to the address object

$address->setLastName($user->getLastName()); // or whatever field you want
$user->addAddress($address);

$em->persist($user);
$em->flush();

Now you call the $user->getAddresses() method, and get all the addresses.


来源: stackexchange

问:
Open Firefox web console be default when it start?
I need to use Firefox web console a lot and I want every time I open Firefox, the Web Console panel will display automatically. Currently I have to press Ctrl + Shift + K to open it.

Is there any way to config the Firefox browser to make it work as I want? I prefer the native way (ie. changing configuration) rather than having install another plugins. I only need the webconsole, don't need the whole toolbox like firebug or something like that.

Thank you!

答:
I'm using a Debian derived Linux. Just installed Firefox Quantum (Firefox 57).

```<code>$ firefox --version
Mozilla Firefox 57.0
</code>```

The --devtools option seems to bring up Firefox with a Web console visible.

```<code>$ firefox --devtools
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm using a Debian derived Linux. Just installed Firefox Quantum (Firefox 57).

$ firefox --version
Mozilla Firefox 57.0

The --devtools option seems to bring up Firefox with a Web console visible.

$ firefox --devtools


问:
Crash copying NSArray into NSMutableArray
I am trying to copy NSArray into NSMutableArray using the below code, but it crashes with the uncaught exception error.

Actual Response Array Result:

```<code>dataroot = (
    1,
    2,
    3
);
</code>```

Code:

```<code>@interface MobileTestViewController ()
{
    NSMutableArray *mainMutArray ;
}
@end

@implementation MobileTestViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    mainMutArray = [[NSMutableArray alloc]init];
}

NSMutableArray *responseArray = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];

NSArray *dataarray = [responseArray valueForKey:@“dataroot”];
mainMutArray = [[NSMutableArray alloc] initWithArray: dataarray];

@end
</code>```

Error

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber isEqualToString:]: unrecognized selector sent to instance 0xb000000000000013'

How can I properly copy that array into a NSMutableArray.

答:
Go for object for key method..

```<code>NSArray *dataarray = [responseArray objectForKey:@“dataroot”];
</code>```

mainMutArray = [NSMutableArray arrayWithArray: dataarray];

Hope it works...

Body:
I am trying to copy NSArray into NSMutableArray using the below code, but it crashes with the uncaught exception error.

Actual Response Array Result:

dataroot = (
    1,
    2,
    3
);

Code:

@interface MobileTestViewController ()
{
    NSMutableArray *mainMutArray ;
}
@end

@implementation MobileTestViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    mainMutArray = [[NSMutableArray alloc]init];
}

NSMutableArray *responseArray = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];

NSArray *dataarray = [responseArray valueForKey:@“dataroot”];
mainMutArray = [[NSMutableArray alloc] initWithArray: dataarray];

@end

Error

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber isEqualToString:]: unrecognized selector sent to instance 0xb000000000000013'

How can I properly copy that array into a NSMutableArray.

Body:
Go for object for key method..

NSArray *dataarray = [responseArray objectForKey:@“dataroot”];

mainMutArray = [NSMutableArray arrayWithArray: dataarray];

Hope it works...


问:
Set Default date 1 year out from insert date
I currently have a table with the following layout:

```<code>create table x (
   insert_date date DEFAULT sysdate,
   last_update_date date,
   expiration_date date
)
</code>```

If I write to this table the value for insert_date will be obviously the exact time in which it was written. My Question is, is there a way to set a default value for expiration_date that is literally just "sysdate + 1 year" ?

答:
Instead of DEFAULT SYSDATE , you can write a BEFORE INSERT TRIGGER to take the passed date value or date of execution if it is null.

```<code>SET DEFINE OFF
CREATE OR REPLACE TRIGGER tr_x BEFORE  INSERT ON x
FOR EACH ROW
BEGIN
:new.insert_date := NVL(:new.insert_date,SYSDATE);
:new.expiration_date := :new.insert_date + INTERVAL '1' YEAR;
END;
/
</code>```

Body:
I currently have a table with the following layout:

create table x (
   insert_date date DEFAULT sysdate,
   last_update_date date,
   expiration_date date
)

If I write to this table the value for insert_date will be obviously the exact time in which it was written. My Question is, is there a way to set a default value for expiration_date that is literally just "sysdate + 1 year" ?

Body:
Instead of DEFAULT SYSDATE , you can write a BEFORE INSERT TRIGGER to take the passed date value or date of execution if it is null.

SET DEFINE OFF
CREATE OR REPLACE TRIGGER tr_x BEFORE  INSERT ON x
FOR EACH ROW
BEGIN
:new.insert_date := NVL(:new.insert_date,SYSDATE);
:new.expiration_date := :new.insert_date + INTERVAL '1' YEAR;
END;
/


问:
ASP.NET TempData persists between requests
I am using temp data as follow in my controllers - very simple, when there is a problem:

```<code>TempData("StatusMessage") = "You have no items set to Auto-Ship."
</code>```

Then on every page I have a user control as follows:

```<code><div class="error-container">
<%  If TempData.ContainsKey("ErrorMessage") Then%>
<script> $('div.error-container').show();</script>
<div class="msg-error"><p><%=TempData("ErrorMessage") %></p></div>
<% End If%>
<%  If TempData.ContainsKey("StatusMessage") Then%>
<script> $('div.error-container').show();</script>
<div class="msg-status"><p><%=TempData("StatusMessage")%></p></div>
<% End If%>
<ul></ul>
</div>
</code>```

Problem is when I do have an error added to tempdata it shows up properly on the first request but ALSO shows up again on the next request as well - which is obviously very confusing and not a desired behavior.

I am not using any IoC, I did see the post with the same problems when using that.

答:
The sole purpose of TempData is to persist until the next request. Stuff you do not want to persist until the next request should go into ViewData, instead.

Realistically, this means that TempData is only safe to use when redirecting. When not redirecting, the "next request" could be anything.

OwnerDisplayName: Max Fraser

ContentLicense: CC BY-SA 2.5

Body:
I am using temp data as follow in my controllers - very simple, when there is a problem:

TempData("StatusMessage") = "You have no items set to Auto-Ship."

Then on every page I have a user control as follows:

<%  If TempData.ContainsKey("ErrorMessage") Then%>

<%=TempData("ErrorMessage") %>

<% End If%>
<%  If TempData.ContainsKey("StatusMessage") Then%>

<%=TempData("StatusMessage")%>

<% End If%>

Problem is when I do have an error added to tempdata it shows up properly on the first request but ALSO shows up again on the next request as well - which is obviously very confusing and not a desired behavior.

I am not using any IoC, I did see the post with the same problems when using that.

OwnerDisplayName: Craig Stuntz


问:
Exception in thread "AWT-EventQueue-0" java.lang.StringIndexOutOfBoundsException: String index out of range: 97
Please help i have an error I just cannot figure out

Exception

```<code>Exception in thread "AWT-EventQueue-0" java.lang.StringIndexOutOfBoundsException: String index out of range: 97
    at java.lang.String.charAt(String.java:658)
    at Autocomplete$TrieAutocomplete.topMatches(Autocomplete.java:440)
</code>```

Code

```<code>      public Iterable<String> topMatches(String prefix, int k) {
        if (prefix == null) {
        throw new NullPointerException("Prefix must not be null");
        }
        Node.ReverseSubtreeMaxWeightComparator comp = new Node.ReverseSubtreeMaxWeightComparator();
        Node curr = myRoot;
        for (int i=0; i < prefix.length(); i++) {
           if (curr.children.containsKey(prefix.charAt(i))) {
              curr = curr.getChild(prefix.charAt(i));
           }
           else {
              return new ArrayList<String>();
           }
        }
        ArrayList<Node> wordsFound = new ArrayList<Node>();
        PriorityQueue queue = new PriorityQueue();
        double queuemax = myRoot.mySubtreeMaxWeight;
        while ((wordsFound.size() < k) || (wordsFound.get(k-1).mySubtreeMaxWeight > queuemax)) {
           queuemax = curr.mySubtreeMaxWeight;
           ArrayList<Node> children = new ArrayList<Node>();
           for (Character ch : curr.children.keySet()) {
            //The next line is line 440
              children.add(curr.getChild(prefix.charAt(ch)));
           }
           Collections.sort(children, comp);
           for (Node n : children) {
              queue.add(n);
           }
           if (curr.isWord == true) {
              wordsFound.add(curr);
              Collections.sort(wordsFound, comp);
           }
           curr = (Node)queue.poll();
           if (curr == null) {
              break;
           }
           queuemax = curr.mySubtreeMaxWeight;
        }
        ArrayList<String> wordList = new ArrayList<String>();
        for (int i=0; i < k; i++) {
           wordList.add(wordsFound.get(i).getWord());
        }
       return wordList;
    }
</code>```

答:
This means you don't have that char:

```<code>for (Character ch : curr.children.keySet()) {
            //The next line is line 440
              children.add(curr.getChild(prefix.charAt(ch)));
           }
</code>```

And the char is this:
97  a

So debug and check that prefix has the letter a in it

Body:
Please help i have an error I just cannot figure out

Exception

Exception in thread "AWT-EventQueue-0" java.lang.StringIndexOutOfBoundsException: String index out of range: 97
    at java.lang.String.charAt(String.java:658)
    at Autocomplete$TrieAutocomplete.topMatches(Autocomplete.java:440)

Code

      public Iterable<String> topMatches(String prefix, int k) {
        if (prefix == null) {
        throw new NullPointerException("Prefix must not be null");
        }
        Node.ReverseSubtreeMaxWeightComparator comp = new Node.ReverseSubtreeMaxWeightComparator();
        Node curr = myRoot;
        for (int i=0; i < prefix.length(); i++) {
           if (curr.children.containsKey(prefix.charAt(i))) {
              curr = curr.getChild(prefix.charAt(i));
           }
           else {
              return new ArrayList<String>();
           }
        }
        ArrayList<Node> wordsFound = new ArrayList<Node>();
        PriorityQueue queue = new PriorityQueue();
        double queuemax = myRoot.mySubtreeMaxWeight;
        while ((wordsFound.size() < k) || (wordsFound.get(k-1).mySubtreeMaxWeight > queuemax)) {
           queuemax = curr.mySubtreeMaxWeight;
           ArrayList<Node> children = new ArrayList<Node>();
           for (Character ch : curr.children.keySet()) {
            //The next line is line 440
              children.add(curr.getChild(prefix.charAt(ch)));
           }
           Collections.sort(children, comp);
           for (Node n : children) {
              queue.add(n);
           }
           if (curr.isWord == true) {
              wordsFound.add(curr);
              Collections.sort(wordsFound, comp);
           }
           curr = (Node)queue.poll();
           if (curr == null) {
              break;
           }
           queuemax = curr.mySubtreeMaxWeight;
        }
        ArrayList<String> wordList = new ArrayList<String>();
        for (int i=0; i < k; i++) {
           wordList.add(wordsFound.get(i).getWord());
        }
       return wordList;
    }

Body:
This means you don't have that char:

for (Character ch : curr.children.keySet()) {
            //The next line is line 440
              children.add(curr.getChild(prefix.charAt(ch)));
           }

And the char is this:
97  a

So debug and check that prefix has the letter a in it


问:
Updating object attributes from within module run in multiprocessor process
I am relatively new to python and definitely new to multiprocessing. I'm following this question/answer for the structure of my multiprocessing, but in def func_A, I'm calling a module that passes a class object as one of the arguments. In the module, I change an object attribute that I would like the main program to see and update the user with the object attribute value. The child processes run for very long times, so I need the main program to provide updates as they run.

My suspicion is that I'm not understanding namespace/object scoping or something similar, but from what I've read, passing an object (an instance of a class?) to a module as an argument passes a reference to the object and not a copy. I would have thought this meant that changing the attributes of the object in the child process/module would have changed the attributes in the main program object (since they're the same object). Or am I confusing things?

The code for my main program:

```<code># MainProgram.py
import multiprocessing as mp
import time
from time import sleep
import sys
from datetime import datetime
import myModule

MYOBJECTNAMES = ['name1','name2']

class myClass:
  def __init__(self, name):
    self.name = name
    self.value = 0

myObjects = []
for n in MYOBJECTNAMES:
  myObjects.append(myClass(n))

def func_A(process_number, queue):
  start = datetime.now()
  print("Process {} (object: {}) started at {}".format(process_number, myObjects[process_number].name, start))
  myModule.Eval(myObjects[process_number])
  sys.stdout.flush()

def multiproc_master():
  queue = mp.Queue()
  proceed = mp.Event()

  processes = [mp.Process(target=func_A, args=(x, queue)) for x in range(len(myObjects))]
  for p in processes:
    p.start()

  for i in range(100):
    for o in myObjects:
      print("In main: Value of {} is {}".format(o.name, o.value))
    sleep(10)

  for p in processes:
    p.join()

if __name__ == '__main__':
  split_jobs = multiproc_master()
  print(split_jobs)
</code>```

The code for my module program:

```<code># myModule.py
from time import sleep

def Eval(myObject):

  for i in range(100):
    myObject.value += 1
    print("In module: Value of {} is {}".format(myObject.name, myObject.value))
    sleep(5)
</code>```

答:
That question/answer you linked to probably was probably a poor choice to use as a template, as it's doing many things that your code doesn't require (much less use).

I think your biggest misconception about how multiprocessing works is thinking that all the code is running in the same address-space. The main task runs in its own, and there are separate ones for each subtask. The way your code is written, each of them will end up with its own separate myObjects list. That's why the main task doesn't see any of the changes made by any of the other tasks.

While there are ways share objects using the multiprocessing module, doing so often introduces significant overhead because keeping it or them all in-sync between all the processes requires lots of things happening "under the covers" to make seem like they're shared (which is what is really going on since they can't actually be because of having separate address-spaces). This overhead frequently completely cancels out any speed gained by parallel-processing.

As stated in the documentation: "when doing concurrent programming it is usually best to avoid using shared state as far as possible".

Body:
I am relatively new to python and definitely new to multiprocessing. I'm following this question/answer for the structure of my multiprocessing, but in def func_A, I'm calling a module that passes a class object as one of the arguments. In the module, I change an object attribute that I would like the main program to see and update the user with the object attribute value. The child processes run for very long times, so I need the main program to provide updates as they run.

My suspicion is that I'm not understanding namespace/object scoping or something similar, but from what I've read, passing an object (an instance of a class?) to a module as an argument passes a reference to the object and not a copy. I would have thought this meant that changing the attributes of the object in the child process/module would have changed the attributes in the main program object (since they're the same object). Or am I confusing things?

The code for my main program:

# MainProgram.py
import multiprocessing as mp
import time
from time import sleep
import sys
from datetime import datetime
import myModule

MYOBJECTNAMES = ['name1','name2']

class myClass:
  def __init__(self, name):
    self.name = name
    self.value = 0

myObjects = []
for n in MYOBJECTNAMES:
  myObjects.append(myClass(n))

def func_A(process_number, queue):
  start = datetime.now()
  print("Process {} (object: {}) started at {}".format(process_number, myObjects[process_number].name, start))
  myModule.Eval(myObjects[process_number])
  sys.stdout.flush()

def multiproc_master():
  queue = mp.Queue()
  proceed = mp.Event()

  processes = [mp.Process(target=func_A, args=(x, queue)) for x in range(len(myObjects))]
  for p in processes:
    p.start()

  for i in range(100):
    for o in myObjects:
      print("In main: Value of {} is {}".format(o.name, o.value))
    sleep(10)

  for p in processes:
    p.join()

if __name__ == '__main__':
  split_jobs = multiproc_master()
  print(split_jobs)

The code for my module program:

# myModule.py
from time import sleep

def Eval(myObject):

  for i in range(100):
    myObject.value += 1
    print("In module: Value of {} is {}".format(myObject.name, myObject.value))
    sleep(5)


问:
Error with Jenkins Pipeline spinning up multiple docker containers for cucumber tests, one feature file per container
We have been stuck with this problem for a week now though we have been working with pipelines for past few months.  Our goal is to spin-up as many containers as many feature files in our cucumber test suite and run those tests in parallel (one per container). Here is the error we are getting with the pipeline code below:

java.lang.UnsupportedOperationException: Calling public static
  java.util.List
  org.codehaus.groovy.runtime.DefaultGroovyMethods.each(java.util.List,groovy.lang.Closure)
  on a CPS-transformed closure is not yet supported (JENKINS-26481);
  encapsulate in a @NonCPS method, or use Java-style loops

pipeline code:

```<code>def cucumberTestImage
pipeline {
    agent any
    options {
         echo "options stuff"
    }

  stages {
    stage('Build & Deploy'){
            steps {
        parallel (
                SPA: {
            script {
                  echo "deploying SPA app"
                }
              }
            }
                    echo 'SPA JOB COMPLETED!!'
          },
          Tests: {
            script {
              }
              //building docker image name cucumberTestImage

            }
          }
        )
      }
    }

     stage('Test') {
     steps {
         script {
            def tests = [:]
            getFeatures().each {stage -> tests[stage] = {
                    cucumberTestImage.inside{sh "echo ${stage}"}
                }}
            parallel tests;
        }
     }
    }

  }
}

@NonCPS
def getFeatures() {
            return sh(script: 'cd testfolder && find features -type f -name \'*.feature\'', returnStdout: true).tokenize()
    }
</code>```

答:
The error seems to indicate that this block is causing the problem:

```<code>getFeatures().each {stage -> tests[stage] = {
                    cucumberTestImage.inside{sh "echo ${stage}"}
                }}
</code>```

It seems that the each method is not support in the jenkins version you are using, you can change it to the following:

```<code>def features = getFeatures()
for(def stage: features) {
   tests[stage] = {cucumberTestImage.inside{sh "echo ${stage}"}}}
}
</code>```

Alternatively, you may want to upgrade jenkins as the stated jenkins issue JENKINS-26481 is resolved.

ContentLicense: CC BY-SA 4.0

Body:
We have been stuck with this problem for a week now though we have been working with pipelines for past few months.  Our goal is to spin-up as many containers as many feature files in our cucumber test suite and run those tests in parallel (one per container). Here is the error we are getting with the pipeline code below:

java.lang.UnsupportedOperationException: Calling public static
  java.util.List
  org.codehaus.groovy.runtime.DefaultGroovyMethods.each(java.util.List,groovy.lang.Closure)
  on a CPS-transformed closure is not yet supported (JENKINS-26481);
  encapsulate in a @NonCPS method, or use Java-style loops

pipeline code:

def cucumberTestImage
pipeline {
    agent any
    options {
         echo "options stuff"
    }

  stages {
    stage('Build & Deploy'){
            steps {
        parallel (
                SPA: {
            script {
                  echo "deploying SPA app"
                }
              }
            }
                    echo 'SPA JOB COMPLETED!!'
          },
          Tests: {
            script {
              }
              //building docker image name cucumberTestImage

            }
          }
        )
      }
    }

     stage('Test') {
     steps {
         script {
            def tests = [:]
            getFeatures().each {stage -> tests[stage] = {
                    cucumberTestImage.inside{sh "echo ${stage}"}
                }}
            parallel tests;
        }
     }
    }

  }
}

@NonCPS
def getFeatures() {
            return sh(script: 'cd testfolder && find features -type f -name \'*.feature\'', returnStdout: true).tokenize()
    }

Body:
The error seems to indicate that this block is causing the problem:

getFeatures().each {stage -> tests[stage] = {
                    cucumberTestImage.inside{sh "echo ${stage}"}
                }}

It seems that the each method is not support in the jenkins version you are using, you can change it to the following:

def features = getFeatures()
for(def stage: features) {
   tests[stage] = {cucumberTestImage.inside{sh "echo ${stage}"}}}
}

Alternatively, you may want to upgrade jenkins as the stated jenkins issue JENKINS-26481 is resolved.


问:
2 retrofit calls 1 adapter
I call API for popular Movies (I need poster and title) and popular TV Shows (poster and title). I need to do it with 2 different asynchronous calls, put data into List<PopularMovieAdapterObject> podaci and setAdapter. Adapter is for GridView, so basically I need a mix of popular movies and popular tv shows in one gridview. This is my code:

```<code>       PopularMoviesFromAPI popularMoviesFromAPI = new PopularMoviesFromAPI();

   popularMoviesFromAPI.getPopularMoviesInfo(new PopularMoviesFromAPI.GenericCallback() {
       @Override
       public void success(@NonNull List<String> posterURL, List<String> movieTVName) {
           List<PopularMovieAdapterObject> podaci = new ArrayList<>();
           for(int i=0; i<(posterURL.size()/2); i++){
               podaci.add(new PopularMovieAdapterObject("https://image.tmdb.org/t/p/w500" + posterURL.get(i), movieTVName.get(i)));
           }

           PopularMoviesAdapter popularMoviesAdapter = new PopularMoviesAdapter(getContext(), R.layout.popular_movies_item, podaci);

           popularMoviesGridView.setAdapter(popularMoviesAdapter);
       }

       @Override
       public void failure(@NonNull Throwable throwable) {

       }
   });

   popularMoviesFromAPI.getPopularTVShowsInfo(new PopularMoviesFromAPI.GenericCallback() {
       @Override
       public void success(@NonNull List<String> posterURL, List<String> movieTVName) {
           List<PopularMovieAdapterObject> podaci = new ArrayList<>();
           for(int i=0; i<(posterURL.size()/2); i++){
               podaci.add(new PopularMovieAdapterObject("https://image.tmdb.org/t/p/w500" + posterURL.get(i), movieTVName.get(i)));
           }

           PopularMoviesAdapter popularMoviesAdapter = new PopularMoviesAdapter(getContext(), R.layout.popular_movies_item, podaci);

           popularMoviesGridView.setAdapter(popularMoviesAdapter);
       }

       @Override
       public void failure(@NonNull Throwable throwable) {

       }
   });
</code>```

Right now I can either put movies OR tv shows in GridView.

答:
That is happening because you are setting the adapter twice.

Try:

not passing the List (podaci) as an argument to your adapter class;

in the constructor of your adapter, set the list as an empty list initially;

create a method that sets the list of adapter by adding the podaci elements one by one at the end to the existing list.

Title: 2 retrofit calls 1 adapter

Body:
I call API for popular Movies (I need poster and title) and popular TV Shows (poster and title). I need to do it with 2 different asynchronous calls, put data into List<PopularMovieAdapterObject> podaci and setAdapter. Adapter is for GridView, so basically I need a mix of popular movies and popular tv shows in one gridview. This is my code:

       PopularMoviesFromAPI popularMoviesFromAPI = new PopularMoviesFromAPI();

   popularMoviesFromAPI.getPopularMoviesInfo(new PopularMoviesFromAPI.GenericCallback() {
       @Override
       public void success(@NonNull List<String> posterURL, List<String> movieTVName) {
           List<PopularMovieAdapterObject> podaci = new ArrayList<>();
           for(int i=0; i<(posterURL.size()/2); i++){
               podaci.add(new PopularMovieAdapterObject("https://image.tmdb.org/t/p/w500" + posterURL.get(i), movieTVName.get(i)));
           }

           PopularMoviesAdapter popularMoviesAdapter = new PopularMoviesAdapter(getContext(), R.layout.popular_movies_item, podaci);

           popularMoviesGridView.setAdapter(popularMoviesAdapter);
       }

       @Override
       public void failure(@NonNull Throwable throwable) {

       }
   });

   popularMoviesFromAPI.getPopularTVShowsInfo(new PopularMoviesFromAPI.GenericCallback() {
       @Override
       public void success(@NonNull List<String> posterURL, List<String> movieTVName) {
           List<PopularMovieAdapterObject> podaci = new ArrayList<>();
           for(int i=0; i<(posterURL.size()/2); i++){
               podaci.add(new PopularMovieAdapterObject("https://image.tmdb.org/t/p/w500" + posterURL.get(i), movieTVName.get(i)));
           }

           PopularMoviesAdapter popularMoviesAdapter = new PopularMoviesAdapter(getContext(), R.layout.popular_movies_item, podaci);

           popularMoviesGridView.setAdapter(popularMoviesAdapter);
       }

       @Override
       public void failure(@NonNull Throwable throwable) {

       }
   });

Right now I can either put movies OR tv shows in GridView.


问:
Convert a string to a matrix in C#
I have a string like this:

```<code> people="Prof. Dr. Bill Gates;bill@microsoft.com;Microsoft Corporation!
 Dr. Elon Musk;elon@tesla.com;Tesle Inc.!
 Dr.Mehdi Karakoç;mehdi@tetra.com.tr;Tetra Yazılım!";
</code>```

And I want to convert this data to 3x3 matrix like below:

```<code>Prof. Dr. Bill Gates    bill@microsoft.com  Microsoft Corporation
Assoc. Dr. Elon Musk    elon@teslacar.com   Tesle Inc.
Dr. Mehmet Mehdi Kara   mehdi@tetra.com.tr  Tetra Yazılım
</code>```

Each '!' is an 'End of Line' and ';' is the end of each elements
How can I do this in a simple way?

答:
use str.split();</p>

```<code>var people = @"Prof. Dr. Bill Gates;bill@microsoft.com;Microsoft Corporation!Dr.Elon Musk; elon @tesla.com; Tesle Inc.!Dr.Mehdi Karakoç; mehdi @tetra.com.tr; Tetra Yazılım!";

        var person = people.Split('!');

        foreach (var item in person)
        {
            var data = item.Split(';');

            var name = data[0];
            var email = data[1];
            var company = data[2];

            --> Here Add Itens on your Matriz or List

        }
</code>```

Title: Convert a string to a matrix in C#

Body:
I have a string like this:

 people="Prof. Dr. Bill Gates;bill@microsoft.com;Microsoft Corporation!
 Dr. Elon Musk;elon@tesla.com;Tesle Inc.!
 Dr.Mehdi Karakoç;mehdi@tetra.com.tr;Tetra Yazılım!";

And I want to convert this data to 3x3 matrix like below:

Prof. Dr. Bill Gates    bill@microsoft.com  Microsoft Corporation
Assoc. Dr. Elon Musk    elon@teslacar.com   Tesle Inc.
Dr. Mehmet Mehdi Kara   mehdi@tetra.com.tr  Tetra Yazılım

Each '!' is an 'End of Line' and ';' is the end of each elements
How can I do this in a simple way?

Body:
use str.split();

var people = @"Prof. Dr. Bill Gates;bill@microsoft.com;Microsoft Corporation!Dr.Elon Musk; elon @tesla.com; Tesle Inc.!Dr.Mehdi Karakoç; mehdi @tetra.com.tr; Tetra Yazılım!";

        var person = people.Split('!');

        foreach (var item in person)
        {
            var data = item.Split(';');

            var name = data[0];
            var email = data[1];
            var company = data[2];

            --> Here Add Itens on your Matriz or List

        }


问:
HTTPS via Secure Gateway
I'm trying to basically make one of the Watson services available on-premise by using the Secure Gateway. It's working fine with basic HTTP traffic, but I'm in doubt how to configure HTTPS traffic of for instance the Watson Conversation service on API endpoint "https://gateway.watsonplatform.net/conversation/api/v1"

I've configured a Destination in the service to:
gateway.watsonplatform.net, destination port 443 and client listening port 6554 - protocol HTTPS.
Connecting via Postman simply yields the following in my client, though using standard basic auth with the credentials from the service in Bluemix:

```<code>[2017-08-26 12:51:01.626] [INFO] (Client ID LilwbDOdR61_4Am) Connection #1 to gateway.watsonplatform.net:443 was closed
</code>```

I also tried to configure the protocol to be TCP, but this yields the same result. Any hints?

With loglevel TRACE I get:
[2017-09-09 15:05:06.481] [DEBUG] (Client ID LilwbDOdR61_PlY) Sending a reverse destination connection to the server
[2017-09-09 15:05:06.833] [TRACE] (Client ID LilwbDOdR61_PlY) Connection #1 received data: 361 bytes
[2017-09-09 15:05:07.285] [ERROR] (Client ID LilwbDOdR61_PlY) Connection #1 to destination gateway.watsonplatform.net:443 had error: Error: write after end
[2017-09-09 15:05:07.289] [DEBUG] (Client ID LilwbDOdR61_PlY) Connection #1 to gateway.watsonplatform.net:443 has ended
[2017-09-09 15:05:07.289] [INFO] (Client ID LilwbDOdR61_PlY) Connection #1 to gateway.watsonplatform.net:443 was closed
[2017-09-09 15:05:07.290] [DEBUG] (Client ID LilwbDOdR61_PlY) Closing connection and removing from array
[2017-09-09 15:05:07.291] [DEBUG] (Client ID LilwbDOdR61_PlY) clearConnectionArray: 0

答:
Thomas, I've managed to make the connection to conversation service using secure gateway.

For the User/Application protocol, use TCP

For destination side authentication, select "destination side", there is no need to upload any certificate.

The configuration screen will look like this:

And finally, the request must be made using http and not https, this is because you left the secure connection to be managed by the secure gateway server.

You can test the request like this:curl -X POST 'http://localhost:10001/conversation/api/v1/workspaces/<YOUR_WORKSPACE_ID>/message/?version=2017-05-26' -H 'authorization: Basic <ENCODED_CREDENTIALS>' -H 'cache-control: no-cache' -H 'content-type: application/json' -d '{"input": {"text": "hello"}}'

Title: HTTPS via Secure Gateway

Body:
I'm trying to basically make one of the Watson services available on-premise by using the Secure Gateway. It's working fine with basic HTTP traffic, but I'm in doubt how to configure HTTPS traffic of for instance the Watson Conversation service on API endpoint "https://gateway.watsonplatform.net/conversation/api/v1"

I've configured a Destination in the service to:
gateway.watsonplatform.net, destination port 443 and client listening port 6554 - protocol HTTPS.
Connecting via Postman simply yields the following in my client, though using standard basic auth with the credentials from the service in Bluemix:

[2017-08-26 12:51:01.626] [INFO] (Client ID LilwbDOdR61_4Am) Connection #1 to gateway.watsonplatform.net:443 was closed

I also tried to configure the protocol to be TCP, but this yields the same result. Any hints?

With loglevel TRACE I get:
[2017-09-09 15:05:06.481] [DEBUG] (Client ID LilwbDOdR61_PlY) Sending a reverse destination connection to the server
[2017-09-09 15:05:06.833] [TRACE] (Client ID LilwbDOdR61_PlY) Connection #1 received data: 361 bytes
[2017-09-09 15:05:07.285] [ERROR] (Client ID LilwbDOdR61_PlY) Connection #1 to destination gateway.watsonplatform.net:443 had error: Error: write after end
[2017-09-09 15:05:07.289] [DEBUG] (Client ID LilwbDOdR61_PlY) Connection #1 to gateway.watsonplatform.net:443 has ended
[2017-09-09 15:05:07.289] [INFO] (Client ID LilwbDOdR61_PlY) Connection #1 to gateway.watsonplatform.net:443 was closed
[2017-09-09 15:05:07.290] [DEBUG] (Client ID LilwbDOdR61_PlY) Closing connection and removing from array
[2017-09-09 15:05:07.291] [DEBUG] (Client ID LilwbDOdR61_PlY) clearConnectionArray: 0


问:
How to create custom google maps style in Android app (Java)
I would like to develop an Android application that contains a customized map ( I guess I have to use the Google API ) .

What I would do is to create an interactive map as that of "Ingress" or "Pokemon Go" , I wondered if this could be done simply by superimposing a custom layout to the existing one or if there are alternative methods.

Currently I have only found this document but refers to the web version , there is a specific way to Android or do I create a webview ?

https://developers.google.com/maps/documentation/javascript/styling

https://developers.google.com/maps/documentation/javascript/tutorials/styling-the-base-map

答: Now Google Maps styles available for Android too. </p>


问:
AcceptEx without WSAIoctl
Is there any difference between using AcceptEx direct call or using function pointer obtained by WSAIoctl.

MSDN doesn't fully covers this question regarding performance issue and other problems that can be faced using AcceptEx as direct call.

And other question is:
If I have for example 4 listening sockets in my program, do I need to call WSAIoctl for each listening socket and of course store function pointer for every socket? Or it is enough to call it once for any socket and than use with other ones.

Thank in advance.

答:
WSAIoctl. It's an extension provider that you use for new functions/additions to the winsock functionality, each new windows version usually add a couple of new extensions.

AcceptEx function pointer:
Using the AcceptEx directly binds the application to the Microsoft provider with the need for MSWsock.dll. As for correctness you probably should do it the msdn way and use the functions through the extension.

Just set it up once and use as you would have with the MSWsock-AcceptEx (you will still be using the same thing)

As for speed/performance I would suggest concentrating on the pooling of sockets instead.

Edit:
Should clarify the (msdn) reason for separating - Extensions are Microsoft specific functions that other providers should not be forced to implement.

Title: AcceptEx without WSAIoctl


问:
What is the value of an report parameter which allows multiple value, no null vals & gets its value from a query when you don't check any checkbox?
I got an ssrs report which has a parameter @param which is configured to allows multiple value, no null values and gets its value from a query.

I want to be able to test the rdl's sql query by putting the report's parameter value in a declared variable in sql server

```<code>declare @param type = value
</code>```

The question is what is the type and value of this variable when you don't tick any checkbox in the actual report.

答:
If you don't choose a value from your list, your report will not run so how can you test it?

Your parameter is based on a query, the Value field you chose when you set the parameter up will be value or values passed to the query with the same datatype, so if you pass a list of integers then SSRS will pass integers to your query

.. however...

Let's say you had a list of items with ID's that you use as your parmeters values and it looks like this

```<code>myID  myDescription
1     Apples
2     Oranges
3     Pears
4     Carrots
5     Onions
</code>```

and your user chose 'Apples' and 'Pears', then 1 and 3 would be passed to the query.

If your dataset query is something like

```<code>SELECT * FROM myTable WHERE myID IN (@myParameter)
</code>```

and , assuming your query is directly in your dataset (and not a stored proc) then SSRS will automatically convert the passed in values to a comma delimited list so the query executed will look like this.

```<code>SELECT * FROM myTable WHERE myID IN (1, 3)
</code>```

What this means is that you can only really test the query with a single value unless you hardcode your test values in place of the @myParameter

Note: You should not declare @myParameter in your dataset query.

Body:
I got an ssrs report which has a parameter @param which is configured to allows multiple value, no null values and gets its value from a query.

I want to be able to test the rdl's sql query by putting the report's parameter value in a declared variable in sql server

declare @param type = value

The question is what is the type and value of this variable when you don't tick any checkbox in the actual report.

Body:
If you don't choose a value from your list, your report will not run so how can you test it?

Your parameter is based on a query, the Value field you chose when you set the parameter up will be value or values passed to the query with the same datatype, so if you pass a list of integers then SSRS will pass integers to your query

.. however...

Let's say you had a list of items with ID's that you use as your parmeters values and it looks like this

myID  myDescription
1     Apples
2     Oranges
3     Pears
4     Carrots
5     Onions

and your user chose 'Apples' and 'Pears', then 1 and 3 would be passed to the query.

If your dataset query is something like

SELECT * FROM myTable WHERE myID IN (@myParameter)

and , assuming your query is directly in your dataset (and not a stored proc) then SSRS will automatically convert the passed in values to a comma delimited list so the query executed will look like this.

SELECT * FROM myTable WHERE myID IN (1, 3)

What this means is that you can only really test the query with a single value unless you hardcode your test values in place of the @myParameter

Note: You should not declare @myParameter in your dataset query.


问:
Angular Material button is not rendering
I have followed steps to install material design, but when I add button I don't get the MD style.

```<code><button mat-button [matMenuTriggerFor]="menu">Menu</button>
    <mat-menu #menu="matMenu">
      <button mat-menu-item>Item 1</button>
      <button mat-menu-item>Item 2</button>
</mat-menu>
</code>```

Package.json file

```<code>{
  "name": "apimap",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^5.0.2",
    "@angular/cdk": "github:angular/cdk-builds",
    "@angular/common": "^5.0.0",
    "@angular/compiler": "^5.0.0",
    "@angular/core": "^5.0.0",
    "@angular/forms": "^5.0.0",
    "@angular/http": "^5.0.0",
    "@angular/material": "github:angular/material2-builds",
    "@angular/platform-browser": "^5.0.0",
    "@angular/platform-browser-dynamic": "^5.0.0",
    "@angular/router": "^5.0.0",
    "core-js": "^2.4.1",
    "hammerjs": "^2.0.8",
    "rxjs": "^5.5.2",
    "zone.js": "^0.8.14"
  },
  "devDependencies": {
    "@angular/cli": "1.5.2",
    "@angular/compiler-cli": "^5.0.0",
    "@angular/language-service": "^5.0.0",
    "@types/jasmine": "~2.5.53",
    "@types/jasminewd2": "~2.0.2",
    "@types/node": "~6.0.60",
    "codelyzer": "~3.2.0",
    "jasmine-core": "~2.6.2",
    "jasmine-spec-reporter": "~4.1.0",
    "karma": "~1.7.0",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.2",
    "ts-node": "~3.2.0",
    "tslint": "~5.7.0",
    "typescript": "~2.4.2"
  }
}
</code>```

I have also added css theme + material design in index.html
Added MD modules in app.mudule.ts but I get a basic html button style, only the mat-menu-item are in MD style.

Update: A screen capture of the button:

when I click on it

答: Just for confirmation, have you added MatButtonModule in appModule imports? Can't add it as comment because of my reputation :P </p>

Body:
I have followed steps to install material design, but when I add button I don't get the MD style.

<button mat-button [matMenuTriggerFor]="menu">Menu</button>
    <mat-menu #menu="matMenu">
      <button mat-menu-item>Item 1</button>
      <button mat-menu-item>Item 2</button>
</mat-menu>

Package.json file

{
  "name": "apimap",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^5.0.2",
    "@angular/cdk": "github:angular/cdk-builds",
    "@angular/common": "^5.0.0",
    "@angular/compiler": "^5.0.0",
    "@angular/core": "^5.0.0",
    "@angular/forms": "^5.0.0",
    "@angular/http": "^5.0.0",
    "@angular/material": "github:angular/material2-builds",
    "@angular/platform-browser": "^5.0.0",
    "@angular/platform-browser-dynamic": "^5.0.0",
    "@angular/router": "^5.0.0",
    "core-js": "^2.4.1",
    "hammerjs": "^2.0.8",
    "rxjs": "^5.5.2",
    "zone.js": "^0.8.14"
  },
  "devDependencies": {
    "@angular/cli": "1.5.2",
    "@angular/compiler-cli": "^5.0.0",
    "@angular/language-service": "^5.0.0",
    "@types/jasmine": "~2.5.53",
    "@types/jasminewd2": "~2.0.2",
    "@types/node": "~6.0.60",
    "codelyzer": "~3.2.0",
    "jasmine-core": "~2.6.2",
    "jasmine-spec-reporter": "~4.1.0",
    "karma": "~1.7.0",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.2",
    "ts-node": "~3.2.0",
    "tslint": "~5.7.0",
    "typescript": "~2.4.2"
  }
}

I have also added css theme + material design in index.html
Added MD modules in app.mudule.ts but I get a basic html button style, only the mat-menu-item are in MD style.

Update: A screen capture of the button:

when I click on it


问:
How can this structure have sizeof == 0?
There is an old post asking for a construct for which sizeof would return 0. There are some high score answers from high reputation users saying that by the standard no type or variable can have sizeof 0. And I agree 100% with that.

However there is this new answer which presents this solution:

```<code>struct ZeroMemory {
    int *a[0];
};
</code>```

I was just about to down-vote and comment on it, but time spent here taught me to check even the things that I am 100% sure on. So... to my surprise both gcc and clang show the same results: sizeof(ZeroMemory) == 0. Even more, sizeof a variable is 0:

```<code>ZeroMemory z{};
static_assert(sizeof(z) == 0); // Awkward...
</code>```

Whaaaat...?

Godbolt link

How is this possible?

答:
Before C was standardized, many compilers would have had no difficulty handling zero-size types as long as code never tried to subtract one pointer to a zero-size type from another.  Such types were useful, and supporting them was easier and cheaper than forbidding them.  Other compilers decided to forbid such types, however, and some static-assertion code may have relied upon the fact that they would squawk if code tried to create a zero-sized array.  The authors of the Standard were faced with a choice:

Allow compilers to silently accept zero-sized array declarations, even
in cases where the purpose of such declarations would be to trigger a
diagnostic and abort compilation, and require that all compilers accept
such declarations (though not necessarily silently) as producing zero-
sized objects.

Allow compilers to silently accept zero-sized array declarations, even
in cases where the purpose of such declarations would be to trigger a
diagnostic and abort compilation, and allow compilers encountering such
declarations to either abort compilation or continue it at their leisure.

Require that implementations issue a diagnostic if code declares a
zero-sized array, but then allow implementations to either abort
compilation or continue it (with whatever semantics they see fit) at
their leisure.

The authors of the Standard opted for #3.  Consequently, zero-sized array declarations are regarded by the Standard "extension", even though such constructs were widely supported before the Standard forbade them.

The C++ Standard allows for the existence of empty objects, but in an effort to allow the addresses of empty objects to be usable as tokens it mandates that they have a minimum size of 1.  For an object that has no members to have a size of 0 would thus violate the Standard.  If an object contains zero-sized members, however, the C++ Standard imposes no requirements about how it is processed beyond the fact that a program containing such a declaration must trigger a diagnostic.  Since most code that uses such declarations expects the resulting objects to have a size of zero, the most useful behavior for compilers receiving such code is to treat them that way.

Body:
There is an old post asking for a construct for which sizeof would return 0. There are some high score answers from high reputation users saying that by the standard no type or variable can have sizeof 0. And I agree 100% with that.

However there is this new answer which presents this solution:

struct ZeroMemory {
    int *a[0];
};

I was just about to down-vote and comment on it, but time spent here taught me to check even the things that I am 100% sure on. So... to my surprise both gcc and clang show the same results: sizeof(ZeroMemory) == 0. Even more, sizeof a variable is 0:

ZeroMemory z{};
static_assert(sizeof(z) == 0); // Awkward...

Whaaaat...?

Godbolt link

How is this possible?


问:
When should public variables be used?
Using the android developer page for ScanResult, https://developer.android.com/reference/android/net/wifi/ScanResult.html, I noticed that they have public variables BSSID, SSID, capabilities, etc. I thought this was weird, as using getters/setters over public variables is the java norm. Is there a broad, rule-based reason why public variables are sometimes used over getters/setters? </p>

答:
In this example you mentioned, they are really public variables and that is bad practice. Strange why they made them public. This breaks encapsulation - the principle of hiding data in order to be able to control precisely who and when the data gets set.

But if you think, what's the point in making members private and allowing just dumb getters and setters? It's the same as setting them directly.

And the answer is this:
1. If you make the fields public, it would be impossible to change the API of your classes and if you decide later you want to put some logging or security constraints in the getters or setters, you won't be able to make those fields private without breaking people's code.
2. Getters and setters allow for overriding in child classes.
and many other advantages.

So in conclusion - it is stupid to make these fields public. Not expecting that from Google engineers. Also they made the class extend Object (which is by default the case in java)

Title: When should public variables be used?