问:
Symfony retrieve the id of the filled-in entity in the previous form
I will try to explain as best as possible. I created 2 linked entities for a @manytoone bidirectional relationship (I believe ^^ '). Here is what I want to do, I create a first form that allows me to fill the first entity (the daughter entity) and then I am redirected according to criteria to another page that allows me to fill the parent entity but I Can not find a way to retrieve the id of the entity girl, I tried to pass it through the URL but I can not retrieve it and insert it in the field id_daughterentities.
I enclose the code, I hope that this explanation will allow you to see more clearly.

```<code>public function newclientAction(Request $request)
{
    // On crée un objet Advert
    $client = new Clients();

    // J'ai raccourci cette partie, car c'est plus rapide à écrire !
    $form = $this->get('form.factory')->createBuilder(FormType::class, $client)
        ->add('FirstName',      TextType::class)
        ->add('Surname',      TextType::class)
        ->add('Address',      TextType::class)
        ->add('Mail',      EmailType::class, array(
            'required' => false))
        ->add('Mail2',   EmailType::class, array(
            'label' => 'Mail N°2',
            'required' => false
        ))
        ->add('Phone',      TextType::class, array(
            'required' => false))
        ->add('Phone2',     TextType::class, array('label' => 'Phone N°2',
            'required' => false))
        ->add('BirthDate',    BirthdayType::class, array('label' => 'Date of Birth'))
        ->add('Status',     ChoiceType::class, array(
            'choices'  => array(
                'Client' => 'Client',
                'Ex-Client' => 'Ex-Client',
                'Prospect' => 'Prospect'),
        ))
        ->add('Comments',     TextareaType::class, array(
            'required' => false))
        ->add('TypeofBuisness', ChoiceType::class, array(
            'choices'  => array(
                'Blank'=> Null,
                'SE' => 'SE',
                'SA' => 'SE',
                'LLP' => 'LTD',
                'LTD' => 'LTD',
                'Payroll' => 'Payroll'),
                'label' => 'Type of buisness'
        ))
        ->add('save',      SubmitType::class)
        ->getForm()
    ;

    // Si la requête est en POST
    if ($request->isMethod('POST')) {
        // On fait le lien Requête <-> Formulaire
        // À partir de maintenant, la variable $advert contient les valeurs entrées dans le formulaire par le visiteur
        $form->handleRequest($request);

        // On vérifie que les valeurs entrées sont correctes
        // (Nous verrons la validation des objets en détail dans le prochain chapitre)
        if ($form->isValid()) {
            // On enregistre notre objet $advert dans la base de données, par exemple
            $em = $this->getDoctrine()->getManager();
            $em->persist($client);
            $em->flush();

            $request->getSession()->getFlashBag()->add('notice', 'Well regitered.');
            if ($client->getTypeOfBuisness()== 'Payroll')
            {
                return $this->redirectToRoute('pegasus_payroll', array('id' => $client->getId()));
            }
            elseif ($client->getTypeOfBuisness()== 'LTD')
            {
                return $this->redirectToRoute('pegasus_ltd', array('id' => $client->getId()));
            }
            elseif ($client->getTypeOfBuisness()== 'LTD')
            {
                return $this->redirectToRoute('pegasus_se', array('id' => $client->getId()));
            }
            else {
                return $this->redirectToRoute('pegasus_web_homepage', array('id' => $client->getId()));
            }
        }
    }

    // À ce stade, le formulaire n'est pas valide car :
    // - Soit la requête est de type GET, donc le visiteur vient d'arriver sur la page et veut voir le formulaire
    // - Soit la requête est de type POST, mais le formulaire contient des valeurs invalides, donc on l'affiche de nouveau
    return $this->render('PegasusWebBundle:Default:newclient.html.twig', array(
        'form' => $form->createView(),
    ));
}
public function payrollAction(Request $request)
{
    // On crée un objet Advert
    $payroll = new Payroll();

    // J'ai raccourci cette partie, car c'est plus rapide à écrire !
    $form = $this->get('form.factory')->createBuilder(FormType::class, $payroll)
        ->add('EmployerName',      TextType::class, array('label' => 'Employer name'))
        ->add('EmployerSurname',      TextType::class)
        ->add('Address',      TextType::class, array('required' => false))
        ->add('Phone',      TextType::class, array('required' => false))
        ->add('Phone2',     TextType::class, array('label' => 'Phone N°2','required'=> false))
        ->add('Mail',      EmailType::class, array('required' => false))
        ->add('Mail2',   EmailType::class, array('label' => 'Mail N°2','required'=> false ))
        ->add('ContactName',      TextType::class, array('required' => false))
        ->add('Payedisctrict',      TextType::class, array('label' => 'PAYE district','required'=> false))
        ->add('Payeaddress',      TextType::class, array('label' => 'PAYE address','required'=> false))
        ->add('Payephone',      TextType::class, array('label' => 'PAYE phone','required'=> false))
        ->add('Payereference',      TextType::class, array('label' => 'PAYE reference','required'=> false))
        ->add('Accref',      TextType::class, array('label' => 'Account reference','required'=> false))
        ->add('Taxereff',      TextType::class, array('label' => 'Tax reference','required'=> false))
        ->add('Comments',     TextareaType::class, array('label' => 'Any comment ?','required'=> false))
        ->add('save',      SubmitType::class)
        ->getForm()
    ;
</code>```

I tried there to take the id from the url but it's not working, i tried tones of solutions but nothing works .... I really sorry for this stupid question but i'm trying to learn it by my own

```<code>    $payroll.clients=$request->query->get('id');

    // Si la requête est en POST
    if ($request->isMethod('POST')) {
        // On fait le lien Requête <-> Formulaire
        // À partir de maintenant, la variable $advert contient les valeurs entrées dans le formulaire par le visiteur
        $form->handleRequest($request);
        $payroll->is

        // On vérifie que les valeurs entrées sont correctes
        // (Nous verrons la validation des objets en détail dans le prochain chapitre)
        if ($form->isValid()) {
            // On enregistre notre objet $advert dans la base de données, par exemple
            $em = $this->getDoctrine()->getManager();
            $em->persist($payroll);
            $em->flush();

            $request->getSession()->getFlashBag()->add('notice', 'Well regitered.');

            return $this->redirectToRoute('pegasus_web_homepage');

        }
    }

    // À ce stade, le formulaire n'est pas valide car :
    // - Soit la requête est de type GET, donc le visiteur vient d'arriver sur la page et veut voir le formulaire
    // - Soit la requête est de type POST, mais le formulaire contient des valeurs invalides, donc on l'affiche de nouveau
    return $this->render('PegasusWebBundle:Default:newclient.html.twig', array(
        'form' => $form->createView(),
    ));
}
</code>```

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

    /**
     * @ORM\ManyToOne(targetEntity="Clients", inversedBy="payroll")
     * @ORM\JoinColumn(nullable=false, name="clients_id", referencedColumnName="id")
     */
    private $clients;

     /**
     * Set clients
     *
     * @param \Pegasus\WebBundle\Entity\Clients $clients
     *
     * @return Payroll
     */
    public function setClients(\Pegasus\WebBundle\Entity\Clients $clients )
    {
        $this->clients = $clients;

        return $this;
    }

    /**
     * Get clients
     *
     * @return \Pegasus\WebBundle\Entity\Clients
     */
    public function getClients()
    {
        return $this->clients;
    }
</code>```

Cause of that i can't validate my form because my foreign key is empty ... :/
Someone can help me ? pls

答:
First you need the Clients Entity object to persist the doctrine entity, not the integer ID. If you are passing the id in your request, you'll need to either use automatic Dependency Injection, or get the entity from doctrine manually, like so:

```<code>$clients = $this->getDoctrine()->getManager()
    ->find('PegasusWebBundle:Clients', $request->query->get('id'));
</code>```

The next issue is your Payroll form. It needs to be made aware of the Payroll entity (data_class option) and the Clients EntityType association, even if clients is a hidden field. Though it is unclear in your example how you are passing the form data to the new Payroll entity object.

For example using separate GET and POST actions.

```<code>/**
 * @Route("/pegasus_payroll/{id}", name="pegasus_payroll", requirements={"id":"\d+"})
 * @Method("GET")
 */
public function payrollAction(Request $request, \Pegasus\WebBundle\Entity\Clients $clients)
{
     $payroll = new Payroll();
     //set the new payroll clients based on the automatic param conversion
     $payroll->setClients($clients);
     $form = $this->createPayrollForm($payroll, ['action' => $this->generateUrl('save_pegasus_payroll')]);
     $form->handleRequest($request);

     return $this->render('PegasusWebBundle:Default:newpayroll.html.twig', [
        'form' => $form->createView(),
     ]);
}

/**
 * @Route("/pegasus_payroll", name="save_pegasus_payroll")
 * @Method("POST")
 */
public function savePayrollAction(Request $request)
{
     //retrieve the entity from the request form data, to validate with the previous form choice(s).
     $em = $this->getDoctrine()->getManager();
     $clients = $em->find('PegasusWebBundle:Clients', $request->request->get('form')['clients']);
     $payroll = new Payroll;
     $payroll->setClients($clients);
     $form = $this->createPayrollForm($payroll);
     $form->handleRequest($request);
     if ($form->isSubmitted() && $form->isValid()) {
         $formPayroll = $form->getData();
         echo $formPayroll->getClients()->getId();
         //the form data is propagated to the $payroll object passed to it
         echo $payroll->getClients()->getId();
         exit;
         //$em->persist($payroll);
         //$em->flush();
         //$this->addFlash('notice', 'Well regitered.');

         //return $this->redirectToRoute('pegasus_web_homepage');
     }

     return $this->render('PegasusWebBundle:Default:newpayroll.html.twig', [
         'form' => $form->createView(),
     ]);
}

/**
 * use a method to store the form so you can use it elsewhere
 * Alternatively create a new FormType class that extends AbstractFormType
 */
private function createPayrollForm(Payroll $payroll, array $options = [])
{
     $options['data_class'] = Payroll::class;

     return $this->get('form.factory')
         ->createBuilder(FormType::class, $payroll, $options)
         //.. you will need to update to match the Payroll entity property name getter/setters names.
         ->add('clients', EntityType::class, [
             'class' => \Pegasus\WebBundle\Entity\Clients::class,
             'multiple' => false, //only a single selection
             'label' => false, //don't display the form field label
             'choice_label' => false, //don't display select options
             'choices' => [$payroll->getClients()], //only available choice
             'attr' => [
                 'style' => 'display:none;' //hide the select box
             ]
        ])
        ->getForm();
}
</code>```

As a final note, you should take advantage of the automatic Dependency Injection using ParamConverter
It will make your life a lot easier when your controllers have type-hinted what they are requiring, rather than having to manually define evertything.

Body:
I will try to explain as best as possible. I created 2 linked entities for a @manytoone bidirectional relationship (I believe ^^ '). Here is what I want to do, I create a first form that allows me to fill the first entity (the daughter entity) and then I am redirected according to criteria to another page that allows me to fill the parent entity but I Can not find a way to retrieve the id of the entity girl, I tried to pass it through the URL but I can not retrieve it and insert it in the field id_daughterentities.
I enclose the code, I hope that this explanation will allow you to see more clearly.

public function newclientAction(Request $request)
{
    // On crée un objet Advert
    $client = new Clients();

    // J'ai raccourci cette partie, car c'est plus rapide à écrire !
    $form = $this->get('form.factory')->createBuilder(FormType::class, $client)
        ->add('FirstName',      TextType::class)
        ->add('Surname',      TextType::class)
        ->add('Address',      TextType::class)
        ->add('Mail',      EmailType::class, array(
            'required' => false))
        ->add('Mail2',   EmailType::class, array(
            'label' => 'Mail N°2',
            'required' => false
        ))
        ->add('Phone',      TextType::class, array(
            'required' => false))
        ->add('Phone2',     TextType::class, array('label' => 'Phone N°2',
            'required' => false))
        ->add('BirthDate',    BirthdayType::class, array('label' => 'Date of Birth'))
        ->add('Status',     ChoiceType::class, array(
            'choices'  => array(
                'Client' => 'Client',
                'Ex-Client' => 'Ex-Client',
                'Prospect' => 'Prospect'),
        ))
        ->add('Comments',     TextareaType::class, array(
            'required' => false))
        ->add('TypeofBuisness', ChoiceType::class, array(
            'choices'  => array(
                'Blank'=> Null,
                'SE' => 'SE',
                'SA' => 'SE',
                'LLP' => 'LTD',
                'LTD' => 'LTD',
                'Payroll' => 'Payroll'),
                'label' => 'Type of buisness'
        ))
        ->add('save',      SubmitType::class)
        ->getForm()
    ;

    // Si la requête est en POST
    if ($request->isMethod('POST')) {
        // On fait le lien Requête <-> Formulaire
        // À partir de maintenant, la variable $advert contient les valeurs entrées dans le formulaire par le visiteur
        $form->handleRequest($request);

        // On vérifie que les valeurs entrées sont correctes
        // (Nous verrons la validation des objets en détail dans le prochain chapitre)
        if ($form->isValid()) {
            // On enregistre notre objet $advert dans la base de données, par exemple
            $em = $this->getDoctrine()->getManager();
            $em->persist($client);
            $em->flush();

            $request->getSession()->getFlashBag()->add('notice', 'Well regitered.');
            if ($client->getTypeOfBuisness()== 'Payroll')
            {
                return $this->redirectToRoute('pegasus_payroll', array('id' => $client->getId()));
            }
            elseif ($client->getTypeOfBuisness()== 'LTD')
            {
                return $this->redirectToRoute('pegasus_ltd', array('id' => $client->getId()));
            }
            elseif ($client->getTypeOfBuisness()== 'LTD')
            {
                return $this->redirectToRoute('pegasus_se', array('id' => $client->getId()));
            }
            else {
                return $this->redirectToRoute('pegasus_web_homepage', array('id' => $client->getId()));
            }
        }
    }

    // À ce stade, le formulaire n'est pas valide car :
    // - Soit la requête est de type GET, donc le visiteur vient d'arriver sur la page et veut voir le formulaire
    // - Soit la requête est de type POST, mais le formulaire contient des valeurs invalides, donc on l'affiche de nouveau
    return $this->render('PegasusWebBundle:Default:newclient.html.twig', array(
        'form' => $form->createView(),
    ));
}
public function payrollAction(Request $request)
{
    // On crée un objet Advert
    $payroll = new Payroll();

    // J'ai raccourci cette partie, car c'est plus rapide à écrire !
    $form = $this->get('form.factory')->createBuilder(FormType::class, $payroll)
        ->add('EmployerName',      TextType::class, array('label' => 'Employer name'))
        ->add('EmployerSurname',      TextType::class)
        ->add('Address',      TextType::class, array('required' => false))
        ->add('Phone',      TextType::class, array('required' => false))
        ->add('Phone2',     TextType::class, array('label' => 'Phone N°2','required'=> false))
        ->add('Mail',      EmailType::class, array('required' => false))
        ->add('Mail2',   EmailType::class, array('label' => 'Mail N°2','required'=> false ))
        ->add('ContactName',      TextType::class, array('required' => false))
        ->add('Payedisctrict',      TextType::class, array('label' => 'PAYE district','required'=> false))
        ->add('Payeaddress',      TextType::class, array('label' => 'PAYE address','required'=> false))
        ->add('Payephone',      TextType::class, array('label' => 'PAYE phone','required'=> false))
        ->add('Payereference',      TextType::class, array('label' => 'PAYE reference','required'=> false))
        ->add('Accref',      TextType::class, array('label' => 'Account reference','required'=> false))
        ->add('Taxereff',      TextType::class, array('label' => 'Tax reference','required'=> false))
        ->add('Comments',     TextareaType::class, array('label' => 'Any comment ?','required'=> false))
        ->add('save',      SubmitType::class)
        ->getForm()
    ;

I tried there to take the id from the url but it's not working, i tried tones of solutions but nothing works .... I really sorry for this stupid question but i'm trying to learn it by my own

    $payroll.clients=$request->query->get('id');

    // Si la requête est en POST
    if ($request->isMethod('POST')) {
        // On fait le lien Requête <-> Formulaire
        // À partir de maintenant, la variable $advert contient les valeurs entrées dans le formulaire par le visiteur
        $form->handleRequest($request);
        $payroll->is

        // On vérifie que les valeurs entrées sont correctes
        // (Nous verrons la validation des objets en détail dans le prochain chapitre)
        if ($form->isValid()) {
            // On enregistre notre objet $advert dans la base de données, par exemple
            $em = $this->getDoctrine()->getManager();
            $em->persist($payroll);
            $em->flush();

            $request->getSession()->getFlashBag()->add('notice', 'Well regitered.');

            return $this->redirectToRoute('pegasus_web_homepage');

        }
    }

    // À ce stade, le formulaire n'est pas valide car :
    // - Soit la requête est de type GET, donc le visiteur vient d'arriver sur la page et veut voir le formulaire
    // - Soit la requête est de type POST, mais le formulaire contient des valeurs invalides, donc on l'affiche de nouveau
    return $this->render('PegasusWebBundle:Default:newclient.html.twig', array(
        'form' => $form->createView(),
    ));
}

/**
 * Payroll
 *
 * @ORM\Table(name="payroll")
 * @ORM\Entity(repositoryClass="Pegasus\WebBundle\Repository\PayrollRepository")
 */
class Payroll
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="Clients", inversedBy="payroll")
     * @ORM\JoinColumn(nullable=false, name="clients_id", referencedColumnName="id")
     */
    private $clients;

     /**
     * Set clients
     *
     * @param \Pegasus\WebBundle\Entity\Clients $clients
     *
     * @return Payroll
     */
    public function setClients(\Pegasus\WebBundle\Entity\Clients $clients )
    {
        $this->clients = $clients;

        return $this;
    }

    /**
     * Get clients
     *
     * @return \Pegasus\WebBundle\Entity\Clients
     */
    public function getClients()
    {
        return $this->clients;
    }

Cause of that i can't validate my form because my foreign key is empty ... :/
Someone can help me ? pls

Body:
First you need the Clients Entity object to persist the doctrine entity, not the integer ID. If you are passing the id in your request, you'll need to either use automatic Dependency Injection, or get the entity from doctrine manually, like so:

$clients = $this->getDoctrine()->getManager()
    ->find('PegasusWebBundle:Clients', $request->query->get('id'));

The next issue is your Payroll form. It needs to be made aware of the Payroll entity (data_class option) and the Clients EntityType association, even if clients is a hidden field. Though it is unclear in your example how you are passing the form data to the new Payroll entity object.

For example using separate GET and POST actions.

/**
 * @Route("/pegasus_payroll/{id}", name="pegasus_payroll", requirements={"id":"\d+"})
 * @Method("GET")
 */
public function payrollAction(Request $request, \Pegasus\WebBundle\Entity\Clients $clients)
{
     $payroll = new Payroll();
     //set the new payroll clients based on the automatic param conversion
     $payroll->setClients($clients);
     $form = $this->createPayrollForm($payroll, ['action' => $this->generateUrl('save_pegasus_payroll')]);
     $form->handleRequest($request);

     return $this->render('PegasusWebBundle:Default:newpayroll.html.twig', [
        'form' => $form->createView(),
     ]);
}

/**
 * @Route("/pegasus_payroll", name="save_pegasus_payroll")
 * @Method("POST")
 */
public function savePayrollAction(Request $request)
{
     //retrieve the entity from the request form data, to validate with the previous form choice(s).
     $em = $this->getDoctrine()->getManager();
     $clients = $em->find('PegasusWebBundle:Clients', $request->request->get('form')['clients']);
     $payroll = new Payroll;
     $payroll->setClients($clients);
     $form = $this->createPayrollForm($payroll);
     $form->handleRequest($request);
     if ($form->isSubmitted() && $form->isValid()) {
         $formPayroll = $form->getData();
         echo $formPayroll->getClients()->getId();
         //the form data is propagated to the $payroll object passed to it
         echo $payroll->getClients()->getId();
         exit;
         //$em->persist($payroll);
         //$em->flush();
         //$this->addFlash('notice', 'Well regitered.');

         //return $this->redirectToRoute('pegasus_web_homepage');
     }

     return $this->render('PegasusWebBundle:Default:newpayroll.html.twig', [
         'form' => $form->createView(),
     ]);
}

/**
 * use a method to store the form so you can use it elsewhere
 * Alternatively create a new FormType class that extends AbstractFormType
 */
private function createPayrollForm(Payroll $payroll, array $options = [])
{
     $options['data_class'] = Payroll::class;

     return $this->get('form.factory')
         ->createBuilder(FormType::class, $payroll, $options)
         //.. you will need to update to match the Payroll entity property name getter/setters names.
         ->add('clients', EntityType::class, [
             'class' => \Pegasus\WebBundle\Entity\Clients::class,
             'multiple' => false, //only a single selection
             'label' => false, //don't display the form field label
             'choice_label' => false, //don't display select options
             'choices' => [$payroll->getClients()], //only available choice
             'attr' => [
                 'style' => 'display:none;' //hide the select box
             ]
        ])
        ->getForm();
}

As a final note, you should take advantage of the automatic Dependency Injection using ParamConverter
It will make your life a lot easier when your controllers have type-hinted what they are requiring, rather than having to manually define evertything.


来源: stackexchange

问:
Searching for the best prescaler (closest integer multiple)
Let's say we have a timer with a counter (cnt) and a prescaler (psc), which triggers clk_freq / div times per second (Hz), where div = cnt * psc and clk_freq is a clock frequency, which is irrelevant. Value range for both counter and prescaler is [1;65536].

Which is the best (quickest) method of picking cnt and psc so that cnt * psc would be as close as possible to some desired_div value?

Example:

```<code>desired_div = 3849586
psc = 251, cnt = 15337, psc * cnt = 3849587, distance = 1
psc = 313, cnt = 12299, distance = 1
psc = 1757, cnt = 2191, distance = 1
psc = 2191, cnt = 1757, distance = 1
psc = 12299, cnt = 313, distance = 1
psc = 15337, cnt = 251, distance = 1
</code>```

The code used to acquire these values (not effective enough):

```<code>int main(int argc, char *argv[])
{
    uint32_t val, cnt, psc;
    if (argc < 2) {
        printf("Usage: %s <u32_value>\n", argv[0]);
        return 1;
    }

    sscanf(argv[1], "%u", &val);
    printf("Searching for %u\n", val);

    uint32_t hlimit = min(65536, val);
    uint32_t llimit = max(1, val / 65536);

    uint32_t minpsc = 0, minredif = 0xFFFFFFFF;

    for (psc = llimit; psc <= hlimit; ++psc) {
        cnt = min(65536, val / psc);

        uint32_t redif = abs(val - cnt * psc);
        if (cnt < 65536) {
            redif = min(redif, abs((cnt + 1) * psc - val));
        }

        if (redif < minredif) {
            minpsc = psc;
            minredif = redif;
        }
        printf("%u %u\n", psc, redif);
    }

    printf("Optimal psc: %u, difference: %u\n", minpsc, minredif);

    return 0;
}
</code>```

答:
not sure how much faster or slower, not calling any libraries so that helps (well other than printf).

```<code>#include <stdio.h>

void fun ( unsigned int x )
{
    unsigned int ra;
    unsigned int rb;
    unsigned int rc;
    unsigned int rd;
    unsigned int min;

    min=0; min--;

    for(ra=1;ra<32768;ra++)
    {
        rb=x/ra;
        if(rb>65536) continue;
if(1)
{
        rc=rb*ra;
        if(rc>x) rd=rc-x;
        else rd=x-rc;
        if(rd<=min)
        {
            printf("%u %u %u\n",ra,rb,rd);
            min=rd;
        }
}
if(1)
{
        rc=(rb+1)*ra;
        if(rc>x) rd=rc-x;
        else rd=x-rc;
        if(rd<=min)
        {
            printf("%u %u %u\n",ra,rb+1,rd);
            min=rd;
        }
}
    }
}
</code>```

for your value the +1 gave the closest results.

```<code>59 65247 13
61 63108 2
122 31554 2
183 21036 2
244 15777 2
251 15337 1
313 12299 1
1757 2191 1
2191 1757 1
12299 313 1
15337 251 1
</code>```

but dont know off hand if that will always be the case (expect not).

You shouldnt need to go past the halfway point as you are just testing the same pairs twice.  ab = ba

ContentLicense: CC BY-SA 3.0

Body:
Let's say we have a timer with a counter (cnt) and a prescaler (psc), which triggers clk_freq / div times per second (Hz), where div = cnt * psc and clk_freq is a clock frequency, which is irrelevant. Value range for both counter and prescaler is [1;65536].

Which is the best (quickest) method of picking cnt and psc so that cnt * psc would be as close as possible to some desired_div value?

Example:

desired_div = 3849586
psc = 251, cnt = 15337, psc * cnt = 3849587, distance = 1
psc = 313, cnt = 12299, distance = 1
psc = 1757, cnt = 2191, distance = 1
psc = 2191, cnt = 1757, distance = 1
psc = 12299, cnt = 313, distance = 1
psc = 15337, cnt = 251, distance = 1

The code used to acquire these values (not effective enough):

int main(int argc, char *argv[])
{
    uint32_t val, cnt, psc;
    if (argc < 2) {
        printf("Usage: %s <u32_value>\n", argv[0]);
        return 1;
    }

    sscanf(argv[1], "%u", &val);
    printf("Searching for %u\n", val);

    uint32_t hlimit = min(65536, val);
    uint32_t llimit = max(1, val / 65536);

    uint32_t minpsc = 0, minredif = 0xFFFFFFFF;

    for (psc = llimit; psc <= hlimit; ++psc) {
        cnt = min(65536, val / psc);

        uint32_t redif = abs(val - cnt * psc);
        if (cnt < 65536) {
            redif = min(redif, abs((cnt + 1) * psc - val));
        }

        if (redif < minredif) {
            minpsc = psc;
            minredif = redif;
        }
        printf("%u %u\n", psc, redif);
    }

    printf("Optimal psc: %u, difference: %u\n", minpsc, minredif);

    return 0;
}

Body:
not sure how much faster or slower, not calling any libraries so that helps (well other than printf).

#include <stdio.h>

void fun ( unsigned int x )
{
    unsigned int ra;
    unsigned int rb;
    unsigned int rc;
    unsigned int rd;
    unsigned int min;

    min=0; min--;

    for(ra=1;ra<32768;ra++)
    {
        rb=x/ra;
        if(rb>65536) continue;
if(1)
{
        rc=rb*ra;
        if(rc>x) rd=rc-x;
        else rd=x-rc;
        if(rd<=min)
        {
            printf("%u %u %u\n",ra,rb,rd);
            min=rd;
        }
}
if(1)
{
        rc=(rb+1)*ra;
        if(rc>x) rd=rc-x;
        else rd=x-rc;
        if(rd<=min)
        {
            printf("%u %u %u\n",ra,rb+1,rd);
            min=rd;
        }
}
    }
}

for your value the +1 gave the closest results.

59 65247 13
61 63108 2
122 31554 2
183 21036 2
244 15777 2
251 15337 1
313 12299 1
1757 2191 1
2191 1757 1
12299 313 1
15337 251 1

but dont know off hand if that will always be the case (expect not).

You shouldnt need to go past the halfway point as you are just testing the same pairs twice.  ab = ba


问:
Using spawn function with NODE_ENV=production
I'm currently trying to run process using spawn. What I am trying to run from shell is the following;

NODE_ENV=production node app/app.js

Here's the code to run that;

```<code>var spawn = require('child_process').spawn;
var start = spawn('NODE_ENV=production',['node','app/app.js']);
</code>```

However, I got the following error;

```<code>events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: spawn ENOENT
    at errnoException (child_process.js:980:11)
    at Process.ChildProcess._handle.onexit (child_process.js:771:34)
</code>```

How can I do that using spawn ?

答:
add shell option worked for me</p>

```<code>gulp.task('xxx', function (callback) {
    process.chdir('xxx/');
    var spawn = require('child_process').spawn;
    var productionEnv = Object.create(process.env);
    // var jekyll = spawn('gulp', ['stylecheck'], {stdio: 'inherit', env: productionEnv});
    var jekyll = spawn('gulp', ['stylecheck'], {stdio: 'inherit', env: productionEnv, shell: true});

    jekyll.on('exit', function (code) {
        console.log(arguments);
    });
});
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm currently trying to run process using spawn. What I am trying to run from shell is the following;

NODE_ENV=production node app/app.js

Here's the code to run that;

var spawn = require('child_process').spawn;
var start = spawn('NODE_ENV=production',['node','app/app.js']);

However, I got the following error;

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: spawn ENOENT
    at errnoException (child_process.js:980:11)
    at Process.ChildProcess._handle.onexit (child_process.js:771:34)

How can I do that using spawn ?

Body:
add shell option worked for me

gulp.task('xxx', function (callback) {
    process.chdir('xxx/');
    var spawn = require('child_process').spawn;
    var productionEnv = Object.create(process.env);
    // var jekyll = spawn('gulp', ['stylecheck'], {stdio: 'inherit', env: productionEnv});
    var jekyll = spawn('gulp', ['stylecheck'], {stdio: 'inherit', env: productionEnv, shell: true});

    jekyll.on('exit', function (code) {
        console.log(arguments);
    });
});


问:
Batch files - number of command line arguments
Just converting some shell scripts into batch files and there is one thing I can't seem to find...and that is a simple count of the number of command line arguments.

eg. if you have:

```<code>myapp foo bar
</code>```

In Shell:

$# -> 2

$* -> foo bar

$0 -> myapp

$1 -> foo

$2 -> bar

In batch

?? -> 2   <---- what command?!

%* -> foo bar

%0 -> myapp

%1 -> foo

%2 -> bar

So I've looked around, and either I'm looking in the wrong spot or I'm blind, but I can't seem to find a way to get a count of number of command line arguments passed in.

Is there a command similar to shell's "$#" for batch files?

ps. the closest i've found is to iterate through the %1s and use 'shift', but I need to refernece %1,%2 etc later in the script so that's no good.

答:
Avoids using either shift or a for cycle at the cost of size and readability.

```<code>@echo off
setlocal EnableExtensions EnableDelayedExpansion
set /a arg_idx=1
set "curr_arg_value="
:loop1
if !arg_idx! GTR 9 goto :done
set curr_arg_label=%%!arg_idx!
call :get_value curr_arg_value !curr_arg_label!
if defined curr_arg_value (
  echo/!curr_arg_label!: !curr_arg_value!
  set /a arg_idx+=1
  goto :loop1
)
:done
set /a cnt=!arg_idx!-1
echo/argument count: !cnt!
endlocal
goto :eof

:get_value
(
  set %1=%2
)
</code>```

Output:

```<code>count_cmdline_args.bat testing more_testing arg3 another_arg

%1: testing
%2: more_testing
%3: arg3
%4: another_arg
argument count: 4
</code>```

EDIT: The "trick" used here involves:

Constructing a string that represents a currently evaluated command-line argument variable (i.e. "%1", "%2" etc.) using a string that contains a percent character (%%) and a counter variable arg_idx on each loop iteration.

Storing that string into a variable curr_arg_label.

Passing both that string (!curr_arg_label!) and a return variable's name (curr_arg_value) to a primitive subprogram get_value.

In the subprogram its first argument's (%1) value is used on the left side of assignment (set) and its second argument's (%2) value on the right. However, when the second subprogram's argument is passed it is resolved into value of the main program's command-line argument by the command interpreter. That is, what is passed is not, for example, "%4" but whatever value the fourth command-line argument variable holds ("another_arg" in the sample usage).

Then the variable given to the subprogram as return variable (curr_arg_value) is tested for being undefined, which would happen if currently evaluated command-line argument is absent. Initially this was a comparison of the return variable's value wrapped in square brackets to empty square brackets (which is the only way I know of testing program or subprogram arguments which may contain quotes and was an overlooked leftover from trial-and-error phase) but was since fixed to how it is now.

ContentLicense: CC BY-SA 2.5

Body:
Just converting some shell scripts into batch files and there is one thing I can't seem to find...and that is a simple count of the number of command line arguments.

eg. if you have:

myapp foo bar

In Shell:

$# -> 2

$* -> foo bar

$0 -> myapp

$1 -> foo

$2 -> bar

In batch

?? -> 2   <---- what command?!

%* -> foo bar

%0 -> myapp

%1 -> foo

%2 -> bar

So I've looked around, and either I'm looking in the wrong spot or I'm blind, but I can't seem to find a way to get a count of number of command line arguments passed in.

Is there a command similar to shell's "$#" for batch files?

ps. the closest i've found is to iterate through the %1s and use 'shift', but I need to refernece %1,%2 etc later in the script so that's no good.

Body:
Avoids using either shift or a for cycle at the cost of size and readability.

@echo off
setlocal EnableExtensions EnableDelayedExpansion
set /a arg_idx=1
set "curr_arg_value="
:loop1
if !arg_idx! GTR 9 goto :done
set curr_arg_label=%%!arg_idx!
call :get_value curr_arg_value !curr_arg_label!
if defined curr_arg_value (
  echo/!curr_arg_label!: !curr_arg_value!
  set /a arg_idx+=1
  goto :loop1
)
:done
set /a cnt=!arg_idx!-1
echo/argument count: !cnt!
endlocal
goto :eof

:get_value
(
  set %1=%2
)

Output:

count_cmdline_args.bat testing more_testing arg3 another_arg

%1: testing
%2: more_testing
%3: arg3
%4: another_arg
argument count: 4

EDIT: The "trick" used here involves:

Constructing a string that represents a currently evaluated command-line argument variable (i.e. "%1", "%2" etc.) using a string that contains a percent character (%%) and a counter variable arg_idx on each loop iteration.

Storing that string into a variable curr_arg_label.

Passing both that string (!curr_arg_label!) and a return variable's name (curr_arg_value) to a primitive subprogram get_value.

In the subprogram its first argument's (%1) value is used on the left side of assignment (set) and its second argument's (%2) value on the right. However, when the second subprogram's argument is passed it is resolved into value of the main program's command-line argument by the command interpreter. That is, what is passed is not, for example, "%4" but whatever value the fourth command-line argument variable holds ("another_arg" in the sample usage).

Then the variable given to the subprogram as return variable (curr_arg_value) is tested for being undefined, which would happen if currently evaluated command-line argument is absent. Initially this was a comparison of the return variable's value wrapped in square brackets to empty square brackets (which is the only way I know of testing program or subprogram arguments which may contain quotes and was an overlooked leftover from trial-and-error phase) but was since fixed to how it is now.


问:
XQuery return text node if it contains given keyword
A test sample of my xml file is shown below:

test.xml

```<code><feed>
  <entry>
    <title>Link ISBN</title>
    <libx:libapp xmlns:libx="http://libx.org/xml/libx2" />
  </entry>
  <entry>
    <title>Link Something</title>
    <libx:module xmlns:libx="http://libx.org/xml/libx2" />
  </entry>
</feed>
</code>```

Now, I want to write an xquery which will find all <entry> elements which have <libx:libapp> as a child. Then, for all such entries return the title if the title contains a given keyword (such as Link). So, in my example xml document the xquery should return "Link ISBN".

My sample xquery is shown below:

samplequery.xq (here doc_name is the xml file shown above and libapp_matchkey is a keyword such as 'Link')

```<code>declare namespace libx='http://libx.org/xml/libx2';
declare variable $doc_name as xs:string external;
declare variable $libpp_matchkey as xs:string external;
let $feeds_doc := doc($doc_name)

for $entry in $feeds_doc/feed/entry
   (: test whether entry has libx:libapp child and has "Link" in its title child :)
   where ($entry/libx:libapp and $entry/title/text()[contains(.,$libapp_matchkey)])
    return $entry/title/text()
</code>```

This xquery is returning null instead of the expected result 'Link ISBN'. Why is that?

答:
I want to write an xquery which will
  find all  elements which have
   as a child. Then, for
  all such entries return the title if
  the title contains a given keyword
  (such as Link).

Just use:

```<code>/*/entry[libx:libapp]/title[contains(.,'Link')]/text()
</code>```

Wrapping this XPath expression in XQuery we get:

```<code>declare namespace libx='http://libx.org/xml/libx2';
/*/entry[libx:libapp]/title[contains(.,'Link')]/text()
</code>```

when applied on the provided XML document:

```<code><feed>
  <entry>
    <title>Link ISBN</title>
    <libx:libapp xmlns:libx="http://libx.org/xml/libx2" />
  </entry>
  <entry>
    <title>Link Something</title>
    <libx:module xmlns:libx="http://libx.org/xml/libx2" />
  </entry>
</feed>
</code>```

the wanted, correct result is produced:

```<code>Link ISBN
</code>```

Body:
A test sample of my xml file is shown below:

test.xml

<feed>
  <entry>
    <title>Link ISBN</title>
    <libx:libapp xmlns:libx="http://libx.org/xml/libx2" />
  </entry>
  <entry>
    <title>Link Something</title>
    <libx:module xmlns:libx="http://libx.org/xml/libx2" />
  </entry>
</feed>

Now, I want to write an xquery which will find all <entry> elements which have <libx:libapp> as a child. Then, for all such entries return the title if the title contains a given keyword (such as Link). So, in my example xml document the xquery should return "Link ISBN".

My sample xquery is shown below:

samplequery.xq (here doc_name is the xml file shown above and libapp_matchkey is a keyword such as 'Link')

declare namespace libx='http://libx.org/xml/libx2';
declare variable $doc_name as xs:string external;
declare variable $libpp_matchkey as xs:string external;
let $feeds_doc := doc($doc_name)

for $entry in $feeds_doc/feed/entry
   (: test whether entry has libx:libapp child and has "Link" in its title child :)
   where ($entry/libx:libapp and $entry/title/text()[contains(.,$libapp_matchkey)])
    return $entry/title/text()

This xquery is returning null instead of the expected result 'Link ISBN'. Why is that?

Body:
I want to write an xquery which will
  find all  elements which have
   as a child. Then, for
  all such entries return the title if
  the title contains a given keyword
  (such as Link).

Just use:

/*/entry[libx:libapp]/title[contains(.,'Link')]/text()

Wrapping this XPath expression in XQuery we get:

declare namespace libx='http://libx.org/xml/libx2';
/*/entry[libx:libapp]/title[contains(.,'Link')]/text()

when applied on the provided XML document:

<feed>
  <entry>
    <title>Link ISBN</title>
    <libx:libapp xmlns:libx="http://libx.org/xml/libx2" />
  </entry>
  <entry>
    <title>Link Something</title>
    <libx:module xmlns:libx="http://libx.org/xml/libx2" />
  </entry>
</feed>

the wanted, correct result is produced:

Link ISBN


问:
WPF get Content of a treeviewitem
I need to check what treeviewitem the user selected everytime it changes. I used the SelectedItemChangedmethod or whatever this is called. It works fine but now I need to do a switch case for every possible treeviewitem. But I can't do that since I have no idea how to get the name of it. I checked on internet but some people said to use treeview.SelectedItem but it returns System.Windows.Controls.TreeViewItem Header: Items.Count:0. I was wondering if I could do that entirely in the .cs code file or if I had to use data binding and such.

Thanks for your help.

EDIT:

Here is how i setup the treeview and the treeviewitems. They are all like the second example.

```<code><TreeView x:Name="treeview" Margin="10,10,0,4" HorizontalAlignment="Left" Width="192" Background="#FFA45353" SelectedItemChanged="treeview_SelectedItemChanged"">
        <TreeViewItem IsExpanded="False">
            <TreeViewItem.Header>
                <StackPanel Orientation="Horizontal">
                    <Image Source="./Resources/smallicons/icon.jpg"/>
                    <TextBlock Text=" Main" FontSize="14"/>
                </StackPanel>
            </TreeViewItem.Header>
            <!--==============================================================================================-->
            <TreeViewItem>
                <TreeViewItem.Header>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="First" Foreground="Black" />
                    </StackPanel>
                </TreeViewItem.Header>
            </TreeViewItem>
            <!--==============================================================================================-->
</code>```

答:
Are you looking for this?

```<code>TreeViewItem selectedNode = (TreeViewItem)treeView.SelectedItem;
string strSelectedNode = selectedNode.Header.ToString();
</code>```

The above snippet assumes a few things though.

By the way, this code is part of

```<code>private void TreeViewItem_Selected(object sender, RoutedEventArgs e)
{
    TreeViewItem selectedNode = (TreeViewItem)treeView.SelectedItem;
    MessageBox.Show(selectedNode.Header.ToString());
}
</code>```

Title: WPF get Content of a treeviewitem

Body:
I need to check what treeviewitem the user selected everytime it changes. I used the SelectedItemChangedmethod or whatever this is called. It works fine but now I need to do a switch case for every possible treeviewitem. But I can't do that since I have no idea how to get the name of it. I checked on internet but some people said to use treeview.SelectedItem but it returns System.Windows.Controls.TreeViewItem Header: Items.Count:0. I was wondering if I could do that entirely in the .cs code file or if I had to use data binding and such.

Thanks for your help.

EDIT:

Here is how i setup the treeview and the treeviewitems. They are all like the second example.

<TreeView x:Name="treeview" Margin="10,10,0,4" HorizontalAlignment="Left" Width="192" Background="#FFA45353" SelectedItemChanged="treeview_SelectedItemChanged"">
        <TreeViewItem IsExpanded="False">
            <TreeViewItem.Header>
                <StackPanel Orientation="Horizontal">
                    <Image Source="./Resources/smallicons/icon.jpg"/>
                    <TextBlock Text=" Main" FontSize="14"/>
                </StackPanel>
            </TreeViewItem.Header>

            <TreeViewItem>
                <TreeViewItem.Header>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="First" Foreground="Black" />
                    </StackPanel>
                </TreeViewItem.Header>
            </TreeViewItem>

Body:
Are you looking for this?

TreeViewItem selectedNode = (TreeViewItem)treeView.SelectedItem;
string strSelectedNode = selectedNode.Header.ToString();

The above snippet assumes a few things though.

By the way, this code is part of

private void TreeViewItem_Selected(object sender, RoutedEventArgs e)
{
    TreeViewItem selectedNode = (TreeViewItem)treeView.SelectedItem;
    MessageBox.Show(selectedNode.Header.ToString());
}


问:
Ionic beautify js file back
I have received one project from my senior and it is uglified. There is no official documentation as well and when I try to check svn, there is only one version (uglified one). I see variable name like e, t, o, r.

I am also just beginner in ionic.

How shall I do? Is there a way that I can beautify back or do I really need to chase them down?

答:
You can beautify the project but that would be just one big mess of "beautified" code. This would be one js file that may be already transpiled down from ES6 or Typescript, that contains all the "rendered" templates and all the application logic along with all the Ionic truckloads of code plus of course all the Cordova code.

=

CHASE THAT mother... DOWN and save yourself from this madness!

Unless this is a job post on reverse engineering, in which case go on.

Title: Ionic beautify js file back


问:
Reference for git status shorthand
Is there a reference for all of the status notations (e.g. AD, MM, ??) output from git status --porcelain? I'm parsing this output and need to make sure I have all the permutations covered. Reading through the git source code, it looks like the output is assembled on the fly rather than templated and I'm not confidant in my ability to find every edge case there.

Here's what I have:

```<code>??: 'untracked',
A: 'staged',
AD: 'staged_deleted',
AM: 'staged_modified',
D: 'deleted',
M: 'modified',
MM: 'staged_modified',
R: 'renamed',
UU: 'conflicted'
</code>```

答:
It's under the Short Format section of git status:

or paths with merge conflicts, X and Y show the modification states of each side of the merge. For paths that do not have merge conflicts, X shows the status of the index, and Y shows the status of the work tree. For untracked paths, XY are ??. Other status codes can be interpreted as follows:

' ' = unmodified

M = modified

A = added

D = deleted

R = renamed

C = copied

U = updated but unmerged

```<code>X          Y     Meaning
-------------------------------------------------
          [MD]   not updated
M        [ MD]   updated in index
A        [ MD]   added to index
D         [ M]   deleted from index
R        [ MD]   renamed in index
C        [ MD]   copied in index
[MARC]           index and work tree matches
[ MARC]     M    work tree changed since index
[ MARC]     D    deleted in work tree
-------------------------------------------------
D           D    unmerged, both deleted
A           U    unmerged, added by us
U           D    unmerged, deleted by them
U           A    unmerged, added by them
D           U    unmerged, deleted by us
A           A    unmerged, both added
U           U    unmerged, both modified
-------------------------------------------------
?           ?    untracked
!           !    ignored
-------------------------------------------------
</code>```

Title: Reference for git status shorthand

Body:
Is there a reference for all of the status notations (e.g. AD, MM, ??) output from git status --porcelain? I'm parsing this output and need to make sure I have all the permutations covered. Reading through the git source code, it looks like the output is assembled on the fly rather than templated and I'm not confidant in my ability to find every edge case there.

Here's what I have:

??: 'untracked',
A: 'staged',
AD: 'staged_deleted',
AM: 'staged_modified',
D: 'deleted',
M: 'modified',
MM: 'staged_modified',
R: 'renamed',
UU: 'conflicted'

Body:
It's under the Short Format section of git status:

or paths with merge conflicts, X and Y show the modification states of each side of the merge. For paths that do not have merge conflicts, X shows the status of the index, and Y shows the status of the work tree. For untracked paths, XY are ??. Other status codes can be interpreted as follows:

' ' = unmodified

M = modified

A = added

D = deleted

R = renamed

C = copied

U = updated but unmerged

X          Y     Meaning
-------------------------------------------------
          [MD]   not updated
M        [ MD]   updated in index
A        [ MD]   added to index
D         [ M]   deleted from index
R        [ MD]   renamed in index
C        [ MD]   copied in index
[MARC]           index and work tree matches
[ MARC]     M    work tree changed since index
[ MARC]     D    deleted in work tree
-------------------------------------------------
D           D    unmerged, both deleted
A           U    unmerged, added by us
U           D    unmerged, deleted by them
U           A    unmerged, added by them
D           U    unmerged, deleted by us
A           A    unmerged, both added
U           U    unmerged, both modified
-------------------------------------------------
?           ?    untracked
!           !    ignored
-------------------------------------------------


问:
Why is a negative index value taken while inserting a new element into an java array?
I was trying out a java code to insert a new element into an array, I understand most of the program except for a line of code: "int newindex = -index-1;". Why does a negative sign used in front of the index?

Here is the full program:

```<code>public class ArrayManipulation2 {

    public static void main(String[] args) {

        int[] array = {6,3,5,2,-9,-5,-1,0};
        Arrays.sort(array);
        printArray(array);

        int index= Arrays.binarySearch(array, 1);
        int newindex = -index-1;

        array = insertElement(array, 1, newindex);
        printArray(array);
    }

    public static void printArray(int[] array){

        for(int i=0; i<array.length; i++){
            if(i!=0){
                System.out.print(", ");
            }
            System.out.print(array[i]);
        }
        System.out.println();

    }

    public static int[] insertElement(int[] orginal, int element, int index){
        int length = orginal.length;
        int[] destination = new int[length+1];
        System.arraycopy(orginal, 0, destination, 0, index);
        destination[index]=element;
        System.arraycopy(orginal, index, destination, index+1, length-index);

        return destination;

    }
}
</code>```

I need to know why the new index is specified as "-index-1"?.

答:
Arrays.binarySearch() returns a negative value if the item isn't already in the array, so that it can distinguish between where the item is if it is there and where it should be if it isn't there.

The code isn't correct without catering for the case where the result is positive.

Body:
I was trying out a java code to insert a new element into an array, I understand most of the program except for a line of code: "int newindex = -index-1;". Why does a negative sign used in front of the index?

Here is the full program:

public class ArrayManipulation2 {

    public static void main(String[] args) {

        int[] array = {6,3,5,2,-9,-5,-1,0};
        Arrays.sort(array);
        printArray(array);

        int index= Arrays.binarySearch(array, 1);
        int newindex = -index-1;

        array = insertElement(array, 1, newindex);
        printArray(array);
    }

    public static void printArray(int[] array){

        for(int i=0; i<array.length; i++){
            if(i!=0){
                System.out.print(", ");
            }
            System.out.print(array[i]);
        }
        System.out.println();

    }

    public static int[] insertElement(int[] orginal, int element, int index){
        int length = orginal.length;
        int[] destination = new int[length+1];
        System.arraycopy(orginal, 0, destination, 0, index);
        destination[index]=element;
        System.arraycopy(orginal, index, destination, index+1, length-index);

        return destination;

    }
}

I need to know why the new index is specified as "-index-1"?.


问:
How can I convert an int number from decimal to binary?
How can I convert an int number from decimal to binary. For example:

```<code>int x=10; // radix 10
</code>```

How can I make another integer has the binary representation of x, such as:

```<code>int y=1010; // radix 2
</code>```

by using c only?

答: Both integers will have the same interior representation, you can however display as binary via Integer.toBinaryString(i)</p>

Body:
How can I convert an int number from decimal to binary. For example:

int x=10; // radix 10

How can I make another integer has the binary representation of x, such as:

int y=1010; // radix 2

by using c only?


问:
TortoiseSVN Tree Conflict: can't choose remote file
Here's the scenario:

User1, Branch1: adds "abc.def"; commits.

User2, Branch2: adds "abc.def" (same file name, but more details in the file); commits.

Now User1 wants to merge the updated version of the "abc.def" file. So (using TortoiseSVN 1.7.10), User1 starts in the Working Copy of Branch1, selects Merge... -> Reintegrate a Branch, then chooses Branch2 and selects Merge. Predictably, a "Tree Conflict" results, with this text:

The last merge operation tried to add the file 'abc.def' from Branch2, but the file was already added locally.
  How do you want to resolve this conflict?

But the only choice is a single button labelled Keep the local file. There is no option to choose the remote file, which is the one that User1 really wants.

What am I doing wrong here, and how do I fix it? More specifically, how do I get User2's version of the file into Branch1?

(Of course, I'm sure User1 could manually delete the file prior to merging, but that obliterates any history that User1 may have wanted to preserve. Plus it's just a clunky workflow, particularly when there are numerous files in this predicament.)

Unfortunately, this scenario isn't even mentioned in the TortoiseSVN documentation on Tree Conflicts

UPDATE:

In addition to choosing "Reintegrate a Branch" I have also tried "Merge a Range of Revisions" and "Merge two different trees". For the latter case, I chose the remote branch (Branch2) as the "Start" and the local branch as the target (Branch1; choosing the Revision prior to the addition of the file.) I got the same result in all cases: Tree Conflict with no option to select the User2 version of the file.

UPDATE #2:

According to the documentation, there should be "a checkbox in the merge progress dialog called Merge non-interactive", which, if unchecked, supposedly opens the "Merge Conflict Callback Dialog" during the Merge. However, I cannot find any such checkbox in the merge process. Where is it?

答:
I was able to merge from one branch to another in version 1.9 of TortoiseSVN with the following procedure.

Setup

With a test repository, I did the following steps:

Create a branch, "first"

Create a file "doc.txt" with contents "FIRST" in the new branch

Add and commit the file to the new branch

Create a branch, "second"

Create a file "doc.txt" with contents "SECOND" in that branch

Add and commit the file to the new branch

So my structure looks like:

```<code>branches/
    first/
        doc.txt => "FIRST"
    second/
        doc.txt => "SECOND"
</code>```

Merging

In this example, my goal is to get the contents of second/doc.txt into the first branch.

Right-click on the first branch folder, and select TortoiseSVN > Merge...

Select "Merge two different trees"

Fill in the "From" box with the URL for /branches/first, and the "To" box with the URL for /branches/second.

(This is where I got tripped up originally - I thought it would be the opposite! The docs explain: "This may sound wrong, but remember that the trunk is the start point to which you want to add the branch changes.")

Hit Next and try a test merge if you want. It should show that "doc.txt" is replaced, with no tree conflicts. For this example the default merge options were fine.

Do the merge and check the contents of first/doc.txt - it should now read "SECOND".

Run an update and then commit the first folder to save the merge to the repository!

Complete log:

Body:
I was able to merge from one branch to another in version 1.9 of TortoiseSVN with the following procedure.

Setup

With a test repository, I did the following steps:

Create a branch, "first"

Create a file "doc.txt" with contents "FIRST" in the new branch

Add and commit the file to the new branch

Create a branch, "second"

Create a file "doc.txt" with contents "SECOND" in that branch

Add and commit the file to the new branch

So my structure looks like:

branches/
    first/
        doc.txt => "FIRST"
    second/
        doc.txt => "SECOND"

Merging

In this example, my goal is to get the contents of second/doc.txt into the first branch.

Right-click on the first branch folder, and select TortoiseSVN > Merge...

Select "Merge two different trees"

Fill in the "From" box with the URL for /branches/first, and the "To" box with the URL for /branches/second.

(This is where I got tripped up originally - I thought it would be the opposite! The docs explain: "This may sound wrong, but remember that the trunk is the start point to which you want to add the branch changes.")

Hit Next and try a test merge if you want. It should show that "doc.txt" is replaced, with no tree conflicts. For this example the default merge options were fine.

Do the merge and check the contents of first/doc.txt - it should now read "SECOND".

Run an update and then commit the first folder to save the merge to the repository!

Complete log:


问:
SQL/SAP HANA SQL DATATYPES
I need to know how can i get an 'E' to appear for each of the columns when the sum of all these columns = 0. I've tried case when <...> then 'E' but i keep getting "SAP DBTech JDBC: [339]: invalid number: not a valid number string 'E'"

i figure its because of the data types, the column seems to be in DOUBLE or INT
Please help. Thanks

```<code>ROUND((EBD."Disagg Charge"*ID."perc_airConditioning"),2) AS "CB_Cooling($)",
ROUND((EBD."Disagg Charge"*ID."perc_refrigeration"),2) AS "CB_Fridges & Freezers($)",
ROUND((EBD."Disagg Charge"*ID."perc_waterHeating"),2) AS "CB_Electric Hot Water($)",
ROUND((EBD."Disagg Charge"*ID."perc_cooking"),2) AS "CB_Cooking($)",
ROUND((EBD."Disagg Charge"*ID."perc_laundry"),2) AS "CB_Laundry & Dishwasher($)",
ROUND((EBD."Disagg Charge"*ID."perc_lighting"),2) AS "CB_Lighting($)",
ROUND((EBD."Disagg Charge"*ID."perc_entertainment"),2) AS "CB_Home Entertainment($)",
ROUND((EBD."Disagg Charge"*ID."perc_pool"),2) AS "CB_Pool Pump($)",
</code>```

答:
The problem you face here is that the output data type needs to be fixed when you write your SQL statement. SQL is statically typed, so the result cannot be DOUBLE for non-zero values and STRING for zero values.

So, if you want to have the described behaviour, making the output column a STRING type is the only option you have here. One consequence of this is that whatever client application reads this result, will not be able to understand that this column is mainly a DOUBLE data type (e.g. formatting becomes a lot harder and further computation likely will require another data type change). If you're comfortable with this, then go ahead...

Here's how such code can look like in SAP HANA:

```<code>with some_data as (
                select 'A' as add_group, 1.2 as mynumber from dummy
    union all   select 'A' as add_group, 4.523 as mynumber from dummy
    union all   select 'A' as add_group, 3.23 as mynumber from dummy
    union all   select 'B' as add_group, 3.5 as mynumber from dummy
    union all   select 'B' as add_group, -1.75 as mynumber from dummy
    union all   select 'B' as add_group, -1.75 as mynumber from dummy
)
select
    add_group, sum(mynumber),
    case
        when (sum (mynumber) = 0.0)
            then 'E'
        else
            to_varchar( sum (mynumber))
    end as err_sum
from
    some_data
group by add_group;

ADD_GROUP   SUM(MYNUMBER)   ERR_SUM
A           8.953           8.953
B           0               E
</code>```

Title: SQL/SAP HANA SQL DATATYPES

Body:
I need to know how can i get an 'E' to appear for each of the columns when the sum of all these columns = 0. I've tried case when <...> then 'E' but i keep getting "SAP DBTech JDBC: [339]: invalid number: not a valid number string 'E'"

i figure its because of the data types, the column seems to be in DOUBLE or INT
Please help. Thanks

ROUND((EBD."Disagg Charge"*ID."perc_airConditioning"),2) AS "CB_Cooling($)",
ROUND((EBD."Disagg Charge"*ID."perc_refrigeration"),2) AS "CB_Fridges & Freezers($)",
ROUND((EBD."Disagg Charge"*ID."perc_waterHeating"),2) AS "CB_Electric Hot Water($)",
ROUND((EBD."Disagg Charge"*ID."perc_cooking"),2) AS "CB_Cooking($)",
ROUND((EBD."Disagg Charge"*ID."perc_laundry"),2) AS "CB_Laundry & Dishwasher($)",
ROUND((EBD."Disagg Charge"*ID."perc_lighting"),2) AS "CB_Lighting($)",
ROUND((EBD."Disagg Charge"*ID."perc_entertainment"),2) AS "CB_Home Entertainment($)",
ROUND((EBD."Disagg Charge"*ID."perc_pool"),2) AS "CB_Pool Pump($)",

Body:
The problem you face here is that the output data type needs to be fixed when you write your SQL statement. SQL is statically typed, so the result cannot be DOUBLE for non-zero values and STRING for zero values.

So, if you want to have the described behaviour, making the output column a STRING type is the only option you have here. One consequence of this is that whatever client application reads this result, will not be able to understand that this column is mainly a DOUBLE data type (e.g. formatting becomes a lot harder and further computation likely will require another data type change). If you're comfortable with this, then go ahead...

Here's how such code can look like in SAP HANA:

with some_data as (
                select 'A' as add_group, 1.2 as mynumber from dummy
    union all   select 'A' as add_group, 4.523 as mynumber from dummy
    union all   select 'A' as add_group, 3.23 as mynumber from dummy
    union all   select 'B' as add_group, 3.5 as mynumber from dummy
    union all   select 'B' as add_group, -1.75 as mynumber from dummy
    union all   select 'B' as add_group, -1.75 as mynumber from dummy
)
select
    add_group, sum(mynumber),
    case
        when (sum (mynumber) = 0.0)
            then 'E'
        else
            to_varchar( sum (mynumber))
    end as err_sum
from
    some_data
group by add_group;

ADD_GROUP   SUM(MYNUMBER)   ERR_SUM
A           8.953           8.953
B           0               E


问:
Pandorable way to reference a column of a filtered dataframe
I have a Dataframe that looks like this:

```<code>>>>df
      Source              Log  Size
0        USB         file.txt   256
1  Bluetooth         song.wav    75
2        USB  spreadsheet.xls   129
</code>```

I want to splice based on column Source and then select only column Log. The following code works but I don't think it's the pandorable way to write it because I've read that it's not proper to use back to back brackets ][.

```<code>df[df['Source'] == 'USB']['Log']
</code>```

Is there a better way to do this?

答:
Probably, the most pandorable way is to use .loc with boolean indexing.

You can use .loc:

```<code>df.loc[df['Source'] =="USB",'Log']
</code>```

Output:

```<code>0           file.txt
2    spreadsheet.xls
Name: Log, dtype: object
</code>```

Or a more readable syntax using .query.

You can use query:

```<code>df.query('Source == "USB"')['Log']
</code>```

Output:

```<code>0           file.txt
2    spreadsheet.xls
Name: Log, dtype: object
</code>```

Body:
I have a Dataframe that looks like this:

>>>df
      Source              Log  Size
0        USB         file.txt   256
1  Bluetooth         song.wav    75
2        USB  spreadsheet.xls   129

I want to splice based on column Source and then select only column Log. The following code works but I don't think it's the pandorable way to write it because I've read that it's not proper to use back to back brackets ][.

df[df['Source'] == 'USB']['Log']

Is there a better way to do this?

Body:
Probably, the most pandorable way is to use .loc with boolean indexing.

You can use .loc:

df.loc[df['Source'] =="USB",'Log']

Output:

0           file.txt
2    spreadsheet.xls
Name: Log, dtype: object

Or a more readable syntax using .query.

You can use query:

df.query('Source == "USB"')['Log']

Output:

0           file.txt
2    spreadsheet.xls
Name: Log, dtype: object


问:
spark saveAsTable permissions
When a spark program writes a table using DataFrame.saveAsTable, it creates the HDFS file permissions as the user who the job is running as. This is as expected, however, I would like to be able to set write permissions to a larger group so that the table may be manipulated manually with a command such as "DROP TABLE" or updated by other users.

How can I set the group HDFS permissions during the table write in spark?

答:
changing permission while running saveAsTable is not possible. you can use hadoop-client library to change the hdfs path permission as shown below.

```<code>import org.apache.hadoop.fs.permission.FsPermission
import org.apache.hadoop.fs.FileSystem
import java.net.URI

val uri = new URI("hdfs://hdfs-namenode:8080/target/path")
val fileSystem = FileSystem.get(uri, new Configuration())
fileSystem.setPermission(new Path(uri), new FsPermission(777: Short))
</code>```

The hadoop client package can be added to the project using the below code in the sbt build file.

```<code>libraryDependencies += "org.apache.hadoop" % "hadoop-client" % "2.7.2"
</code>```

Title: spark saveAsTable permissions

Body:
changing permission while running saveAsTable is not possible. you can use hadoop-client library to change the hdfs path permission as shown below.

import org.apache.hadoop.fs.permission.FsPermission
import org.apache.hadoop.fs.FileSystem
import java.net.URI

val uri = new URI("hdfs://hdfs-namenode:8080/target/path")
val fileSystem = FileSystem.get(uri, new Configuration())
fileSystem.setPermission(new Path(uri), new FsPermission(777: Short))

The hadoop client package can be added to the project using the below code in the sbt build file.

libraryDependencies += "org.apache.hadoop" % "hadoop-client" % "2.7.2"


问:
Click a button that not visible in page source (only in inspect)
I try to click a button whenever the button shows. However when the button shows, in google chrome's page source, the actual URL is not shown. Here's the source:

```<code> <div id="fname2"  style="display:none" > Description1  <br/> <span> Description2    </span></div>

    <div id="fname"><h1 class="ThreeDee"> Preparing Your Links....<br/> Please wait...</h1></div>
    <div id="hata" style="display:none" > Failed to Create Links..  <br/> <span>Please Restart your link Translation . </span></div>
    <div id="vip" style="display:none" > None This Link Download your consent  <br/> <span> More Description1.. </span></div>

</div>
<div id="buton" style="display:none">
  <div class="info-link right" >
    <a href="#">Download</a>
  </div>
</div>
</code>```

# is a link of the current page(it is a hyperlink), when it should be the URL of next page. However when I "inspect" the button after it appears:

```<code><div id="wrapper">
    <div class="main-menu clearfix">

    </div>
<center><a href="http://example.com/" target="_blank" rel="noreferrer" data-ss1496972790="1"> <img src="./images/example.png"></a></center>

      <div class="info-v3 clearfix">
        <div class="info-txt left">

      <div id="fname2" style=""> Created to download Links  <br> <span> Download your Download Push Button  </span></div>

            <div id="fname" style="display: none;"><h1 class="ThreeDee"> Preparing Your Links....<br> Please wait...</h1></div>
            <div id="hata" style="display:none"> Failed to Create Links..  <br> <span>Please Restart your link Translation . </span></div>
            <div id="vip" style="display:none"> None This Link Download your consent  <br> <span> This file is a private Vip our users.. </span></div>

        </div>
        <div id="buton" style="">
          <div class="info-link right">
            <a href="http://thedownloadlink.com" data-ss1496972790="1">Download</a>
          </div>
        </div>

      </div>

          </div>
</code>```

Any idea how to click the button? Thanks!

答:
The link must be a side effect of JS. You can't see the changes made by JS in source code. JS is client-side. It executes on the browser. However, you can see in inspect element.

And source code doesnt show the side-effects of executed JS. It show the page got from the server.

Body:
I try to click a button whenever the button shows. However when the button shows, in google chrome's page source, the actual URL is not shown. Here's the source:

 Description1
  Description2

 Preparing Your Links....
 Please wait...

 Failed to Create Links..
 Please Restart your link Translation .

 None This Link Download your consent
  More Description1..

    Download

# is a link of the current page(it is a hyperlink), when it should be the URL of next page. However when I "inspect" the button after it appears:

 Created to download Links
  Download your Download Push Button

 Preparing Your Links....
 Please wait...

 Failed to Create Links..
 Please Restart your link Translation .

 None This Link Download your consent
  This file is a private Vip our users..

            Download

Any idea how to click the button? Thanks!


问:
Recognizing rectangles in OpenCV Java
I'm trying to crop rectangles out of an image using OpenCV/Java.  I've been somewhat successful finding the lines that make up the rectangular sections I want to crop, but I'm having a hard time finding the best way to do the following:

Connect the segmented lines I've found (see screenshot below) into separate rectangles (lines can be shared by multiple adjacent rectangles)

Determine that a nearly complete rectangle is a rectangle (see broken bottom edge of full rectangle in screenshot, to the left of line #6)

Any guidance is appreciated!

答: I had been using OpenCV's Impgproc.HoughLinesP, which produced the line segments seen in the question's screenshot. I ended up scrapping that path, opting for a combination of Imgproc.findContours, Imgproc.contourArea and Imgproc.boundingRect instead.  This approach worked for me, and allowed me to avoid writing a bunch of recursive line-combining code.

Title: Recognizing rectangles in OpenCV Java


问:
MYSQL Query That Outputs "Prior Transaction Date" Per Customer Transaction
Let's say I have a table that reflects all of the individual purchases customers have made to date (see image below for the output i'm envisioning)

How would I write a query in MYSQL that returned these 2 columns, +:

A column that reflected the purchase date of that customer's purchase made directly prior (and in the case of no prior purchase, a null value)

A column that output a value of "1" for every difference in the two date columns that are greater than 70 days, a value of "0" for differences that are less than 70 days, and a null value for those that don't have a "prior purchase".

I have been working on this for days and I have only gotten it to work when I "GROUP BY" the customer ID's (using a self join that requires one date to be less than the other). I have no idea how i'd do it at the transaction level.

答:
You can use a correlated subquery.  Here is how you get the previous date:

```<code>select p.*,
       (select p2.purchase_date
        from purchases p2
        where p2.customerid = p.customerid and
              p2.purchase_date < p.purchase_date
        order by p2.purchase_date desc
        limit 1
       ) as prev_purchase_date
from purchases p;
</code>```

You can use this as a subquery and then do the calculation for the final column using prev_purchase_date.

Body:
You can use a correlated subquery.  Here is how you get the previous date:

select p.*,
       (select p2.purchase_date
        from purchases p2
        where p2.customerid = p.customerid and
              p2.purchase_date < p.purchase_date
        order by p2.purchase_date desc
        limit 1
       ) as prev_purchase_date
from purchases p;

You can use this as a subquery and then do the calculation for the final column using prev_purchase_date.


问:
How can I trace string creation in Ruby?
In this answer to a separate question, I said that if you do

```<code>name = "Rohit " "Sharma"
</code>```

you don't create two String objects with the contents "Rohit " and "Sharma" that combine to create a new String object with the contents "Rohit Sharma", but that you only create a single String object to start off with.

But it's only a book telling me that, rather than manually verifying it.

How would you be able to log the creation of a String?

I tried using

```<code>set_trace_func proc { |event, file, line, id, binding, classname|
  printf "%8s %s:%-2d %10s %8s\n", event, file, line, id, classname
}

string = "Insert content here"
</code>```

But only got

```<code>c-return -:3  set_trace_func   Kernel
    line -:5
</code>```

And "Programming Ruby 1.9" (the Pickaxe) says that modifying Class#new wouldn't work for strings, as they're constructed without using new.

答:
This doesn't trace string creation as such, but the following suggests that the concatenation occurs before any string objects are created:

The following (I read about this in the Pickaxe, in the section "Behind the Curtain: The Ruby VM") works in YARV - I don't think it'd work in any other implementations of ruby:

```<code>irb(main):003:0> uncompiled_code = 'name = "Rohit " "Sharma"'
=> "name = \"Rohit \" \"Sharma\""
irb(main):004:0> code = RubyVM::InstructionSequence.compile(uncompiled_code)
=> <RubyVM::InstructionSequence:<compiled>@<compiled>>
irb(main):005:0> puts code.disassemble
== disasm: <RubyVM::InstructionSequence:<compiled>@<compiled>>==========
local table (size: 2, argc: 0 [opts: 0, rest: -1, post: 0, block: -1] s1)
[ 2] name
0000 trace            1                                               (   1)
0002 putstring        "Rohit Sharma"
0004 dup
0005 setlocal         name
0007 leave
=> nil
</code>```

Body:
In this answer to a separate question, I said that if you do

name = "Rohit " "Sharma"

you don't create two String objects with the contents "Rohit " and "Sharma" that combine to create a new String object with the contents "Rohit Sharma", but that you only create a single String object to start off with.

But it's only a book telling me that, rather than manually verifying it.

How would you be able to log the creation of a String?

I tried using

set_trace_func proc { |event, file, line, id, binding, classname|
  printf "%8s %s:%-2d %10s %8s\n", event, file, line, id, classname
}

string = "Insert content here"

But only got

c-return -:3  set_trace_func   Kernel
    line -:5

And "Programming Ruby 1.9" (the Pickaxe) says that modifying Class#new wouldn't work for strings, as they're constructed without using new.

Body:
This doesn't trace string creation as such, but the following suggests that the concatenation occurs before any string objects are created:

The following (I read about this in the Pickaxe, in the section "Behind the Curtain: The Ruby VM") works in YARV - I don't think it'd work in any other implementations of ruby:

irb(main):003:0> uncompiled_code = 'name = "Rohit " "Sharma"'
=> "name = \"Rohit \" \"Sharma\""
irb(main):004:0> code = RubyVM::InstructionSequence.compile(uncompiled_code)
=> <RubyVM::InstructionSequence:<compiled>@<compiled>>
irb(main):005:0> puts code.disassemble
== disasm: <RubyVM::InstructionSequence:<compiled>@<compiled>>==========
local table (size: 2, argc: 0 [opts: 0, rest: -1, post: 0, block: -1] s1)
[ 2] name
0000 trace            1                                               (   1)
0002 putstring        "Rohit Sharma"
0004 dup
0005 setlocal         name
0007 leave
=> nil


问:
Converting this to shared pointer and passing it as an argument to another C++ class
I am working on a code with the following framework:

```<code>class IFirstStep // abstract interface
{
public:
    virtual commonMethod1() = 0;
    ...
};

class FirstStepBase : public IFirstStep // Jobs common to all FirstStep's
{
public:
    FirstStepBase() {}
    commonMethod1() override;
    ...
protected:
    CommonMembers;
    void correctSettings()
    {
        somePreparations;
        auto smartPtr = static_cast<std::shared_ptr<IFirstStep>>(this);
        SecondStep secondStep(smartPtr);
        some calculations using secondStep;
        reassignment of some of commonMembers;
    }
};

class FirstStep1 : public FirstStepBase
{
public:
    FirstSiep1(bool fineTune)
    {
        commonMembers = initilizeSettings();
        if (fineTune)
            correctSettings();
    }
private:
    CommonMembers initilizeSettings() {calculate and assign commonMembers;}
};

class FirstStep2 : public FirstStepBase
...
class FirstStepN : public FirstStepBase
...

class SecondStep
{
public:
    SecondStep(std::shared_ptr<IFirstStep> & firstStep) : m_firstStep(firstStep) {}
    some methods which use firstStep and return some results;
    firstStep itself is not changed;
};
</code>```

correctSettings() is perfectly executed correcting all settings for FirstStep1 right, but crashes in MS VS debugger on exit from correctSettings() with the diagnostics:

```<code>File: minkernel\crts\ucrt\src\appcrt\heap\debug_heap.cpp
Line: 888
Expression: _CrtIsValidHeapPointer(block)
</code>```

Looks the problem is caused by casting - code crashes even if exit is carried out just after the casting. Other types of casting, including pointer casts, were not accepted by the MS VS compiler. However, the thing works flawlessly if correctSettings() is changed as follows and an appropriate constructor is added to FirstStepBase

```<code>void correctSettings()
{
    std::shared_ptr<IFirstStep> smartPtr
        = <std::make_shared<FirstStepBase>>(commonMembers);
    SecondStep secondStep(smartPtr);
    some calculations using secondStep;
    reassignment of some of commonMembers;
}
</code>```

I would greatly appreciate an explanation of why the first approach fails and is it possible at all to utilize in the code this pointer rather than to generate an additional FirstStepBase object? Please, assume that there is no possibility to change interface to the SecondStep.
Thank you.

答: "this" is casted as a shared pointer, but in this case isn't it the raw pointer</p>

Body:
I am working on a code with the following framework:

class IFirstStep // abstract interface
{
public:
    virtual commonMethod1() = 0;
    ...
};

class FirstStepBase : public IFirstStep // Jobs common to all FirstStep's
{
public:
    FirstStepBase() {}
    commonMethod1() override;
    ...
protected:
    CommonMembers;
    void correctSettings()
    {
        somePreparations;
        auto smartPtr = static_cast<std::shared_ptr<IFirstStep>>(this);
        SecondStep secondStep(smartPtr);
        some calculations using secondStep;
        reassignment of some of commonMembers;
    }
};

class FirstStep1 : public FirstStepBase
{
public:
    FirstSiep1(bool fineTune)
    {
        commonMembers = initilizeSettings();
        if (fineTune)
            correctSettings();
    }
private:
    CommonMembers initilizeSettings() {calculate and assign commonMembers;}
};

class FirstStep2 : public FirstStepBase
...
class FirstStepN : public FirstStepBase
...

class SecondStep
{
public:
    SecondStep(std::shared_ptr<IFirstStep> & firstStep) : m_firstStep(firstStep) {}
    some methods which use firstStep and return some results;
    firstStep itself is not changed;
};

correctSettings() is perfectly executed correcting all settings for FirstStep1 right, but crashes in MS VS debugger on exit from correctSettings() with the diagnostics:

File: minkernel\crts\ucrt\src\appcrt\heap\debug_heap.cpp
Line: 888
Expression: _CrtIsValidHeapPointer(block)

Looks the problem is caused by casting - code crashes even if exit is carried out just after the casting. Other types of casting, including pointer casts, were not accepted by the MS VS compiler. However, the thing works flawlessly if correctSettings() is changed as follows and an appropriate constructor is added to FirstStepBase

void correctSettings()
{
    std::shared_ptr<IFirstStep> smartPtr
        = <std::make_shared<FirstStepBase>>(commonMembers);
    SecondStep secondStep(smartPtr);
    some calculations using secondStep;
    reassignment of some of commonMembers;
}

I would greatly appreciate an explanation of why the first approach fails and is it possible at all to utilize in the code this pointer rather than to generate an additional FirstStepBase object? Please, assume that there is no possibility to change interface to the SecondStep.
Thank you.


问:
Is GWTTestCase obsolete? Are there better alternatives?
Trying to figure out what's the status of GWTTestCase suite/methodology.

I've read some things which say that GWTTestCase is kind of obsolete. If this is true, then what would be the preferred methodology for client-side testing?

Also, although I haven't tried it myself, someone here says that he tried it, and it takes seconds or tens of seconds to run a single test; is this true? (i.e. is it common to take tens of seconds to run a test with GWTTestCase, or is it more likely a config error on our side, etc)

Do you use any other methodology for GWT client-side testing that has worked well for you?

答:
The problem is that any GWT code has to be compiled to run within a browser. If your code is just Java, you can run in a typical JUnit or TestNG test, and it will run as instantly as you expect.

But consider that a JUnit test must be compiled to .class, and run in the JVM from the test runner main() - though you don't normally invoke this directly, just start it from your build tool or IDE. In the same way, your GWT/Java code must be compiled into JavaScript, and then run in a browser of some kind.

That compilation is what takes time - for a minimal test, running in only one browser (i.e. one permutation), this is going to take a minimum of 10 seconds on most machines (the host page for the GWTTestCase to allow the JVM to tell it which test to run, and get results or stacktraces or timeouts back). Then add in how long the tested component of your project takes to compile, and you should have a good idea of how long that test case will take.

There are a few measures you can take to minimize the time taken, though 10 seconds is pretty much the bare minimum if you need to run in the browser.

Use test suites - these tell the compiler to go ahead and make a single larger module in which to run all of the tests. Downside: if you do anything clever with your modules, joining them into one might have other ramifications.

Use JVM tests - if you are just testing a presenter, and the presenter is pure Java (with a mock vide), then don't mess with running the code in the browser just to test its logic. If you are concerned about differences, consider if the purpose of the test is to make sure the compiler works, or to exercise the logic.


问:
I cannot figure out how to pass a turtle and a screen from one function to another in my main function
I am very new to programming to start. I will try to be clear. This may be not be proper etiquette but I am still curious how I should accomplish what I am trying to do. Any help would be appreciated. Here's my main function.

```<code>def main():

     y = turtlesetup()
     moveturtle(y)

     wn.exitonclick()
</code>```

Here is turtlesetup:

```<code>def turtlesetup():

     t = turtle.Turtle()
     o = turtle.Turtle()
     wn = turtle.Screen()

     t.shape('turtle')
     o.shape('turtle')
     o.color("red")

     starttx = random.randrange(-50,50)
     startty = random.randrange(-50,50)

     startox = random.randrange(-50,50)
     startoy = random.randrange(-50,50)

     o.penup()
     o.setpos(startox,startoy)
     o.pendown()

     t.penup()
     t.setpos(starttx,startty)
     t.pendown()

     return(wn,t,o)
</code>```

And moveturtle:

```<code>def moveturtle(wn,t,o):

     while isInScreen(wn,t,o):
         angle = random.randrange(1, 361)
         angleo = random.randrange(1,361)

         t.right(angle)
         o.right(angleo)

         o.forward(50)
         t.forward(50)
</code>```

After turtlesetup is called, it moves onto moveturtle but I believe I am getting moveturtle() missing 2 required positional arguments: 't' and 'o'
. I believe this is because I need pass the turtle objects and screen object from turtlesetup into moveturtle and I am not doing it correctly. Forgive my unimaginative variables and possibly improper use of functions and the main function. Thanks for you time.

答:
moveturtle takes 3 arguments, but you are only passing it 1: the tuple of 3 elements that was returned by turtlesetup.

You could fix this by calling moveturtle like so:

```<code>moveturtle( y[0], y[1], y[2] )
</code>```

Or:

```<code>moveturtle( *y )
</code>```

Body:
I am very new to programming to start. I will try to be clear. This may be not be proper etiquette but I am still curious how I should accomplish what I am trying to do. Any help would be appreciated. Here's my main function.

def main():

     y = turtlesetup()
     moveturtle(y)

     wn.exitonclick()

Here is turtlesetup:

def turtlesetup():

     t = turtle.Turtle()
     o = turtle.Turtle()
     wn = turtle.Screen()

     t.shape('turtle')
     o.shape('turtle')
     o.color("red")

     starttx = random.randrange(-50,50)
     startty = random.randrange(-50,50)

     startox = random.randrange(-50,50)
     startoy = random.randrange(-50,50)

     o.penup()
     o.setpos(startox,startoy)
     o.pendown()

     t.penup()
     t.setpos(starttx,startty)
     t.pendown()

     return(wn,t,o)

And moveturtle:

def moveturtle(wn,t,o):

     while isInScreen(wn,t,o):
         angle = random.randrange(1, 361)
         angleo = random.randrange(1,361)

         t.right(angle)
         o.right(angleo)

         o.forward(50)
         t.forward(50)

After turtlesetup is called, it moves onto moveturtle but I believe I am getting moveturtle() missing 2 required positional arguments: 't' and 'o'
. I believe this is because I need pass the turtle objects and screen object from turtlesetup into moveturtle and I am not doing it correctly. Forgive my unimaginative variables and possibly improper use of functions and the main function. Thanks for you time.

Body:
moveturtle takes 3 arguments, but you are only passing it 1: the tuple of 3 elements that was returned by turtlesetup.

You could fix this by calling moveturtle like so:

moveturtle( y[0], y[1], y[2] )

Or:

moveturtle( *y )


问:
java basic question
```<code>public static void main( String arg[] )
</code>```

In the above statement, can I use an int array in place of the String array? What happens if I don't put anything in the parenthesis, i.e if I use an empty parenthesis?

答:
No,it produces a runtime error like
Main method not found in class test, please define the main method as:
   public static void main(String[] args)

JAVA is more specific about main method signature, It considers your method as a general method in a class.

Title: java basic question

Body:
public static void main( String arg[] )

In the above statement, can I use an int array in place of the String array? What happens if I don't put anything in the parenthesis, i.e if I use an empty parenthesis?


问:
Why doesn't this SQL statement work?
```
SELECT * FROM table1, table2
WHERE table1.user_id = table2.id
AND table1.content = news
AND table1.content_id = 1
```

that wont work. cant u have two "AND" in a sql statement??

//Tomek

答:
What do table1 and table2 look like? Can you paste a create script?

I would STRONGLY recommend to use the proper JOIN syntax:

select * from table1
inner join table2 on table1.user_id = table2.id
......

what datatypes is "table1.content" ?

You can most definitely have a lot more than just 2 AND statements in a SQL query - any database that really support any of the SQL-xx standards will support this...

OwnerDisplayName: Tomek

LastEditorDisplayName: Graeme Perrow

Title: Why doesn't this SQL statement work?

Body:
SELECT * FROM table1, table2
WHERE table1.user_id = table2.id
AND table1.content = news
AND table1.content_id = 1

that wont work. cant u have two "AND" in a sql statement??

//Tomek


答:
Use Integer.toBinaryString()</p>

```<code>String y = Integer.toBinaryString(10);
</code>```

Title: How can I convert an int number from decimal to binary?

Body:
Use Integer.toBinaryString()

String y = Integer.toBinaryString(10);


答:
You can use waitForKeyElements with jQuery's :visible selector to click the button only once it is displayed.

Something like:

```<code>waitForKeyElements (
    "#button:visible",
    clickButtton
);

function clickButton(jNode) {
jNode.click();
}
</code>```

Title: Click a button that not visible in page source (only in inspect)

Body:
You can use waitForKeyElements with jQuery's :visible selector to click the button only once it is displayed.

Something like:

waitForKeyElements (
    "#button:visible",
    clickButtton
);

function clickButton(jNode) {
jNode.click();
}


问:
Issue with regex in perl script
```<code>processLine('23/05/2017 07:10:58 [6] 00-Always: ACTION=QUERY&Text=iphone%205%20has%20no%20network%2A&Summary=Context&SpellCheck=true&QuerySummary=false&Sort=AutnRank%2BRelevance&Synonym=true&TotalResults=true&MaxResults=10&PrintFields=drereference%2Cdretitle%2Ccontenttype%2Cautnrank%2COPTUS%5FFILTER1%2COPTUS%5FFILTER2%2COPTUS%5FFILTER3%2CCANONICAL%5FURL&Start=1&Predict=false&FieldText=%28MATCH%7BMy%20Optus%20Community%7D%3AOPTUS%5FFILTER1%3AOPTUS%5FFILTER2%3AOPTUS%5FFILTER3%20NOT%20MATCH%7Bsmb%7D%3ACONTEXT%20NOT%20MATCH%7BCustom%5FPromotions%7D%3ADREDBNAME%29%2BOR%2B%28%28MATCH%7BCustom%5FPromotions%7D%3ADREDBNAME%29%2BAND%2B%28BIASVAL%7Biphone%205%20has%20no%20network%2A%2C100%7D%3APromotion%5FKeywords%29%2BAND%2B%28MATCH%7Biphone%205%20has%20no%20network%2A%7D%3APromotion%5FKeywords%29%29&Combine=Simple&Characters=250 (127.0.0.1)');
if (defined $query && defined $ip && $query =~ m!/?a.*?=(\w+)([?&].*(?<=[?&])Text=([^?&]*))?!)
{
        $events++;
        my $action = $1;
        my $terms = uri_unescape($3) || "";
}
</code>```

I am looking to strip iphone%205%20has%20no%20network%2A from Text=iphone%205%20has%20no%20network%2A and store in $3. I tested regex and do not seem find an issue. It prints $3 as Context.

Expectation is $3 outputs value as iphonehasnonetwork

When I pass,

```<code>processLine('25/05/2017 14:48:10 [9] 00-Always: action=Query&text=samsung&databasematch=Help_Support&ResponseFormat=json&_=1495687690880 (127.0.0.1)');
</code>```

It prints $3 as QuerySamsung. This is the expected result.

I am new to Perl, and I am looking to modify this regex and sort this issue out. I have already stripped down my perl script and diagnosed the root problem. This regex looks fine to me after testing individual components of regex in regex101.com

答:
You forgot to add ignore case modifier to your regexp:

```<code>$query =~ m!/?a.*?=(\w+)([?&].*(?<=[?&])Text=([^?&]*))?!i
</code>```

see i in the end?

read more here: https://perldoc.perl.org/perlre.html#Modifiers

Title: Issue with regex in perl script

Body:
processLine('23/05/2017 07:10:58 [6] 00-Always: ACTION=QUERY&Text=iphone%205%20has%20no%20network%2A&Summary=Context&SpellCheck=true&QuerySummary=false&Sort=AutnRank%2BRelevance&Synonym=true&TotalResults=true&MaxResults=10&PrintFields=drereference%2Cdretitle%2Ccontenttype%2Cautnrank%2COPTUS%5FFILTER1%2COPTUS%5FFILTER2%2COPTUS%5FFILTER3%2CCANONICAL%5FURL&Start=1&Predict=false&FieldText=%28MATCH%7BMy%20Optus%20Community%7D%3AOPTUS%5FFILTER1%3AOPTUS%5FFILTER2%3AOPTUS%5FFILTER3%20NOT%20MATCH%7Bsmb%7D%3ACONTEXT%20NOT%20MATCH%7BCustom%5FPromotions%7D%3ADREDBNAME%29%2BOR%2B%28%28MATCH%7BCustom%5FPromotions%7D%3ADREDBNAME%29%2BAND%2B%28BIASVAL%7Biphone%205%20has%20no%20network%2A%2C100%7D%3APromotion%5FKeywords%29%2BAND%2B%28MATCH%7Biphone%205%20has%20no%20network%2A%7D%3APromotion%5FKeywords%29%29&Combine=Simple&Characters=250 (127.0.0.1)');
if (defined $query && defined $ip && $query =~ m!/?a.*?=(\w+)([?&].*(?<=[?&])Text=([^?&]*))?!)
{
        $events++;
        my $action = $1;
        my $terms = uri_unescape($3) || "";
}

I am looking to strip iphone%205%20has%20no%20network%2A from Text=iphone%205%20has%20no%20network%2A and store in $3. I tested regex and do not seem find an issue. It prints $3 as Context.

Expectation is $3 outputs value as iphonehasnonetwork

When I pass,

processLine('25/05/2017 14:48:10 [9] 00-Always: action=Query&text=samsung&databasematch=Help_Support&ResponseFormat=json&_=1495687690880 (127.0.0.1)');

It prints $3 as QuerySamsung. This is the expected result.

I am new to Perl, and I am looking to modify this regex and sort this issue out. I have already stripped down my perl script and diagnosed the root problem. This regex looks fine to me after testing individual components of regex in regex101.com

Body:
You forgot to add ignore case modifier to your regexp:

$query =~ m!/?a.*?=(\w+)([?&].*(?<=[?&])Text=([^?&]*))?!i

see i in the end?

read more here: https://perldoc.perl.org/perlre.html#Modifiers


答: If df is the dataframe and s is the series, df-s would do. Pandas will do broadcasting just like numpy.

Title: Subtract Dataframe using data in series

Body:
I have a pandas.DataFrame with multiple columns of data

Example Dataframe:

Sample_ID, NaX, NaU
1,         1.0, 2.3
2,         3.4, 2.0

Data Series:

Sample_ID: Blank
NaX        0.2
NaU        0.1

Is there a way to subtract the DataFrame with values in the Series?

The end result I am looking for is as follows:
Example Dataframe blank corrected:

Sample_ID, NaX, NaU
1,         0.8, 2.2
2,         3.2, 1.9

Thanks.

Larger Data Series:

Sample_ID,572,,
NaX,3073.333333,,
NaU,126.666667,,
MgX,3081.666667,,
MgU,69.333333,,
AlX,5275.333333,,
AlU,48.333333,,
SiX,554966.6667,,
SiU,366.666667,,
PX,294.866667,,
PU,3.333333,,
SX,0,,
SU,0,,
ClX,153.033333,,
ClU,1.266667,,
ArX,NaN,,
ArU,NaN,,
KX,684.666667,,
KU,13.666667,,
CaX,6771.333333,,
CaU,33.666667,,
ScX,43,,
ScU,12,,
TiX,75.433333,,
TiU,4.166667,,
VX,12.533333,,
VU,3.633333,,
CrX,74.6,,
CrU,3.033333,,
MnX,35.6,,
,...,,
AgX,0,,
AgU,0,,
CdX,0,,
CdU,0,,
SnX,0,,
SnU,0,,
SbX,0,,
SbU,0,,
TeX,0,,
TeU,0,,
IX,0,,
IU,0,,
CsX,0,,
CsU,0,,
BaX,0,,
BaU,0,,
LaX,0,,
LaU,0,,
CeX,0,,
CeU,0,,
SmX,0,,
SmU,0,,
WX,0,,
WU,0,,
HgX,0,,
HgU,0,,
PbX,0,,
PbU,0,,
BiX,0,,
BiU,0,,
Length:,"87,",dtype:,float64

Larger DataFrame:

Sample_ID,NaX,NaU,MgX,MgU,AlX,AlU,SiX,SiU,PX,PU,...,SmX,SmU,WX,WU,HgX,HgU,PbX,PbU,BiX,BiU
6,332,9470,230,2680,110,6257,55,372700,300,1836,...,0,0,0,0,0,0,297,10,0,0
7,332_Repeat,8940,230,2690,110,6199,55,383500,300,1754,...,0,0,0,0,0,0,215,11,0,0
8,346,10470,260,2500,120,7004,56,253300,200,2586,...,0,0,0,0,0,0,676,13,0,0
9,347,2740,160,1530,79,4799,51,521200,300,530.8,...,0,0,0,0,0,0,107.3,8.8,0,0
10,348,5260,190,1749,91,5506,53,448400,300,1143,...,0,0,0,0,0,0,211,10,0,0
11,348_Repeat,5510,190,1795,91,5486,53,447600,300,1138,...,0,0,0,0,0,0,174,10,0,0
17,427,0,0,3484,75,5093,48,529000,300,560,...,0,0,0,0,0,0,0,0,0,0
18,427_Repeat,0,0,3598,76,5096,48,529900,300,557.8,...,0,0,0,0,0,0,0,0,0,0
19,428,3410,140,5602,86,7590,56,562600,300,794.2,...,0,0,0,0,0,0,8.3,7.3,0,0
20,429,0,0,3977,78,5107,49,530300,300,594.6,...,0,0,0,0,0,0,0,0,0,0
21,430,3530,140,5626,88,7944,57,559800,300,899,...,0,0,0,0,0,0,3.8,3.8,0,0
22,447,139200,300,0,0,2473,27,135200,100,432.2,...,0,0,0,0,0,0,0,0,0,0
23,447_Repeat,138900,300,0,0,2504,26,135400,100,440.3,...,0,0,0,0,0,0,0,0,0,0
24,448,141900,400,0,0,1829,26,73970,60,419.7,...,0,0,0,0,0,0,0,0,0,0
25,449,169700,400,0,0,2034,26,40150,40,420.5,...,0,0,0,0,0,0,0,0,0,0
26,567,168400,600,9460,200,1894,52,20560,40,1474,...,0,0,0,0,0,0,1.2,1.2,0,0
27,568,169300,600,3230,190,1455,51,11370,30,1414,...,0,0,0,0,0,0,6.9,6.9,0,0
28,568_Repeat,169400,600,3200,190,1462,51,11340,30,1406,...,0,0,0,0,0,0,5.3,5.3,0,0
35,7320,174700,500,3470,110,8720,48,129100,100,452.7,...,0,0,0,0,0,0,19,8.2,0,0
36,7323,176500,500,0,0,4928,51,71390,80,572.8,...,0,0,0,0,0,0,17.2,8.1,0,0
37,7326,56390,220,26440,110,24600,60,320900,200,242.1,...,0,0,0,0,0,0,22.3,7.8,0,0

Series and Frame as images:


答:
In your first approach, your this is just a raw pointer, but you tried to cast it into a `shared_pointer, which has different size, different structure.

To solve this, you can try to use boost::enable_shared_from_this, which will allow you to retrieve shared pointer of an object from its own function. Then you don't have to construct another FirstStepBase object.
You can take a look here boost_shared_from_this

Title: Converting this to shared pointer and passing it as an argument to another C++ class