问:
Creating new entity associate with an existing entity in EntityType field
I'm working on Symfony 3 with Doctrine. In my project for a music school, I have 3 entities (Morceau (translation of Tune), Eleve (translation of Student), Instrument). With one form, I would like to create new Morceau associate with new Eleve associate with an existing Instrument.

Now, I have a problem to associate Eleve with an existing Instrument which is an EntityType (list of all the music instruments):

Catchable Fatal Error: Object of class AppBundle\Entity\Instrument could not be converted to string

The thing is that I don't want to create a new Instrument id.

The associations are: Morceau (with @ORM/ManyToOne $eleve), Eleve(@ORM/ManyToOne $instrument), Instrument (with $id and $nomInstrument).

My Forms:

MorceauType:

```<code>public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('titre', TextType::class)
            ->add('compositeur', TextType::class)
            ->add('formation', TextType::class)
            ->add('duree', IntegerType::class)
            ->add('materiel', TextType::class)
            ->add('accompagnementPiano', ChoiceType::class,
                array('choices' => array('Oui' => True, 'Non' => False)))
            ->add('eleve', EleveType::class)
            ->add('save', SubmitType::class)    ;
}
</code>```

EleveType:

```<code>public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('nomEleve', TextType::class)
            ->add('prenomEleve', TextType::class)
            ->add('instrument', InstrumentType::class)
                                ;
}
</code>```

InstrumentType:

```<code>public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('nomInstrument', EntityType::class, array('class' => 'AppBundle:Instrument',
                                                                        'choice_label' => 'nomInstrument'))
    ;
}
</code>```

My Controller:

```<code>public function addTuneAction(Request $request)
{

    // On récupère le formulaire Morceaux
    $morceau = new Morceau();

    $form = $this->createForm(MorceauType::class, $morceau);

    //On vérifie les valeurs
    if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($morceau);
        $em->flush();

        $request->getSession()->getFlashBag()->add('notice', 'Morceau enregistré');

        return $this->redirectToRoute('index');
    }

    // on retourne la vue
    return $this->render('snippets/addTune.html.twig', array('morceau' => $form->createView()));
}
</code>```

Many thanks !

Here's my entities:

Morceau:

```<code>/**
 * Morceau
 *
 * @ORM\Table(name="Morceau")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\MorceauRepository")
 */
class Morceau
{
/**
 * @var int
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

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

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

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

/**
 * @var int
 *
 * @ORM\Column(name="duree", type="smallint")
 */
private $duree;

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

/**
 * @var bool
 *
 * @ORM\Column(name="accompagnementPiano", type="boolean")
 */
private $accompagnementPiano;

/**
*
* @ORM\ManyToOne(targetEntity="Eleve", cascade={"persist"})
* @ORM\JoinColumn(name="eleve_id", referencedColumnName="id")
*/
private $eleve;

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

/**
 * Set titre
 *
 * @param string $titre
 *
 * @return morceau
 */
public function setTitre($titre)
{
    $this->titre = $titre;

    return $this;
}

/**
 * Get titre
 *
 * @return string
 */
public function getTitre()
{
    return $this->titre;
}

/**
 * Set compositeur
 *
 * @param string $compositeur
 *
 * @return morceau
 */
public function setCompositeur($compositeur)
{
    $this->compositeur = $compositeur;

    return $this;
}

/**
 * Get compositeur
 *
 * @return string
 */
public function getCompositeur()
{
    return $this->compositeur;
}

/**
 * Set formation
 *
 * @param string $formation
 *
 * @return morceau
 */
public function setFormation($formation)
{
    $this->formation = $formation;

    return $this;
}

/**
 * Get formation
 *
 * @return string
 */
public function getFormation()
{
    return $this->formation;
}

/**
 * Set duree
 *
 * @param integer $duree
 *
 * @return morceau
 */
public function setDuree($duree)
{
    $this->duree = $duree;

    return $this;
}

/**
 * Get duree
 *
 * @return int
 */
public function getDuree()
{
    return $this->duree;
}

/**
 * Set materiel
 *
 * @param string $materiel
 *
 * @return morceau
 */
public function setMateriel($materiel)
{
    $this->materiel = $materiel;

    return $this;
}

/**
 * Get materiel
 *
 * @return string
 */
public function getMateriel()
{
    return $this->materiel;
}

/**
 * Set accompagnementPiano
 *
 * @param boolean $accompagnementPiano
 *
 * @return morceau
 */
public function setAccompagnementPiano($accompagnementPiano)
{
    $this->accompagnementPiano = $accompagnementPiano;

    return $this;
}

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

/**
 * Set eleve
 *
 * @param \AppBundle\Entity\Eleve $eleve
 *
 * @return Morceau
 */
public function setEleve(\AppBundle\Entity\Eleve $eleve = null)
{
    $this->eleve = $eleve;

    return $this;
}

/**
 * Get eleve
 *
 * @return \AppBundle\Entity\Eleve
 */
public function getEleve()
{
    return $this->eleve;
}
</code>```

}

Eleve:

```<code>/**
 * eleve
 *
 * @ORM\Table(name="Eleve")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\EleveRepository")
 */
class Eleve
{
/**
 * @var int
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

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

/**
 * @var string
 *
 * @ORM\Column(name="prenomEleve", type="string", length=50)
 */
private $prenomEleve;

/**
*
* @ORM\ManyToOne(targetEntity="Instrument", cascade={"persist"})
* @ORM\JoinColumn(name="instrument_id", referencedColumnName="id")
*/
private $instrument;

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

/**
 * Set nomEleve
 *
 * @param string $nomEleve
 *
 * @return eleve
 */
public function setNomEleve($nomEleve)
{
    $this->nomEleve = $nomEleve;

    return $this;
}

/**
 * Get nomEleve
 *
 * @return string
 */
public function getNomEleve()
{
    return $this->nomEleve;
}

/**
 * Set prenomEleve
 *
 * @param string $prenomEleve
 *
 * @return eleve
 */
public function setPrenomEleve($prenomEleve)
{
    $this->prenomEleve = $prenomEleve;

    return $this;
}

/**
 * Get prenomEleve
 *
 * @return string
 */
public function getPrenomEleve()
{
    return $this->prenomEleve;
}

/**
 * Set instrument
 *
 * @param \AppBundle\Entity\Instrument $instrument
 *
 * @return Eleve
 */
public function setInstrument(\AppBundle\Entity\Instrument $instrument)
{
    $this->instrument = $instrument;

    return $this;
}

/**
 * Get instrument
 *
 * @return \AppBundle\Entity\Instrument
 */
public function getInstrument()
{
    return $this->instrument;
}
</code>```

}

Instrument:

```<code>/**
 * Instrument
 *
 * @ORM\Table(name="Instrument")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\InstrumentRepository")
 */
class Instrument
{
/**
 * @var int
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @var string
 *
 * @ORM\Column(name="nomInstrument", type="string", length=50)
 */
private $nomInstrument;

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

/**
 * Set nomInstrument
 *
 * @param string $nomInstrument
 *
 * @return instrument
 */
public function setNomInstrument($nomInstrument)
{
    $this->nomInstrument = $nomInstrument;

    return $this;
}

/**
 * Get nomInstrument
 *
 * @return string
 */
public function getNomInstrument()
{
    return $this->nomInstrument;
}
</code>```

}

UPDATE #1:

When I look at the Profiler, I can see the problem. If you look at nomInstrument, it's a integer but it should be a string for my entity. In this example, 3 is the id of the Instrument selected...

```<code>appbundle_morceau : [▼
  "titre" => "Leapfrog"
  "compositeur" => "Ravel"
  "formation" => "duo"
  "duree" => "5"
  "materiel" => "micro"
  "accompagnementPiano" => "1"
  "eleve" => [▼
    "nomEleve" => "Georges"
    "prenomEleve" => "Gauthier"
    "instrument" => [▼
      "nomInstrument" => "3"
    ]
  ]
  "save" => ""
  "_token" => "m3priXJyFUHCGpP58twZx3yyeS1eb-yeWGtIWrv6Llc"
]
</code>```

UPDATE #2:

When I try to do the same action without the form, it works. I set the values in the controller like that:

```<code>public function testAction(Request $request)
{

    $repository = $this->getDoctrine()
                       ->getManager()
                       ->getRepository('AppBundle:Instrument');

    $instrumentId = $repository->find(3);

    $morceau = new Morceau();
    $eleve = new Eleve();

    $eleve->setNomEleve('Alex');
    $eleve->setPrenomEleve('Jean');
    $eleve->setInstrument($instrumentId);

    $morceau->setTitre('Bolero');
    $morceau->setCompositeur('Ravel');
    $morceau->setFormation('duo');
    $morceau->setDuree('4');
    $morceau->setMateriel('pupitre');
    $morceau->setAccompagnementPiano(true);
    $morceau->setEleve($eleve);

    $em = $this->getDoctrine()->getManager();
    $em->persist($morceau);
    $em->flush();
</code>```

答: When loading an Entity into a form you need to make sure your Entity class has a __toString() method. This is what Symfony uses for the "name" field of option elements.

Body:
I'm working on Symfony 3 with Doctrine. In my project for a music school, I have 3 entities (Morceau (translation of Tune), Eleve (translation of Student), Instrument). With one form, I would like to create new Morceau associate with new Eleve associate with an existing Instrument.

Now, I have a problem to associate Eleve with an existing Instrument which is an EntityType (list of all the music instruments):

Catchable Fatal Error: Object of class AppBundle\Entity\Instrument could not be converted to string

The thing is that I don't want to create a new Instrument id.

The associations are: Morceau (with @ORM/ManyToOne $eleve), Eleve(@ORM/ManyToOne $instrument), Instrument (with $id and $nomInstrument).

My Forms:

MorceauType:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('titre', TextType::class)
            ->add('compositeur', TextType::class)
            ->add('formation', TextType::class)
            ->add('duree', IntegerType::class)
            ->add('materiel', TextType::class)
            ->add('accompagnementPiano', ChoiceType::class,
                array('choices' => array('Oui' => True, 'Non' => False)))
            ->add('eleve', EleveType::class)
            ->add('save', SubmitType::class)    ;
}

EleveType:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('nomEleve', TextType::class)
            ->add('prenomEleve', TextType::class)
            ->add('instrument', InstrumentType::class)
                                ;
}

InstrumentType:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('nomInstrument', EntityType::class, array('class' => 'AppBundle:Instrument',
                                                                        'choice_label' => 'nomInstrument'))
    ;
}

My Controller:

public function addTuneAction(Request $request)
{

    // On récupère le formulaire Morceaux
    $morceau = new Morceau();

    $form = $this->createForm(MorceauType::class, $morceau);

    //On vérifie les valeurs
    if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($morceau);
        $em->flush();

        $request->getSession()->getFlashBag()->add('notice', 'Morceau enregistré');

        return $this->redirectToRoute('index');
    }

    // on retourne la vue
    return $this->render('snippets/addTune.html.twig', array('morceau' => $form->createView()));
}

Many thanks !

Here's my entities:

Morceau:

/**
 * Morceau
 *
 * @ORM\Table(name="Morceau")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\MorceauRepository")
 */
class Morceau
{
/**
 * @var int
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

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

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

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

/**
 * @var int
 *
 * @ORM\Column(name="duree", type="smallint")
 */
private $duree;

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

/**
 * @var bool
 *
 * @ORM\Column(name="accompagnementPiano", type="boolean")
 */
private $accompagnementPiano;

/**
*
* @ORM\ManyToOne(targetEntity="Eleve", cascade={"persist"})
* @ORM\JoinColumn(name="eleve_id", referencedColumnName="id")
*/
private $eleve;

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

/**
 * Set titre
 *
 * @param string $titre
 *
 * @return morceau
 */
public function setTitre($titre)
{
    $this->titre = $titre;

    return $this;
}

/**
 * Get titre
 *
 * @return string
 */
public function getTitre()
{
    return $this->titre;
}

/**
 * Set compositeur
 *
 * @param string $compositeur
 *
 * @return morceau
 */
public function setCompositeur($compositeur)
{
    $this->compositeur = $compositeur;

    return $this;
}

/**
 * Get compositeur
 *
 * @return string
 */
public function getCompositeur()
{
    return $this->compositeur;
}

/**
 * Set formation
 *
 * @param string $formation
 *
 * @return morceau
 */
public function setFormation($formation)
{
    $this->formation = $formation;

    return $this;
}

/**
 * Get formation
 *
 * @return string
 */
public function getFormation()
{
    return $this->formation;
}

/**
 * Set duree
 *
 * @param integer $duree
 *
 * @return morceau
 */
public function setDuree($duree)
{
    $this->duree = $duree;

    return $this;
}

/**
 * Get duree
 *
 * @return int
 */
public function getDuree()
{
    return $this->duree;
}

/**
 * Set materiel
 *
 * @param string $materiel
 *
 * @return morceau
 */
public function setMateriel($materiel)
{
    $this->materiel = $materiel;

    return $this;
}

/**
 * Get materiel
 *
 * @return string
 */
public function getMateriel()
{
    return $this->materiel;
}

/**
 * Set accompagnementPiano
 *
 * @param boolean $accompagnementPiano
 *
 * @return morceau
 */
public function setAccompagnementPiano($accompagnementPiano)
{
    $this->accompagnementPiano = $accompagnementPiano;

    return $this;
}

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

/**
 * Set eleve
 *
 * @param \AppBundle\Entity\Eleve $eleve
 *
 * @return Morceau
 */
public function setEleve(\AppBundle\Entity\Eleve $eleve = null)
{
    $this->eleve = $eleve;

    return $this;
}

/**
 * Get eleve
 *
 * @return \AppBundle\Entity\Eleve
 */
public function getEleve()
{
    return $this->eleve;
}

}

Eleve:

/**
 * eleve
 *
 * @ORM\Table(name="Eleve")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\EleveRepository")
 */
class Eleve
{
/**
 * @var int
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

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

/**
 * @var string
 *
 * @ORM\Column(name="prenomEleve", type="string", length=50)
 */
private $prenomEleve;

/**
*
* @ORM\ManyToOne(targetEntity="Instrument", cascade={"persist"})
* @ORM\JoinColumn(name="instrument_id", referencedColumnName="id")
*/
private $instrument;

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

/**
 * Set nomEleve
 *
 * @param string $nomEleve
 *
 * @return eleve
 */
public function setNomEleve($nomEleve)
{
    $this->nomEleve = $nomEleve;

    return $this;
}

/**
 * Get nomEleve
 *
 * @return string
 */
public function getNomEleve()
{
    return $this->nomEleve;
}

/**
 * Set prenomEleve
 *
 * @param string $prenomEleve
 *
 * @return eleve
 */
public function setPrenomEleve($prenomEleve)
{
    $this->prenomEleve = $prenomEleve;

    return $this;
}

/**
 * Get prenomEleve
 *
 * @return string
 */
public function getPrenomEleve()
{
    return $this->prenomEleve;
}

/**
 * Set instrument
 *
 * @param \AppBundle\Entity\Instrument $instrument
 *
 * @return Eleve
 */
public function setInstrument(\AppBundle\Entity\Instrument $instrument)
{
    $this->instrument = $instrument;

    return $this;
}

/**
 * Get instrument
 *
 * @return \AppBundle\Entity\Instrument
 */
public function getInstrument()
{
    return $this->instrument;
}

}

Instrument:

/**
 * Instrument
 *
 * @ORM\Table(name="Instrument")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\InstrumentRepository")
 */
class Instrument
{
/**
 * @var int
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @var string
 *
 * @ORM\Column(name="nomInstrument", type="string", length=50)
 */
private $nomInstrument;

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

/**
 * Set nomInstrument
 *
 * @param string $nomInstrument
 *
 * @return instrument
 */
public function setNomInstrument($nomInstrument)
{
    $this->nomInstrument = $nomInstrument;

    return $this;
}

/**
 * Get nomInstrument
 *
 * @return string
 */
public function getNomInstrument()
{
    return $this->nomInstrument;
}

}

UPDATE #1:

When I look at the Profiler, I can see the problem. If you look at nomInstrument, it's a integer but it should be a string for my entity. In this example, 3 is the id of the Instrument selected...

appbundle_morceau : [▼
  "titre" => "Leapfrog"
  "compositeur" => "Ravel"
  "formation" => "duo"
  "duree" => "5"
  "materiel" => "micro"
  "accompagnementPiano" => "1"
  "eleve" => [▼
    "nomEleve" => "Georges"
    "prenomEleve" => "Gauthier"
    "instrument" => [▼
      "nomInstrument" => "3"
    ]
  ]
  "save" => ""
  "_token" => "m3priXJyFUHCGpP58twZx3yyeS1eb-yeWGtIWrv6Llc"
]

UPDATE #2:

When I try to do the same action without the form, it works. I set the values in the controller like that:

public function testAction(Request $request)
{

    $repository = $this->getDoctrine()
                       ->getManager()
                       ->getRepository('AppBundle:Instrument');

    $instrumentId = $repository->find(3);

    $morceau = new Morceau();
    $eleve = new Eleve();

    $eleve->setNomEleve('Alex');
    $eleve->setPrenomEleve('Jean');
    $eleve->setInstrument($instrumentId);

    $morceau->setTitre('Bolero');
    $morceau->setCompositeur('Ravel');
    $morceau->setFormation('duo');
    $morceau->setDuree('4');
    $morceau->setMateriel('pupitre');
    $morceau->setAccompagnementPiano(true);
    $morceau->setEleve($eleve);

    $em = $this->getDoctrine()->getManager();
    $em->persist($morceau);
    $em->flush();


来源: stackexchange

问:
Getting AJAX data in Laravel
I'm pulling my hair out here. I cannot access data submitted through an Ajax request in Laravel. I've tried using formData and just plain objects. Every time I just see a default Request object in Laravel and not the data I've submitted.

Here's my JS (TypeScript):

```<code>$('#save-section-order').on('click', function(e){
   e.preventDefault();

   let $this = $(this);
   let data = [];

   const order = $('#sortable').sortable('serialize');
   const project_id = $this.data('id');
   const url = "/admin/save-new-order";
   const csrfToken = $this.data('csrf');

   $.ajax({
       url: url,
       type: 'POST',
       data: {
           order: order,
           project_id: project_id
       },
       contentType: false,
       processData: false,
       headers: {
           'X-CSRF-TOKEN': csrfToken,
           'X-HTTP-Method-Override': 'PATCH'
       },
       success: function( msg ) {
           if ( msg.status === 'success' ) {
               $this.parent().parent().fadeOut();
           }
       },
       error: function( data ) {
           if ( data.status !== 200 ) {
               $this.parent().parent().css('background-color', '#f2dede');
           }
       }
   });
});
</code>```

Here's my web route:

Route::patch('/admin/save-new-order', 'Admin\ProjectsController@saveSectionsOrder');

Here's my ProjectsController:

```<code>public function saveSectionsOrder(Request $request) {

    dd($request);

}
</code>```

The output is always a generic Request object and I cannot retrieve the data I submitted through $request->order or $request->input('order').

I know I'm missing something really obvious, but I just can't see what.

答:
You have contentType: false, which tells $.ajax that you have no content.

Per docs (emphasis mine):

When sending data to the server, use this content type. Default is
  "application/x-www-form-urlencoded; charset=UTF-8", which is fine for
  most cases. If you explicitly pass in a content-type to  $.ajax(),
  then it is always sent to the server (even if no data is sent). As of
  jQuery 1.6 you can pass false to tell jQuery to not set any content
  type header. Note: The W3C XMLHttpRequest specification dictates that
  the charset is always UTF-8; specifying another charset will not force
  the browser to change the encoding. Note: For cross-domain requests,
  setting the content type to anything other than
  application/x-www-form-urlencoded, multipart/form-data, or text/plain
  will trigger the browser to send a preflight OPTIONS request to the
  server.

Change that to something more appropriate, or remove it to allow it to default to application/x-www-form-urlencoded.

Also, you may want to keep processData: false, depending on the nature of the data you're sending, but otherwise remove that, too.

ContentLicense: CC BY-SA 3.0

Title: Getting AJAX data in Laravel

Body:
I'm pulling my hair out here. I cannot access data submitted through an Ajax request in Laravel. I've tried using formData and just plain objects. Every time I just see a default Request object in Laravel and not the data I've submitted.

Here's my JS (TypeScript):

$('#save-section-order').on('click', function(e){
   e.preventDefault();

   let $this = $(this);
   let data = [];

   const order = $('#sortable').sortable('serialize');
   const project_id = $this.data('id');
   const url = "/admin/save-new-order";
   const csrfToken = $this.data('csrf');

   $.ajax({
       url: url,
       type: 'POST',
       data: {
           order: order,
           project_id: project_id
       },
       contentType: false,
       processData: false,
       headers: {
           'X-CSRF-TOKEN': csrfToken,
           'X-HTTP-Method-Override': 'PATCH'
       },
       success: function( msg ) {
           if ( msg.status === 'success' ) {
               $this.parent().parent().fadeOut();
           }
       },
       error: function( data ) {
           if ( data.status !== 200 ) {
               $this.parent().parent().css('background-color', '#f2dede');
           }
       }
   });
});

Here's my web route:

Route::patch('/admin/save-new-order', 'Admin\ProjectsController@saveSectionsOrder');

Here's my ProjectsController:

public function saveSectionsOrder(Request $request) {

    dd($request);

}

The output is always a generic Request object and I cannot retrieve the data I submitted through $request->order or $request->input('order').

I know I'm missing something really obvious, but I just can't see what.


问:
Android: setting custom view's text color with tab layout's style
I am using tab layouts with custom view in some fragments and I want the custom view's text color to be set from the tab layout style (as the custom view would be reused at different places and with different text colors, I want the different stylings of the tab layouts to set the colors). I have not defined any text colors in the custom view, still the text is always shown black instead of white, which is set in the tab layout style.

Codes:

Tab layout style:

```<code><style name="TabBar">
    <item name="android:background">@color/secondary_bg_color</item>
    <item name="tabIndicatorColor">@color/tab_indicator_color</item>
    <item name="tabIndicatorHeight">@dimen/tab_height</item>
    <item name="tabGravity">fill</item>
    <item name="tabTextColor">@color/white_text_color</item>
    <item name="tabSelectedTextColor">@color/white_text_color</item>
</style>
</code>```

Custom view:

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:paddingBottom="@dimen/default_padding_bottom"
    android:paddingTop="@dimen/default_padding_top">

    <TextView
        android:id="@+id/tab_title"
        style="@style/TabLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="@dimen/payment_tab_padding_left" />

</LinearLayout>
</code>```

TabLabel style:

```<code><style name="TabLabel">
    <item name="android:textSize">@dimen/textsize_caption</item>
    <item name="android:textAlignment">textStart</item>
</style>
</code>```

Usage:

```<code><android.support.design.widget.AppBarLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:background="@color/primary_bg_color"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/ThemeOverlay.AppCompat.ActionBar">

    <android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/collapsing_toolbar"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:contentScrim="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <FrameLayout
                android:id="@+id/bf_fragment_container"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:visibility="gone"/>

    </android.support.design.widget.CollapsingToolbarLayout>

    <TabLayout
        android:id="@+id/outgoing_tab"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        style="@style/TabBar"
        app:tabMode="scrollable"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

</android.support.design.widget.AppBarLayout>
</code>```

What is going wrong? Why doesn't the tab layout's text color have any effect on the text color of the custom view?

答:
Because tabTextColor y tabSelectedTextColor only works with the default textView of the tab but it doesn't work with custom tabs. You can see this behaviour in the source implementation of TabLayout.

You need to handle the text colors of custom tabs by yourself.

Body:
I am using tab layouts with custom view in some fragments and I want the custom view's text color to be set from the tab layout style (as the custom view would be reused at different places and with different text colors, I want the different stylings of the tab layouts to set the colors). I have not defined any text colors in the custom view, still the text is always shown black instead of white, which is set in the tab layout style.

Codes:

Tab layout style:

Custom view:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:paddingBottom="@dimen/default_padding_bottom"
    android:paddingTop="@dimen/default_padding_top">

    <TextView
        android:id="@+id/tab_title"
        style="@style/TabLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="@dimen/payment_tab_padding_left" />

</LinearLayout>

TabLabel style:

Usage:

<android.support.design.widget.AppBarLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:background="@color/primary_bg_color"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/ThemeOverlay.AppCompat.ActionBar">

    <android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/collapsing_toolbar"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:contentScrim="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <FrameLayout
                android:id="@+id/bf_fragment_container"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:visibility="gone"/>

    </android.support.design.widget.CollapsingToolbarLayout>

    <TabLayout
        android:id="@+id/outgoing_tab"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        style="@style/TabBar"
        app:tabMode="scrollable"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

</android.support.design.widget.AppBarLayout>

What is going wrong? Why doesn't the tab layout's text color have any effect on the text color of the custom view?


问:
GIT re-merge files from dev to master
My master GIT branch seams to have some errors thus I'd like to recheck, re-merge or possibly clone my dev branch over the master branch so the master branch would be a copy of dev.

How can I do that?
Thx.

答:
If the problem is simply that your checked-out files don't match up with the branch, just use git reset normally:

```<code>git reset --hard HEAD
</code>```

That should be all you need. However, if you still want to overwrite master with dev, read on.

If you want to overwrite your master branch with the contents of your dev branch, use git reset like so:

```<code>$ git checkout master
$ git reset --hard dev
</code>```

And then if you want to push this somewhere else:

```<code>$ git push origin master
</code>```

Note that if your dev branch doesn't fast-forward from your master branch (which I'm guessing it won't, since you said that your master branch has some screwed up stuff in it), you'll need to add the --force flag to the push to overwrite it on a remote:

```<code>$ git push origin master --force
</code>```

Note, however, that this can involve all of the normal caveats of rewriting history a la git rebase - if anyone else uses this remote, they'll need to deal with the equivalent of an upstream rebase.

To avoid this problem in the future, advise your friend that using --force is almost never necessary. If they're getting conflicts when they try to git push, they should git pull first, resolve the conflicts, and then git push.

ContentLicense: CC BY-SA 2.5

Title: GIT re-merge files from dev to master

Body:
If the problem is simply that your checked-out files don't match up with the branch, just use git reset normally:

git reset --hard HEAD

That should be all you need. However, if you still want to overwrite master with dev, read on.

If you want to overwrite your master branch with the contents of your dev branch, use git reset like so:

$ git checkout master
$ git reset --hard dev

And then if you want to push this somewhere else:

$ git push origin master

Note that if your dev branch doesn't fast-forward from your master branch (which I'm guessing it won't, since you said that your master branch has some screwed up stuff in it), you'll need to add the --force flag to the push to overwrite it on a remote:

$ git push origin master --force

Note, however, that this can involve all of the normal caveats of rewriting history a la git rebase - if anyone else uses this remote, they'll need to deal with the equivalent of an upstream rebase.

To avoid this problem in the future, advise your friend that using --force is almost never necessary. If they're getting conflicts when they try to git push, they should git pull first, resolve the conflicts, and then git push.


问:
How to assign value for a variable from user input in python Tkinter?
```<code>from tkinter import *
from tkinter.messagebox import *

def userinput():
    v=StringVar()
    a=input(v.get)
    return(a)

sub = Tk()

Label(sub, text = "Your name :").grid(row=0)

num1 = Entry(sub)
num1.grid(row=0,column=1)

name2=userinput()

Button(sub, text="Proceed", command=sub.destroy).grid(row=1,column=3)

mainloop()
print name2
</code>```

When I run this code i get the following in the shell:

(bound method StringVar.get of (tkinter.StringVar object at 0x02E48D30))

答:
I have a vague idea of what you're trying to do. First, don't use the input method with a GUI. Use the GUI. And here is how you can convert what you have to do at least that much. To operate it, type a name if the entry field, then press the Return key.

```<code>from tkinter import *
import sys

def userinput(*args):
    print(v.get())

sub = Tk()
v = StringVar()

Label(sub, text = "Your name :").grid(row=0)

num1 = Entry(sub, textvariable=v)
num1.grid(row=0,column=1)
num1.bind("<KeyPress-Return>", userinput)

userinput()

Button(sub, text="Proceed", command=sys.exit).grid(row=1,column=3)

sub.mainloop()
</code>```

Body:
from tkinter import *
from tkinter.messagebox import *

def userinput():
    v=StringVar()
    a=input(v.get)
    return(a)

sub = Tk()

Label(sub, text = "Your name :").grid(row=0)

num1 = Entry(sub)
num1.grid(row=0,column=1)

name2=userinput()

Button(sub, text="Proceed", command=sub.destroy).grid(row=1,column=3)

mainloop()
print name2

When I run this code i get the following in the shell:

(bound method StringVar.get of (tkinter.StringVar object at 0x02E48D30))

Body:
I have a vague idea of what you're trying to do. First, don't use the input method with a GUI. Use the GUI. And here is how you can convert what you have to do at least that much. To operate it, type a name if the entry field, then press the Return key.

from tkinter import *
import sys

def userinput(*args):
    print(v.get())

sub = Tk()
v = StringVar()

Label(sub, text = "Your name :").grid(row=0)

num1 = Entry(sub, textvariable=v)
num1.grid(row=0,column=1)
num1.bind("<KeyPress-Return>", userinput)

userinput()

Button(sub, text="Proceed", command=sys.exit).grid(row=1,column=3)

sub.mainloop()


问:
Why can't I use foreach on my Class?
I'm trying to use my custom class with an iterator, but it can't iterate on the elements using foreach. How can I deal with it?

```<code>public class FCSOfOtherClass<Double> {
private int n;
private Double[] a;

public FCSOfOtherClass(int cap) {
    a = (Double[]) new Object[cap];
}

public void push(Double dou) {
    if (a.length == n) {
        this.resize(2 * a.length);
        a[n++] = dou;
    } else {
        a[n++] = dou;
    }
}

private void resize(int max) {
    Double[] newa = (Double[]) new Object[max];
    for (int i = 0; i < n; i++) {
        newa[i] = a[i];
        a = newa;
    }
}

public Boolean isEmpty() {
    return n == 0;
}

public Double pop() {
    Double dou = a[--n];
    a[n] = null;
    if (n > 0 && n == a.length / 2) {
        resize(a.length / 2);
    }
    return dou;
}

public int size() {
    return n;
}

public Iterator<Double> iterator() {
    return new RAIterator();
}

private class RAIterator implements Iterator<Double> {
    private int i = n;

    @Override
    public boolean hasNext() {
        return i > 0;
    }

    @Override
    public Double next() {
        return a[--i];
    }

    @Override
    public void remove() {

    }

    @Override
    public void forEachRemaining(Consumer<? super Double> action) {

    }
</code>```

This is my main method:

```<code>public static void main(String[] args) {
    FCSOfOtherClass<Integer> fcs = new FCSOfOtherClass<>(100);
    int i = 0;
    while (!StdIn.isEmpty()) {
        fcs.push(++i);
    }
    for (int j:fcs) {
        StdOut.print(j);
    }
}
</code>```

When I run this, I get an error telling me that foreach is not applicable to my type.

答:
Your class FCSOfOtherClass does not implement java.lang.Iterable. The "foreach" loop only works on arrays and instances of Iterable.

You can address this by making your class implement Iterable:

```<code>public class FCSOfOtherClass implements java.lang.Iterable<Double> {
    ...
}
</code>```

This requires that you provide an implementation for the interface method iterator(). Your sample code shows that you already do:

```<code>public Iterator<Double> iterator() {
    return new RAIterator();
}
</code>```

This is covered in the Java Language Specification, section 14.14.2: The enhanced for statement:

The type of the Expression must be Iterable or an array type (§10.1), or a compile-time error occurs.

Title: Why can't I use foreach on my Class?

Body:
I'm trying to use my custom class with an iterator, but it can't iterate on the elements using foreach. How can I deal with it?

public class FCSOfOtherClass<Double> {
private int n;
private Double[] a;

public FCSOfOtherClass(int cap) {
    a = (Double[]) new Object[cap];
}

public void push(Double dou) {
    if (a.length == n) {
        this.resize(2 * a.length);
        a[n++] = dou;
    } else {
        a[n++] = dou;
    }
}

private void resize(int max) {
    Double[] newa = (Double[]) new Object[max];
    for (int i = 0; i < n; i++) {
        newa[i] = a[i];
        a = newa;
    }
}

public Boolean isEmpty() {
    return n == 0;
}

public Double pop() {
    Double dou = a[--n];
    a[n] = null;
    if (n > 0 && n == a.length / 2) {
        resize(a.length / 2);
    }
    return dou;
}

public int size() {
    return n;
}

public Iterator<Double> iterator() {
    return new RAIterator();
}

private class RAIterator implements Iterator<Double> {
    private int i = n;

    @Override
    public boolean hasNext() {
        return i > 0;
    }

    @Override
    public Double next() {
        return a[--i];
    }

    @Override
    public void remove() {

    }

    @Override
    public void forEachRemaining(Consumer<? super Double> action) {

    }

This is my main method:

public static void main(String[] args) {
    FCSOfOtherClass<Integer> fcs = new FCSOfOtherClass<>(100);
    int i = 0;
    while (!StdIn.isEmpty()) {
        fcs.push(++i);
    }
    for (int j:fcs) {
        StdOut.print(j);
    }
}

When I run this, I get an error telling me that foreach is not applicable to my type.

Body:
Your class FCSOfOtherClass does not implement java.lang.Iterable. The "foreach" loop only works on arrays and instances of Iterable.

You can address this by making your class implement Iterable:

public class FCSOfOtherClass implements java.lang.Iterable<Double> {
    ...
}

This requires that you provide an implementation for the interface method iterator(). Your sample code shows that you already do:

public Iterator<Double> iterator() {
    return new RAIterator();
}

This is covered in the Java Language Specification, section 14.14.2: The enhanced for statement:

The type of the Expression must be Iterable or an array type (§10.1), or a compile-time error occurs.


问:
facet-style titles in non-facetted plots
I like very much the style of the titles of facet plots:

```<code>require(ggplot2)
df <- data.frame(x = rnorm(1E3), labels = as.factor(c(rep("plot1",500), rep("plot2",500))));
ggplot(df, aes(x=x) ) + geom_histogram() +facet_wrap(~labels)
</code>```

And I would like to format other plots' titles in a similar fashion.  When I just add ggtitle() to the plot, I get the following:

ggplot(df, aes(x=x) ) + geom_histogram() +ggtitle('plot1 and plot2')

How can I format the ggtitle title to look like the facet_wrap title?

Thank you!

答:
If you want thing to look just like the strip labels, you could create a new column for your title that contains a single group and use that variable to facet with.

Essentially using facets with a fake variable to get the look you like.

```<code>df$overall = "plot1 and plot2"

ggplot(df, aes(x=x) ) +
     geom_histogram() +
     facet_wrap(~overall)
</code>```

Body:
I like very much the style of the titles of facet plots:

require(ggplot2)
df <- data.frame(x = rnorm(1E3), labels = as.factor(c(rep("plot1",500), rep("plot2",500))));
ggplot(df, aes(x=x) ) + geom_histogram() +facet_wrap(~labels)

And I would like to format other plots' titles in a similar fashion.  When I just add ggtitle() to the plot, I get the following:

ggplot(df, aes(x=x) ) + geom_histogram() +ggtitle('plot1 and plot2')

How can I format the ggtitle title to look like the facet_wrap title?

Thank you!

Body:
If you want thing to look just like the strip labels, you could create a new column for your title that contains a single group and use that variable to facet with.

Essentially using facets with a fake variable to get the look you like.

df$overall = "plot1 and plot2"

ggplot(df, aes(x=x) ) +
     geom_histogram() +
     facet_wrap(~overall)


问:
Find position of last Non Null element in a list in C#
I have the following values in my MySQL DB

```<code>Date        High_Low_Price
5/18/2017   302
5/19/2017   315.3
5/22/2017   Null
5/23/2017   Null
5/24/2017   Null
5/25/2017   Null
5/26/2017   Null
5/29/2017   Null
</code>```

and I have create the a list in the below format

```<code>List<db1> StockData = new List<db1>();
db1 newStock = new db1();
newStock.High_Low_Price = (double)reader["High_Low_Price"];
StockData.Add(newStock);
</code>```

How can I find the position of the last not null element (i.e. i) in the list. When I mean last element I am refering to the 315.3 of High_Low_Price on the 5/19/2017.

the Null values in High_Low_Price column will keep varying in size. How would i then find the last date which has a value in this list ?

EDIT: i need two things, The Date and the position.

答:
Since you mentioned in one of your comments that Null values are always at the end of the list then assuming that's the case and since you only want the position of the element and its date a naive approach to solving this would be to just do </p>

```<code>        var i = 0;
        var pos = 0;
        DateTime? date = null;
        while (i < StockData.Count && StockData.ElementAt(i)?.High_Low_Price != null )
        {
            pos = i;
            date = StockData.ElementAt(i).Date;
            i++;
        }
</code>```

Body:
I have the following values in my MySQL DB

Date        High_Low_Price
5/18/2017   302
5/19/2017   315.3
5/22/2017   Null
5/23/2017   Null
5/24/2017   Null
5/25/2017   Null
5/26/2017   Null
5/29/2017   Null

and I have create the a list in the below format

List<db1> StockData = new List<db1>();
db1 newStock = new db1();
newStock.High_Low_Price = (double)reader["High_Low_Price"];
StockData.Add(newStock);

How can I find the position of the last not null element (i.e. i) in the list. When I mean last element I am refering to the 315.3 of High_Low_Price on the 5/19/2017.

the Null values in High_Low_Price column will keep varying in size. How would i then find the last date which has a value in this list ?

EDIT: i need two things, The Date and the position.

Body:
Since you mentioned in one of your comments that Null values are always at the end of the list then assuming that's the case and since you only want the position of the element and its date a naive approach to solving this would be to just do

        var i = 0;
        var pos = 0;
        DateTime? date = null;
        while (i < StockData.Count && StockData.ElementAt(i)?.High_Low_Price != null )
        {
            pos = i;
            date = StockData.ElementAt(i).Date;
            i++;
        }


问:
WCF channel factory timeout in WPF Application
I am hosting a WCF service in a WPF application in C#. I would like to call some initializing functions from the host itself so I am using a channel factory. When the host is open I can call the WCF service methods from another application but when I run the following code in the host I get a time out on the Test() method.

```<code>host = new ServiceHost(typeof(SequencerService), new Uri(address));
host.Open();

var binding = new NetTcpBinding(SecurityMode.None);
EndpointAddress endpoint = new EndpointAddress("net.tcp://10.0.0.118:50111/SequencerService");
ChannelFactory<ISequencerService> myFactory = new ChannelFactory<ISequencerService>(binding, endpoint);
ISequencerService mService = myFactory.CreateChannel();

Console.WriteLine(mService.Test());
</code>```

I get locked on the last line of code. Also, if I try to host this code in a console application it works fine. Why is there a difference when running this in a WPF windows application?

答:
I just found the answer. It seems like the service must be hosted in a separate thread than it is consumed in. To host I used:</p>

```<code>new Thread(()=>{
    host = new ServiceHost(typeof(SequencerService), new Uri(address));
    host.Open();
}.Start();
</code>```

Body:
I am hosting a WCF service in a WPF application in C#. I would like to call some initializing functions from the host itself so I am using a channel factory. When the host is open I can call the WCF service methods from another application but when I run the following code in the host I get a time out on the Test() method.

host = new ServiceHost(typeof(SequencerService), new Uri(address));
host.Open();

var binding = new NetTcpBinding(SecurityMode.None);
EndpointAddress endpoint = new EndpointAddress("net.tcp://10.0.0.118:50111/SequencerService");
ChannelFactory<ISequencerService> myFactory = new ChannelFactory<ISequencerService>(binding, endpoint);
ISequencerService mService = myFactory.CreateChannel();

Console.WriteLine(mService.Test());

I get locked on the last line of code. Also, if I try to host this code in a console application it works fine. Why is there a difference when running this in a WPF windows application?

Body:
I just found the answer. It seems like the service must be hosted in a separate thread than it is consumed in. To host I used:

new Thread(()=>{
    host = new ServiceHost(typeof(SequencerService), new Uri(address));
    host.Open();
}.Start();


问:
Error:warning: Ignoring InnerClasses attribute for an anonymous inner class for Paho/Mqtt
Hi I am currently working on an android project using android studio. I would like to use the Paho/Mqtt library but I seem to encounter a problem when building.

These are the relevant elements in the build.gradle file

```<code>repositories {
    jcenter()
    maven {
        url "https://repo.eclipse.org/content/repositories/paho-snapshots/"
    }
}

dependencies {
    compile 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.1.1'
    compile('org.eclipse.paho:org.eclipse.paho.android.service:1.1.1') {
        exclude module: 'support-v4'
    }
}
</code>```

There is 56 errors, but the build still shows as BUILD SUCCESSFUL.

```<code>Error:warning: Ignoring InnerClasses attribute for an anonymous inner class
Error:(org.eclipse.paho.client.mqttv3.MqttAsyncClient$1) that doesn't come with an
Error:associated EnclosingMethod attribute. This class was probably produced by a
Error:compiler that did not target the modern .class file format. The recommended
Error:solution is to recompile the class from source, using an up-to-date compiler
Error:and without specifying any "-target" type options. The consequence of ignoring
Error:this warning is that reflective operations on this class will incorrectly
Error:indicate that it is *not* an inner class.
</code>```

and this same message shows up 5 more times for

```<code>(org.eclipse.paho.client.mqttv3.internal.ClientComms$1
(org.eclipse.paho.client.mqttv3.internal.websocket.WebSocketSecureNetworkModule$1)
(org.eclipse.paho.client.mqttv3.internal.websocket.WebSocketNetworkModule$1)
(org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence$1)
(org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence$2)
</code>```

This is the logs in the Gradle Console

```<code>AGPBI: {"kind":"error","text":"warning: Ignoring InnerClasses attribute for an anonymous inner class","sources":[{}]}
AGPBI: {"kind":"error","text":"(org.eclipse.paho.client.mqttv3.MqttAsyncClient$1) that doesn\u0027t come with an","sources":[{}]}
AGPBI: {"kind":"error","text":"associated EnclosingMethod attribute. This class was probably produced by a","sources":[{}]}
AGPBI: {"kind":"error","text":"compiler that did not target the modern .class file format. The recommended","sources":[{}]}
AGPBI: {"kind":"error","text":"solution is to recompile the class from source, using an up-to-date compiler","sources":[{}]}
AGPBI: {"kind":"error","text":"and without specifying any \"-target\" type options. The consequence of ignoring","sources":[{}]}
AGPBI: {"kind":"error","text":"this warning is that reflective operations on this class will incorrectly","sources":[{}]}
AGPBI: {"kind":"error","text":"indicate that it is *not* an inner class.","sources":[{}]}
AGPBI: {"kind":"error","text":"warning: Ignoring InnerClasses attribute for an anonymous inner class","sources":[{}]}
AGPBI: {"kind":"error","text":"(org.eclipse.paho.client.mqttv3.MqttAsyncClient$2) that doesn\u0027t come with an","sources":[{}]}
AGPBI: {"kind":"error","text":"associated EnclosingMethod attribute. This class was probably produced by a","sources":[{}]}
AGPBI: {"kind":"error","text":"compiler that did not target the modern .class file format. The recommended","sources":[{}]}
AGPBI: {"kind":"error","text":"solution is to recompile the class from source, using an up-to-date compiler","sources":[{}]}
AGPBI: {"kind":"error","text":"and without specifying any \"-target\" type options. The consequence of ignoring","sources":[{}]}
AGPBI: {"kind":"error","text":"this warning is that reflective operations on this class will incorrectly","sources":[{}]}
AGPBI: {"kind":"error","text":"indicate that it is *not* an inner class.","sources":[{}]}
AGPBI: {"kind":"error","text":"warning: Ignoring InnerClasses attribute for an anonymous inner class","sources":[{}]}
AGPBI: {"kind":"error","text":"(org.eclipse.paho.client.mqttv3.internal.ClientComms$1) that doesn\u0027t come with an","sources":[{}]}
AGPBI: {"kind":"error","text":"associated EnclosingMethod attribute. This class was probably produced by a","sources":[{}]}
AGPBI: {"kind":"error","text":"compiler that did not target the modern .class file format. The recommended","sources":[{}]}
AGPBI: {"kind":"error","text":"solution is to recompile the class from source, using an up-to-date compiler","sources":[{}]}
AGPBI: {"kind":"error","text":"and without specifying any \"-target\" type options. The consequence of ignoring","sources":[{}]}
AGPBI: {"kind":"error","text":"this warning is that reflective operations on this class will incorrectly","sources":[{}]}
AGPBI: {"kind":"error","text":"indicate that it is *not* an inner class.","sources":[{}]}
AGPBI: {"kind":"error","text":"warning: Ignoring InnerClasses attribute for an anonymous inner class","sources":[{}]}
AGPBI: {"kind":"error","text":"(org.eclipse.paho.client.mqttv3.internal.websocket.WebSocketSecureNetworkModule$1) that doesn\u0027t come with an","sources":[{}]}
AGPBI: {"kind":"error","text":"associated EnclosingMethod attribute. This class was probably produced by a","sources":[{}]}
AGPBI: {"kind":"error","text":"compiler that did not target the modern .class file format. The recommended","sources":[{}]}
AGPBI: {"kind":"error","text":"solution is to recompile the class from source, using an up-to-date compiler","sources":[{}]}
AGPBI: {"kind":"error","text":"and without specifying any \"-target\" type options. The consequence of ignoring","sources":[{}]}
AGPBI: {"kind":"error","text":"this warning is that reflective operations on this class will incorrectly","sources":[{}]}
AGPBI: {"kind":"error","text":"indicate that it is *not* an inner class.","sources":[{}]}
AGPBI: {"kind":"error","text":"warning: Ignoring InnerClasses attribute for an anonymous inner class","sources":[{}]}
AGPBI: {"kind":"error","text":"(org.eclipse.paho.client.mqttv3.internal.websocket.WebSocketNetworkModule$1) that doesn\u0027t come with an","sources":[{}]}
AGPBI: {"kind":"error","text":"associated EnclosingMethod attribute. This class was probably produced by a","sources":[{}]}
AGPBI: {"kind":"error","text":"compiler that did not target the modern .class file format. The recommended","sources":[{}]}
AGPBI: {"kind":"error","text":"solution is to recompile the class from source, using an up-to-date compiler","sources":[{}]}
AGPBI: {"kind":"error","text":"and without specifying any \"-target\" type options. The consequence of ignoring","sources":[{}]}
AGPBI: {"kind":"error","text":"this warning is that reflective operations on this class will incorrectly","sources":[{}]}
AGPBI: {"kind":"error","text":"indicate that it is *not* an inner class.","sources":[{}]}
AGPBI: {"kind":"error","text":"warning: Ignoring InnerClasses attribute for an anonymous inner class","sources":[{}]}
AGPBI: {"kind":"error","text":"(org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence$1) that doesn\u0027t come with an","sources":[{}]}
AGPBI: {"kind":"error","text":"associated EnclosingMethod attribute. This class was probably produced by a","sources":[{}]}
AGPBI: {"kind":"error","text":"compiler that did not target the modern .class file format. The recommended","sources":[{}]}
AGPBI: {"kind":"error","text":"solution is to recompile the class from source, using an up-to-date compiler","sources":[{}]}
AGPBI: {"kind":"error","text":"and without specifying any \"-target\" type options. The consequence of ignoring","sources":[{}]}
AGPBI: {"kind":"error","text":"this warning is that reflective operations on this class will incorrectly","sources":[{}]}
AGPBI: {"kind":"error","text":"indicate that it is *not* an inner class.","sources":[{}]}
AGPBI: {"kind":"error","text":"warning: Ignoring InnerClasses attribute for an anonymous inner class","sources":[{}]}
AGPBI: {"kind":"error","text":"(org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence$2) that doesn\u0027t come with an","sources":[{}]}
AGPBI: {"kind":"error","text":"associated EnclosingMethod attribute. This class was probably produced by a","sources":[{}]}
AGPBI: {"kind":"error","text":"compiler that did not target the modern .class file format. The recommended","sources":[{}]}
AGPBI: {"kind":"error","text":"solution is to recompile the class from source, using an up-to-date compiler","sources":[{}]}
AGPBI: {"kind":"error","text":"and without specifying any \"-target\" type options. The consequence of ignoring","sources":[{}]}
AGPBI: {"kind":"error","text":"this warning is that reflective operations on this class will incorrectly","sources":[{}]}
AGPBI: {"kind":"error","text":"indicate that it is *not* an inner class.","sources":[{}]}
</code>```

I tried fixing this error by adding in my proguard-rules.pro file

```<code>-keepattributes InnerClasses
-keepattributes EnclosingMethod
-dontoptimize
</code>```

As well as these lines in the defaultConfig block of the build.gradle file

```<code>compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
}
</code>```

The two above solutions still left me with the same 56 errors. Would anyone know what to do in this situation?

答:
This might not be an optimal answer but the I changed the version to 1.1.2-SNAPSHOT and the build was actually successful. I'll see if I encounter any other error. let me know if this solution works for you.

```<code>dependencies {
    compile 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.1.2-SNAPSHOT'
    compile('org.eclipse.paho:org.eclipse.paho.android.service:1.1.2-SNAPSHOT') {
        exclude module: 'support-v4'
    }
}
</code>```

Body:
Hi I am currently working on an android project using android studio. I would like to use the Paho/Mqtt library but I seem to encounter a problem when building.

These are the relevant elements in the build.gradle file

repositories {
    jcenter()
    maven {
        url "https://repo.eclipse.org/content/repositories/paho-snapshots/"
    }
}

dependencies {
    compile 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.1.1'
    compile('org.eclipse.paho:org.eclipse.paho.android.service:1.1.1') {
        exclude module: 'support-v4'
    }
}

There is 56 errors, but the build still shows as BUILD SUCCESSFUL.

Error:warning: Ignoring InnerClasses attribute for an anonymous inner class
Error:(org.eclipse.paho.client.mqttv3.MqttAsyncClient$1) that doesn't come with an
Error:associated EnclosingMethod attribute. This class was probably produced by a
Error:compiler that did not target the modern .class file format. The recommended
Error:solution is to recompile the class from source, using an up-to-date compiler
Error:and without specifying any "-target" type options. The consequence of ignoring
Error:this warning is that reflective operations on this class will incorrectly
Error:indicate that it is *not* an inner class.

and this same message shows up 5 more times for

(org.eclipse.paho.client.mqttv3.internal.ClientComms$1
(org.eclipse.paho.client.mqttv3.internal.websocket.WebSocketSecureNetworkModule$1)
(org.eclipse.paho.client.mqttv3.internal.websocket.WebSocketNetworkModule$1)
(org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence$1)
(org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence$2)

This is the logs in the Gradle Console

AGPBI: {"kind":"error","text":"warning: Ignoring InnerClasses attribute for an anonymous inner class","sources":[{}]}
AGPBI: {"kind":"error","text":"(org.eclipse.paho.client.mqttv3.MqttAsyncClient$1) that doesn\u0027t come with an","sources":[{}]}
AGPBI: {"kind":"error","text":"associated EnclosingMethod attribute. This class was probably produced by a","sources":[{}]}
AGPBI: {"kind":"error","text":"compiler that did not target the modern .class file format. The recommended","sources":[{}]}
AGPBI: {"kind":"error","text":"solution is to recompile the class from source, using an up-to-date compiler","sources":[{}]}
AGPBI: {"kind":"error","text":"and without specifying any \"-target\" type options. The consequence of ignoring","sources":[{}]}
AGPBI: {"kind":"error","text":"this warning is that reflective operations on this class will incorrectly","sources":[{}]}
AGPBI: {"kind":"error","text":"indicate that it is *not* an inner class.","sources":[{}]}
AGPBI: {"kind":"error","text":"warning: Ignoring InnerClasses attribute for an anonymous inner class","sources":[{}]}
AGPBI: {"kind":"error","text":"(org.eclipse.paho.client.mqttv3.MqttAsyncClient$2) that doesn\u0027t come with an","sources":[{}]}
AGPBI: {"kind":"error","text":"associated EnclosingMethod attribute. This class was probably produced by a","sources":[{}]}
AGPBI: {"kind":"error","text":"compiler that did not target the modern .class file format. The recommended","sources":[{}]}
AGPBI: {"kind":"error","text":"solution is to recompile the class from source, using an up-to-date compiler","sources":[{}]}
AGPBI: {"kind":"error","text":"and without specifying any \"-target\" type options. The consequence of ignoring","sources":[{}]}
AGPBI: {"kind":"error","text":"this warning is that reflective operations on this class will incorrectly","sources":[{}]}
AGPBI: {"kind":"error","text":"indicate that it is *not* an inner class.","sources":[{}]}
AGPBI: {"kind":"error","text":"warning: Ignoring InnerClasses attribute for an anonymous inner class","sources":[{}]}
AGPBI: {"kind":"error","text":"(org.eclipse.paho.client.mqttv3.internal.ClientComms$1) that doesn\u0027t come with an","sources":[{}]}
AGPBI: {"kind":"error","text":"associated EnclosingMethod attribute. This class was probably produced by a","sources":[{}]}
AGPBI: {"kind":"error","text":"compiler that did not target the modern .class file format. The recommended","sources":[{}]}
AGPBI: {"kind":"error","text":"solution is to recompile the class from source, using an up-to-date compiler","sources":[{}]}
AGPBI: {"kind":"error","text":"and without specifying any \"-target\" type options. The consequence of ignoring","sources":[{}]}
AGPBI: {"kind":"error","text":"this warning is that reflective operations on this class will incorrectly","sources":[{}]}
AGPBI: {"kind":"error","text":"indicate that it is *not* an inner class.","sources":[{}]}
AGPBI: {"kind":"error","text":"warning: Ignoring InnerClasses attribute for an anonymous inner class","sources":[{}]}
AGPBI: {"kind":"error","text":"(org.eclipse.paho.client.mqttv3.internal.websocket.WebSocketSecureNetworkModule$1) that doesn\u0027t come with an","sources":[{}]}
AGPBI: {"kind":"error","text":"associated EnclosingMethod attribute. This class was probably produced by a","sources":[{}]}
AGPBI: {"kind":"error","text":"compiler that did not target the modern .class file format. The recommended","sources":[{}]}
AGPBI: {"kind":"error","text":"solution is to recompile the class from source, using an up-to-date compiler","sources":[{}]}
AGPBI: {"kind":"error","text":"and without specifying any \"-target\" type options. The consequence of ignoring","sources":[{}]}
AGPBI: {"kind":"error","text":"this warning is that reflective operations on this class will incorrectly","sources":[{}]}
AGPBI: {"kind":"error","text":"indicate that it is *not* an inner class.","sources":[{}]}
AGPBI: {"kind":"error","text":"warning: Ignoring InnerClasses attribute for an anonymous inner class","sources":[{}]}
AGPBI: {"kind":"error","text":"(org.eclipse.paho.client.mqttv3.internal.websocket.WebSocketNetworkModule$1) that doesn\u0027t come with an","sources":[{}]}
AGPBI: {"kind":"error","text":"associated EnclosingMethod attribute. This class was probably produced by a","sources":[{}]}
AGPBI: {"kind":"error","text":"compiler that did not target the modern .class file format. The recommended","sources":[{}]}
AGPBI: {"kind":"error","text":"solution is to recompile the class from source, using an up-to-date compiler","sources":[{}]}
AGPBI: {"kind":"error","text":"and without specifying any \"-target\" type options. The consequence of ignoring","sources":[{}]}
AGPBI: {"kind":"error","text":"this warning is that reflective operations on this class will incorrectly","sources":[{}]}
AGPBI: {"kind":"error","text":"indicate that it is *not* an inner class.","sources":[{}]}
AGPBI: {"kind":"error","text":"warning: Ignoring InnerClasses attribute for an anonymous inner class","sources":[{}]}
AGPBI: {"kind":"error","text":"(org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence$1) that doesn\u0027t come with an","sources":[{}]}
AGPBI: {"kind":"error","text":"associated EnclosingMethod attribute. This class was probably produced by a","sources":[{}]}
AGPBI: {"kind":"error","text":"compiler that did not target the modern .class file format. The recommended","sources":[{}]}
AGPBI: {"kind":"error","text":"solution is to recompile the class from source, using an up-to-date compiler","sources":[{}]}
AGPBI: {"kind":"error","text":"and without specifying any \"-target\" type options. The consequence of ignoring","sources":[{}]}
AGPBI: {"kind":"error","text":"this warning is that reflective operations on this class will incorrectly","sources":[{}]}
AGPBI: {"kind":"error","text":"indicate that it is *not* an inner class.","sources":[{}]}
AGPBI: {"kind":"error","text":"warning: Ignoring InnerClasses attribute for an anonymous inner class","sources":[{}]}
AGPBI: {"kind":"error","text":"(org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence$2) that doesn\u0027t come with an","sources":[{}]}
AGPBI: {"kind":"error","text":"associated EnclosingMethod attribute. This class was probably produced by a","sources":[{}]}
AGPBI: {"kind":"error","text":"compiler that did not target the modern .class file format. The recommended","sources":[{}]}
AGPBI: {"kind":"error","text":"solution is to recompile the class from source, using an up-to-date compiler","sources":[{}]}
AGPBI: {"kind":"error","text":"and without specifying any \"-target\" type options. The consequence of ignoring","sources":[{}]}
AGPBI: {"kind":"error","text":"this warning is that reflective operations on this class will incorrectly","sources":[{}]}
AGPBI: {"kind":"error","text":"indicate that it is *not* an inner class.","sources":[{}]}

I tried fixing this error by adding in my proguard-rules.pro file

-keepattributes InnerClasses
-keepattributes EnclosingMethod
-dontoptimize

As well as these lines in the defaultConfig block of the build.gradle file

compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
}

The two above solutions still left me with the same 56 errors. Would anyone know what to do in this situation?

Body:
This might not be an optimal answer but the I changed the version to 1.1.2-SNAPSHOT and the build was actually successful. I'll see if I encounter any other error. let me know if this solution works for you.

dependencies {
    compile 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.1.2-SNAPSHOT'
    compile('org.eclipse.paho:org.eclipse.paho.android.service:1.1.2-SNAPSHOT') {
        exclude module: 'support-v4'
    }
}


问:
How to replace an entire cell with NaN on pandas DataFrame
I want to replace the entire cell that contains the word as circled in the picture with blanks or NaN. However when I try to replace for example '1.25 Dividend' it turned out as '1.25 NaN'. I want to return the whole cell as 'NaN'. Any idea how to work on this?

答:
Replace all strings:</p>

```<code>df.apply(lambda x: pd.to_numeric(x, errors='coerce'))
</code>```

Body:
Replace all strings:

df.apply(lambda x: pd.to_numeric(x, errors='coerce'))


问:
How to run Google Assistant SDK on start-up?
How do I get google-assistant-demo to run on boot?

I can run it manually with

```<code>$ source /home/pi/env/bin/activate
(env) $ google-assistant-demo
</code>```

But I want to run it on start up, in CLI Mode or GUI mode.
I want it to run inside its virtual environment (venv).
All in the background without interfering with any terminal or SSH session.

答:
This is what I did to achieve startup without a monitor (I think some call it headless?) on my Raspberry Pi Model B.  Hope this helps!

Record a sound file using arecord

https://developers.google.com/assistant/sdk/prototype/getting-started-pi-python/configure-audio

In /home/pi/config/lxsession/LXDE-pi/autostart add

@lxterminal --command "/home/pi/googlehome.sh"

Something like this

```<code>@lxpanel --profile LXDE-pi
@pcmanfm --desktop --profile LXDE-pi
@lxterminal --command "/home/pi/googlehome.sh"
@xscreensaver -no-splash
@point-rpi
</code>```

Where googlehome.sh is the script that runs Google Assistant demo on startup.

In googlehome.sh have it play a sound file then run the demo

```<code>#!/bin/bash
echo Running Google Home Assistant...
sleep 2
aplay --format=S16_LE --rate=16k "/home/pi/googlehomeready.raw"

source env/bin/activate
google-assistant-demo
</code>```

Since I'm not sure when Google Assistant is ready when power on, I have it play a sound file googlehomeready.raw.  Once I hear it, I know Google Assistant demo is running.

Oh, make sure change the mode type to executable for googlehome.sh.

Body:
How do I get google-assistant-demo to run on boot?

I can run it manually with

$ source /home/pi/env/bin/activate
(env) $ google-assistant-demo

But I want to run it on start up, in CLI Mode or GUI mode.
I want it to run inside its virtual environment (venv).
All in the background without interfering with any terminal or SSH session.

Body:
This is what I did to achieve startup without a monitor (I think some call it headless?) on my Raspberry Pi Model B.  Hope this helps!

Record a sound file using arecord

https://developers.google.com/assistant/sdk/prototype/getting-started-pi-python/configure-audio

In /home/pi/config/lxsession/LXDE-pi/autostart add

@lxterminal --command "/home/pi/googlehome.sh"

Something like this

@lxpanel --profile LXDE-pi
@pcmanfm --desktop --profile LXDE-pi
@lxterminal --command "/home/pi/googlehome.sh"
@xscreensaver -no-splash
@point-rpi

Where googlehome.sh is the script that runs Google Assistant demo on startup.

In googlehome.sh have it play a sound file then run the demo

#!/bin/bash
echo Running Google Home Assistant...
sleep 2
aplay --format=S16_LE --rate=16k "/home/pi/googlehomeready.raw"

source env/bin/activate
google-assistant-demo

Since I'm not sure when Google Assistant is ready when power on, I have it play a sound file googlehomeready.raw.  Once I hear it, I know Google Assistant demo is running.

Oh, make sure change the mode type to executable for googlehome.sh.


问:
golang: accessing value in slice of interfaces
I have a data structure which comes of out go-spew looking like this:

```<code>([]interface {}) (len=1 cap=1) {
 (string) (len=1938) "value"
}
</code>```

It is of type []interface {}

How can I print this value with fmt, or access it in some way so that I can use it.

答:
You can use type assertions or reflection work with the generic interface{} to an underlying type. How you do this depends on your particular use case. If you can expect the interface{} to be a []interface{} as in your example, you can:

```<code>if sl, ok := thing.([]interface{}); ok {
    for _, val := range sl {
        fmt.Println(val)
        // Or if needed, coerce val to its underlying type, e.g. strVal := val.(string)
    }
}
</code>```

(Playground link)

If you can't make assumptions about the underlying type, you'll need to do some black magic using reflect.

Body:
I have a data structure which comes of out go-spew looking like this:

([]interface {}) (len=1 cap=1) {
 (string) (len=1938) "value"
}

It is of type []interface {}

How can I print this value with fmt, or access it in some way so that I can use it.

Body:
You can use type assertions or reflection work with the generic interface{} to an underlying type. How you do this depends on your particular use case. If you can expect the interface{} to be a []interface{} as in your example, you can:

if sl, ok := thing.([]interface{}); ok {
    for _, val := range sl {
        fmt.Println(val)
        // Or if needed, coerce val to its underlying type, e.g. strVal := val.(string)
    }
}

(Playground link)

If you can't make assumptions about the underlying type, you'll need to do some black magic using reflect.


问:
Visual Studio 2015 project template type
I'm creating a project template and suffering placing it into a particular section in "New Project" window. I found a MyTemplate.vstemplate xml-like file inside the template folder and there is an entry 'ProjectType'. And that seems to be the right way to solve the problem just setting a proper value there, but I can't find all the list of available types. No problem placing the template into 'Visual C#' or 'Visual Basic' sections, but I would like to put in under 'Other Project Types' or 'Visual Studio Solutions'.

And the greatest achievement would be to setup the template along with an extension.

Any ideas will be appreciated. Thanks

csproj content:

```<code>    <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProjectGuid>{$guid1$}</ProjectGuid>
    <OutputType>Library</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>$safeprojectname$</RootNamespace>
    <AssemblyName>$safeprojectname$</AssemblyName>
    <TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
    <FileAlignment>512</FileAlignment>
    <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup>
    <StartupObject />
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="System" />
    <Reference Include="System.ComponentModel.Composition" />
    <Reference Include="System.Core" />
    <Reference Include="System.Xml.Linq" />
    <Reference Include="System.Data.DataSetExtensions" />
    <Reference Include="Microsoft.CSharp" />
    <Reference Include="System.Data" />
    <Reference Include="System.Net.Http" />
    <Reference Include="System.Xml" />
  </ItemGroup>
  <ItemGroup>
    <Compile Include="ModuleRegistry.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
  </ItemGroup>
  <ItemGroup>
    <None Include="App.config" />
  </ItemGroup>
  <ItemGroup />
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
       Other similar extension points exist, see Microsoft.Common.targets.
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target>
  -->
  <Target Name="TemplateProjectOutputGroup">
  </Target>
</Project>
</code>```

答:
It's not ProjectType that you should use for that.

Edit the csproj that contains the MyTemplate.vstemplate file and set the OutputSubPath value like this:

```<code><VSTemplate Include="MyTemplate.vstemplate">
    <OutputSubPath>ELEVATION</OutputSubPath>
</VSTemplate>
</code>```

Body:
I'm creating a project template and suffering placing it into a particular section in "New Project" window. I found a MyTemplate.vstemplate xml-like file inside the template folder and there is an entry 'ProjectType'. And that seems to be the right way to solve the problem just setting a proper value there, but I can't find all the list of available types. No problem placing the template into 'Visual C#' or 'Visual Basic' sections, but I would like to put in under 'Other Project Types' or 'Visual Studio Solutions'.

And the greatest achievement would be to setup the template along with an extension.

Any ideas will be appreciated. Thanks

csproj content:

    <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProjectGuid>{$guid1$}</ProjectGuid>
    <OutputType>Library</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>$safeprojectname$</RootNamespace>
    <AssemblyName>$safeprojectname$</AssemblyName>
    <TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
    <FileAlignment>512</FileAlignment>
    <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup>
    <StartupObject />
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="System" />
    <Reference Include="System.ComponentModel.Composition" />
    <Reference Include="System.Core" />
    <Reference Include="System.Xml.Linq" />
    <Reference Include="System.Data.DataSetExtensions" />
    <Reference Include="Microsoft.CSharp" />
    <Reference Include="System.Data" />
    <Reference Include="System.Net.Http" />
    <Reference Include="System.Xml" />
  </ItemGroup>
  <ItemGroup>
    <Compile Include="ModuleRegistry.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
  </ItemGroup>
  <ItemGroup>
    <None Include="App.config" />
  </ItemGroup>
  <ItemGroup />
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />

  <Target Name="TemplateProjectOutputGroup">
  </Target>
</Project>

Body:
It's not ProjectType that you should use for that.

Edit the csproj that contains the MyTemplate.vstemplate file and set the OutputSubPath value like this:

<VSTemplate Include="MyTemplate.vstemplate">
    <OutputSubPath>ELEVATION</OutputSubPath>
</VSTemplate>


问:
How to use a camera with OpenCV
I'm trying to learn OpenCV. I have been playing around with it for an entire day trying to get it to recognize my camera. I just can't get it to work and I can't find any information about it.

My camera is a usb xbox live webcam, as soon as I connected it to my computer windows recognized it as if it were its own child and installed the drivers.

DISCLAIMER I'm like completely clueless as I have never worked with cameras before in code and I don't know how hard or difficult it would be to use one, nor do I know where to start, what information to look up, or anything like that. :( DISCLAIMER

I found this example on the opencv website at this url:
http://opencv.willowgarage.com/wiki/CameraCapture

I copy and pasted the first one which says "Here is a simple framework to connect to a camera and show the images in a Window.". I formatted it correctly and got it to compile and run perfectly, but it gives the error "ERROR: capture is NULL" when I execute it(not a compiler error, its an error in the application)

答:
I think there are more than enough code on stackoverflow that shows how to do the trick:

OpenCV 2.1: Runtime error

Unable to detect web cam in OpenCV

OpenCV: process every frame

OpenCV 'cvQueryFrame' non-blocking on OS X?

Title: How to use a camera with OpenCV


问:
How to detect that a scroll bar knob is being dragged by the user
I have (old...) code that updates the scrollbar position and min-max values in the background with SetScrollRange() but this code should not run while the user is dragging the scrollbar knob as it makes the knob visually jump back to the original position and then jumps back to the user's selected position when he drags or releases the mouse.

Is there some easy way to detect that the dragging is going on?

答:
I can think of two ways to do this. The easy (and hacky) way to do it is to call GetCapture(). It will return the HWND value of the current window that has captured the mouse, or NULL if the mouse is not captured. This simply means that the user has pushed the mouse button within the scrollbar control without releasing the mouse button.

The better way to do it would be to subclass the control. Here's some example code on how you could set a flag if the scrollbar's "thumb" is being dragged:

```<code>// Somewhere in your code, subclass the scrollbar
WNDPROC originalScrollBarWndProc = (WNDPROC) SetWindowLongPtr(scrollBarHwnd, GWLP_WNDPROC, (LONG_PTR) myScrollBarWndProc);

LRESULT CALLBACK myScrollBarWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch(message)
    {
        case WM_LBUTTONDOWN:
        {
            // Get Y position of the mouse
            uint16_t mouseYPos = HIWORD(lParam); // Change this to LOWORD for horizontal scrollbars

            // Get the top and bottom coordinates of the scrollbar thumb
            SCROLLBARINFO sbi = {0};
            sbi.cbSize = sizeof(SCROLLBARINFO);

            if(GetScrollBarInfo(hwnd, OBJID_CLIENT, &sbi) == 0)
            {
                // Failed to get scroll bar info, handle however you want
                break;
            }

            // Check if the WM_LBUTTONDOWN event happened over the scrollbar thumb
            if(mouseYPos >= sbi.xyThumbTop && mouseYPos <= sbi.xyThumbBottom)
            {
                // Set a flag to indicate that the thumb is being "dragged"
                // I chose to do this using SetWindowLongPtr; Do it however you like.
                SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR) 1);
            }
        }
        break;

        case WM_LBUTTONUP:
        {
            // Mouse button was released, clear the flag
            SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR) 0);
        }
        break;

        /* ... other cases here, if needed ... */
    }

    return CallWindowProc(originalScrollBarWndProc, hwnd, message, wParam, lParam);
}
</code>```

Using the code above, all you'd have to do is call GetWindowLongPtr(scrollBarHwnd, GWLP_USERDATA) and check if the value is 0 or 1 to see if it's being dragged or not.

I'm not positive this is the best approach to the problem, but I am sure it is at least a good one that will work well.

Body:
I can think of two ways to do this. The easy (and hacky) way to do it is to call GetCapture(). It will return the HWND value of the current window that has captured the mouse, or NULL if the mouse is not captured. This simply means that the user has pushed the mouse button within the scrollbar control without releasing the mouse button.

The better way to do it would be to subclass the control. Here's some example code on how you could set a flag if the scrollbar's "thumb" is being dragged:

// Somewhere in your code, subclass the scrollbar
WNDPROC originalScrollBarWndProc = (WNDPROC) SetWindowLongPtr(scrollBarHwnd, GWLP_WNDPROC, (LONG_PTR) myScrollBarWndProc);

LRESULT CALLBACK myScrollBarWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch(message)
    {
        case WM_LBUTTONDOWN:
        {
            // Get Y position of the mouse
            uint16_t mouseYPos = HIWORD(lParam); // Change this to LOWORD for horizontal scrollbars

            // Get the top and bottom coordinates of the scrollbar thumb
            SCROLLBARINFO sbi = {0};
            sbi.cbSize = sizeof(SCROLLBARINFO);

            if(GetScrollBarInfo(hwnd, OBJID_CLIENT, &sbi) == 0)
            {
                // Failed to get scroll bar info, handle however you want
                break;
            }

            // Check if the WM_LBUTTONDOWN event happened over the scrollbar thumb
            if(mouseYPos >= sbi.xyThumbTop && mouseYPos <= sbi.xyThumbBottom)
            {
                // Set a flag to indicate that the thumb is being "dragged"
                // I chose to do this using SetWindowLongPtr; Do it however you like.
                SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR) 1);
            }
        }
        break;

        case WM_LBUTTONUP:
        {
            // Mouse button was released, clear the flag
            SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR) 0);
        }
        break;

        /* ... other cases here, if needed ... */
    }

    return CallWindowProc(originalScrollBarWndProc, hwnd, message, wParam, lParam);
}

Using the code above, all you'd have to do is call GetWindowLongPtr(scrollBarHwnd, GWLP_USERDATA) and check if the value is 0 or 1 to see if it's being dragged or not.

I'm not positive this is the best approach to the problem, but I am sure it is at least a good one that will work well.


问:
Why we are using 'special checking for namespace object content:media' here?
I came across this python code.

```<code>def parseXML(xmlfile):

# create element tree object
tree = ET.parse(xmlfile)

# get root element
root = tree.getroot()

# create empty list for news items
newsitems = []

# iterate news items
for item in root.findall('./channel/item'):

    # empty news dictionary
    news = {}

    # iterate child elements of item
    for child in item:

        # special checking for namespace object content:media    HERE
        if child.tag == '{http://search.yahoo.com/mrss/}content': #HERE
            news['media'] = child.attrib['url']                 #HERE
        else:
            news[child.tag] = child.text.encode('utf8')

    # append news dictionary to news items list
    newsitems.append(news)

# return news items list
return newsitems
</code>```

Can someone tell me what this content:media checking here is? Why are we doing this? I am unable to find something meaning on the internet about what actually this is.

答:
This is SOAP API element. For example:

```<code> <?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2003/05/soap-envelope/"
soap:encodingStyle="http://www.w3.org/2003/05/soap-encoding">

<soap:Body>
    <m:GetPrice xmlns:m="https://www.w3schools.com/prices">
        <m:Item>Apples</m:Item>
    </m:GetPrice>
</soap:Body>

</soap:Envelope>
</code>```

In previous XML file, if you want to get <Item>Apples</Item>. You have to use:

```<code>body.find('{https://www.w3schools.com/prices}Item')
</code>```

Body:
I came across this python code.

def parseXML(xmlfile):

# create element tree object
tree = ET.parse(xmlfile)

# get root element
root = tree.getroot()

# create empty list for news items
newsitems = []

# iterate news items
for item in root.findall('./channel/item'):

    # empty news dictionary
    news = {}

    # iterate child elements of item
    for child in item:

        # special checking for namespace object content:media    HERE
        if child.tag == '{http://search.yahoo.com/mrss/}content': #HERE
            news['media'] = child.attrib['url']                 #HERE
        else:
            news[child.tag] = child.text.encode('utf8')

    # append news dictionary to news items list
    newsitems.append(news)

# return news items list
return newsitems

Can someone tell me what this content:media checking here is? Why are we doing this? I am unable to find something meaning on the internet about what actually this is.

Body:
This is SOAP API element. For example:

 <?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2003/05/soap-envelope/"
soap:encodingStyle="http://www.w3.org/2003/05/soap-encoding">

<soap:Body>
    <m:GetPrice xmlns:m="https://www.w3schools.com/prices">
        <m:Item>Apples</m:Item>
    </m:GetPrice>
</soap:Body>

</soap:Envelope>

In previous XML file, if you want to get <Item>Apples</Item>. You have to use:

body.find('{https://www.w3schools.com/prices}Item')


问:
Create multistep buttons
I'm trying to create a multistep form with the following buttons:

But I have no clue on how to begin with this. Can someone help me on my way? Maybe a good resource? I'm also using bootstrap in my application.

For now I have:

My HTML looks like this:

```<code>    <ol class="multi-step">
    <li class="active">
        <a href="http://mydomain/nl/data-analysis/templates">
            <span class="number-circle">1</span>
            Maak een sjabloon        </a>
    </li>
    <li class="">
        <a href="http://mydomain/nl/data-analysis/scheduler">
            <span class="number-circle">2</span>
            Plan je sjabloon        </a>
    </li>
    <li class="">
        <a href="http://mydomain/nl/data-analysis/reports">
            <span class="number-circle">3</span>
            Bekijk de resultaten        </a>
    </li>
</ol>
</code>```

答:
So, in HTML everything that gets rendered on the page is just a rectangle of a varying size. It may not appear that way, but everything has a bounding box and it determines its presence on the page.

There are roundabout ways to create shapes (like giving something 50% border-radius just turns it into a circle), but they're just that and they aren't really ideal.

What you have for what would constitute shapes is SVG, where you draw a vector onto the page of your own specifications.

However, I question if what you're showing constitutes a "design" or just an element that happens to look a certain way.

The best solutions I can come up with:

Insert two elements and use the CSS transform property to skew one one way and one the other way:

```<code><div id="bar">
  <div class="arrow">
    <a>asdf</a>
  </div>
  <div class="arrow">
    <a>hjkl</a>
  </div>
  <div class="arrow">
    <a>qwer</a>
  </div>
</div>
</code>```

```<code>#bar {
  display: flex;
  padding: 10px;
}

.arrow a {
  position: absolute;
  line-height: 100px;
  margin-top: -50px;
  width: 200px;
  margin-left: 25px;
  text-align: center;
  z-index: 1;
}

.arrow::before {
  content: '';
  background: blue;
  height: 50px;
  width: 200px;
  margin-left: 25px;
  display: block;
  transform: skew(45deg);
}

.arrow::after {
  content: '';
  background: blue;
  height: 50px;
  width: 200px;
  margin-left: 25px;
  display: block;
  transform: skew(-45deg);
}
</code>```

https://jsfiddle.net/7nku4474/1

Use SVG to draw the shape:

```<code><div id="bar">
  <a href="asdf">
    <svg fill="blue">
      <path d="M 0,0 L 200,0, L 250,50 L 200,100 L 0,100 L 50,50 Z">
      </path>
      <text x="125" y="50" font-size="12" fill="#fff" text-anchor="middle" alignment-baseline="central">
        asdf
      </text>
    </svg>
  </a>

  <a href="asdf">
    <svg fill="blue">
      <path d="M 0,0 L 200,0, L 250,50 L 200,100 L 0,100 L 50,50 Z">
      </path>
      <text x="125" y="50" font-size="12" fill="#fff" text-anchor="middle" alignment-baseline="central">
        hjkl
      </text>
    </svg>
  </a>

  <a href="asdf">
    <svg fill="blue">
      <path d="M 0,0 L 200,0, L 250,50 L 200,100 L 0,100 L 50,50 Z">
      </path>
      <text x="125" y="50" font-size="12" fill="#fff" text-anchor="middle" alignment-baseline="central">
        qwer
      </text>
    </svg>
  </a>
</div>
</code>```

```<code>#bar {
  display: flex;
}

#bar svg {
  height: 100px;
  width: 250px;
  margin: 10px;
}

#bar a:not(:first-of-type) {
  margin-left: -50px;
}
</code>```

https://jsfiddle.net/1smpuL1r/

Title: Create multistep buttons

Body:
I'm trying to create a multistep form with the following buttons:

But I have no clue on how to begin with this. Can someone help me on my way? Maybe a good resource? I'm also using bootstrap in my application.

For now I have:

My HTML looks like this:

            1
            Maak een sjabloon

            2
            Plan je sjabloon

            3
            Bekijk de resultaten

Body:
So, in HTML everything that gets rendered on the page is just a rectangle of a varying size. It may not appear that way, but everything has a bounding box and it determines its presence on the page.

There are roundabout ways to create shapes (like giving something 50% border-radius just turns it into a circle), but they're just that and they aren't really ideal.

What you have for what would constitute shapes is SVG, where you draw a vector onto the page of your own specifications.

However, I question if what you're showing constitutes a "design" or just an element that happens to look a certain way.

The best solutions I can come up with:

Insert two elements and use the CSS transform property to skew one one way and one the other way:

<div id="bar">
  <div class="arrow">
    <a>asdf</a>
  </div>
  <div class="arrow">
    <a>hjkl</a>
  </div>
  <div class="arrow">
    <a>qwer</a>
  </div>
</div>

#bar {
  display: flex;
  padding: 10px;
}

.arrow a {
  position: absolute;
  line-height: 100px;
  margin-top: -50px;
  width: 200px;
  margin-left: 25px;
  text-align: center;
  z-index: 1;
}

.arrow::before {
  content: '';
  background: blue;
  height: 50px;
  width: 200px;
  margin-left: 25px;
  display: block;
  transform: skew(45deg);
}

.arrow::after {
  content: '';
  background: blue;
  height: 50px;
  width: 200px;
  margin-left: 25px;
  display: block;
  transform: skew(-45deg);
}

https://jsfiddle.net/7nku4474/1

Use SVG to draw the shape:

<div id="bar">
  <a href="asdf">
    <svg fill="blue">
      <path d="M 0,0 L 200,0, L 250,50 L 200,100 L 0,100 L 50,50 Z">
      </path>
      <text x="125" y="50" font-size="12" fill="#fff" text-anchor="middle" alignment-baseline="central">
        asdf
      </text>
    </svg>
  </a>

  <a href="asdf">
    <svg fill="blue">
      <path d="M 0,0 L 200,0, L 250,50 L 200,100 L 0,100 L 50,50 Z">
      </path>
      <text x="125" y="50" font-size="12" fill="#fff" text-anchor="middle" alignment-baseline="central">
        hjkl
      </text>
    </svg>
  </a>

  <a href="asdf">
    <svg fill="blue">
      <path d="M 0,0 L 200,0, L 250,50 L 200,100 L 0,100 L 50,50 Z">
      </path>
      <text x="125" y="50" font-size="12" fill="#fff" text-anchor="middle" alignment-baseline="central">
        qwer
      </text>
    </svg>
  </a>
</div>

#bar {
  display: flex;
}

#bar svg {
  height: 100px;
  width: 250px;
  margin: 10px;
}

#bar a:not(:first-of-type) {
  margin-left: -50px;
}

https://jsfiddle.net/1smpuL1r/


问:
Autoincremented foreignkey and added new row in a table where I don't want to
I have a table named Users with the foreign key "BranchOffice_Id" and a table named BranchOffice with an autoincrementing primary key "Id". I have some issues with adding data into the Users table. Here is my code, written in C# using Entity Framework.

```<code>currentUser = new User()
{
   Username = username,
   UserType = UserType.User,
   Email = email,
   Name = name,
   BranchOffice = _taskService.GetBranchOfficeById(branchOffice)
};
_db.Users.Add(currentUser);
_db.SaveChanges();
</code>```

Until _db.Users.Add(currentUser); the value for currentUser.BranchOffice is 1, corresponding with Id #1 of the BranchOffice table. But the issue is the following: on _db.SaveChanges(); it doesn't save that value, but instead an incremented value (it started from '5', athough in BranchOffice table I have only 4 rows). And last but not least, it added a new row to the BranchOffice table!

Here are my models:

```<code>public class User : IPrincipal, IIdentity
{
    [Key]
    public string Username { get; set; }
    public UserType UserType { get; set; }
    public string Email { get; set; }
    public string Name { get; set; }
    public virtual BranchOffice BranchOffice { get; set; }
}

public class BranchOffice
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
}
</code>```

答:
When you add an Entity to a DbSet EF automatically adds all the related entities that are not part of the database.

With your code you can have 3 different cases during

```<code>BranchOffice = _taskService.GetBranchOfficeById(branchOffice)

_db.SaveChanges();
</code>```

If _taskService reads the BranchOffice from the database using the _db context EF will add a new User with the specified BranchOffice.

If _taskService reads the BranchOffice from the database using a different context EF will throw an exception.

If _taskService creates a new BranchOffice (outside any context and you don't attach BranchOffice to the _db context), EF will insert the BranchOffice in the database, retrieve the BranchOffice.Id from the database, update the in memory User, insert the User in the database.

The third is probably your case (you did not have the BranchOffice with Id=5 but EF created it)

Body:
I have a table named Users with the foreign key "BranchOffice_Id" and a table named BranchOffice with an autoincrementing primary key "Id". I have some issues with adding data into the Users table. Here is my code, written in C# using Entity Framework.

currentUser = new User()
{
   Username = username,
   UserType = UserType.User,
   Email = email,
   Name = name,
   BranchOffice = _taskService.GetBranchOfficeById(branchOffice)
};
_db.Users.Add(currentUser);
_db.SaveChanges();

Until _db.Users.Add(currentUser); the value for currentUser.BranchOffice is 1, corresponding with Id #1 of the BranchOffice table. But the issue is the following: on _db.SaveChanges(); it doesn't save that value, but instead an incremented value (it started from '5', athough in BranchOffice table I have only 4 rows). And last but not least, it added a new row to the BranchOffice table!

Here are my models:

public class User : IPrincipal, IIdentity
{
    [Key]
    public string Username { get; set; }
    public UserType UserType { get; set; }
    public string Email { get; set; }
    public string Name { get; set; }
    public virtual BranchOffice BranchOffice { get; set; }
}

public class BranchOffice
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
}

Body:
When you add an Entity to a DbSet EF automatically adds all the related entities that are not part of the database.

With your code you can have 3 different cases during

BranchOffice = _taskService.GetBranchOfficeById(branchOffice)

_db.SaveChanges();

If _taskService reads the BranchOffice from the database using the _db context EF will add a new User with the specified BranchOffice.

If _taskService reads the BranchOffice from the database using a different context EF will throw an exception.

If _taskService creates a new BranchOffice (outside any context and you don't attach BranchOffice to the _db context), EF will insert the BranchOffice in the database, retrieve the BranchOffice.Id from the database, update the in memory User, insert the User in the database.

The third is probably your case (you did not have the BranchOffice with Id=5 but EF created it)