答:
this is similar to Joel Coehoorn's updated query, but still a little different:</p>

```<code>INSERT INTO tablea
SELECT
    min_time, b.term_id, b.config1, b.config_2, 1 as final
FROM
    (SELECT
        term_id, config1, config_2,
        MIN(TIME) AS min_time
    FROM
        tableb
    GROUP BY
        term_id, config1, config_2) b INNER JOIN
    tablea a ON
    b.termid = a.termid AND
    ((b.config1 <> a.config1) OR
    (b.config2 <> a.config2))
</code>```

Title: Insert Only One/the Very First Record Using an Left Join in T-Sql

Body:
I have two tables TableA and TableB. I am trying to join using a leftjoin and insert some records into TableA.

My TableA,

Time                             term_id   config1   config2    final
2017-04-19 23:59:00                 8        147       0        NULL
2017-04-19 23:59:00                 9        87        0        NULL
2017-04-19 23:59:00                10        284       0        NULL

My TableB

Time                             term_id   config1   config2       Claims     Rejects
2017-04-20 00:00:00                8         148       0            568.2        62
2017-04-20 01:00:00                8         148       0            569          62
2017-04-20 02:00:00                8         148       0            572          62
2017-04-20 00:00:00                9         88        0            458          12
2017-04-20 01:00:00                9         88        0            459          12
2017-04-20 02:00:00                9         88        0            462          12
2017-04-20 00:00:00               10         285       0            125          13
2017-04-20 01:00:00               10         285       0            123          13
2017-04-20 02:00:00               10         285       0            117          13
2017-04-20 03:00:00               10         286       1            119          13

My desired output is,

Time                           term_id         config1     config2     final
2017-04-19 23:59:00                 8            147           0        NULL
2017-04-19 23:59:00                 9            87            0        NULL
2017-04-19 23:59:00                 10           284           0        NULL
2017-04-20 00:00:00                 8            148           0         1
2017-04-20 00:00:00                 9            88            0         1
2017-04-20 00:00:00                 10           285           0         1
2017-04-20 03:00:00                 10           286           1         1

I want to insert only the changes in the config1, config2 from TableB into the TableA. So, I did a left join like this, (I don't need Claims and Rejects from TableB)

insert into TableA
select B.[time], B.term_id, B.Config1, B.config2,
        (CASE
        WHEN B.config1 <> A.config1 OR
             B.config2 <> A.config2
        THEN 1
        ELSE 0 END)
from
    TableB B
left join
    (select max([time]) as maxtime, term_id, config1, config2
     from TableA
     group by [time], term_id, config1, config2
    ) as A
on A.term_id = B.term_id

I do not get what I want. How can I change my code to get only the very first changing value inserted into TableA?

Body:
this is similar to Joel Coehoorn's updated query, but still a little different:

INSERT INTO tablea
SELECT
    min_time, b.term_id, b.config1, b.config_2, 1 as final
FROM
    (SELECT
        term_id, config1, config_2,
        MIN(TIME) AS min_time
    FROM
        tableb
    GROUP BY
        term_id, config1, config_2) b INNER JOIN
    tablea a ON
    b.termid = a.termid AND
    ((b.config1 <> a.config1) OR
    (b.config2 <> a.config2))


来源: stackexchange

问:
How Do I Delete Item from Recycler View Holder Class
I am new to android, currently I am working on recyclerView implementations. The issue is I want to delete an item after onCreateContextMenu has been called. I am having some problems getting the right reference to my delete option.

Holder Class

```<code>  public class UploadDrugsHolder extends RecyclerView.ViewHolder  implements View.OnClickListener, View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener {
        //OUR VIEWS
        UploadDrugsAdapter uploadDrugsAdapter;
        TextView drugName;
        ImageView drugImage;
        ItemClickListener itemClickListener;
        ArrayList<UploadedDrugs> drugs;
        public UploadDrugsHolder(View itemView) {
            super(itemView);
            this.drugName= (TextView) itemView.findViewById(R.id.shopName);
            this.drugImage= (ImageView) itemView.findViewById(R.id.model_menu);
            itemView.setOnClickListener(this);
            itemView.setOnCreateContextMenuListener(this);
        }

        public void setItemClickListener(ItemClickListener itemClickListener) {
            this.itemClickListener=itemClickListener;
        }

        @Override
        public void onClick(View v) {
            this.itemClickListener.onItemClick(v,getLayoutPosition());
        }

        @Override
        public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
            MenuItem myActionItem = menu.add("delete");
            myActionItem.setOnMenuItemClickListener(this);
        }

        @Override
        public boolean onMenuItemClick(MenuItem item) {
// what do i need to write here?
            Toast.makeText(itemView.getContext(), "Drug deleted successfully", Toast.LENGTH_SHORT).show();
            return false;
        }

    }
</code>```

答:
I always put adapter and holder in the same file.

You should do like this:

```<code>public class UploadedDrugsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private List<UploadedDrugs> dataList = new ArrayList<>();
    private OnClickUploadedDrugs event;

    public UploadedDrugsAdapter (List<UploadedDrugs> dataList, OnClickUploadedDrugs event) {
        this.dataList = dataList;
        this.event = event;
    }

    public interface OnClickUploadedDrugs{
        void onClickUploadedDrugs(UploadedDrugs uploadedDrugs);
    }

    public void changeDataSet(List<UploadedDrugs> dataSet){
        dataList = dataSet;
        notifyDataSetChanged();
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.your_xml_file, parent, false);

        return new ViewHolderUploadedDrugs(view);
    }

    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        try {
            final UploadedDrugs model = dataList.get(position);
            final ViewHolderUploadedDrugs vh = (ViewHolderUploadedDrugs) holder;

            // configure view values

            //Event
            vh.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(event != null){
                        event.onClickUploadedDrugs(model);
                    }
                }
            });
        }catch (Exception e){
            Log.e(getClass().getSimpleName(), "Erro ao exibir informaçeõs", e);
        }
    }

    @Override
    public int getItemCount() {
        return (null != dataList ? dataList.size() : 0);
    }

    static class ViewHolderUploadedDrugs extends RecyclerView.ViewHolder {

        TextView drugName;
        ImageView drugImage;

        ViewHolderUploadedDrugs(View itemView) {
            super(itemView);
            this.drugName= (TextView) itemView.findViewById(R.id.shopName);
            this.drugImage= (ImageView) itemView.findViewById(R.id.model_menu);
        }
    }

    public List<UploadedDrugs> getDataList() {
        return dataList;
    }

    public void setEvent(OnClickUploadedDrugs event) {
        this.event = event;
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am new to android, currently I am working on recyclerView implementations. The issue is I want to delete an item after onCreateContextMenu has been called. I am having some problems getting the right reference to my delete option.

Holder Class

  public class UploadDrugsHolder extends RecyclerView.ViewHolder  implements View.OnClickListener, View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener {
        //OUR VIEWS
        UploadDrugsAdapter uploadDrugsAdapter;
        TextView drugName;
        ImageView drugImage;
        ItemClickListener itemClickListener;
        ArrayList<UploadedDrugs> drugs;
        public UploadDrugsHolder(View itemView) {
            super(itemView);
            this.drugName= (TextView) itemView.findViewById(R.id.shopName);
            this.drugImage= (ImageView) itemView.findViewById(R.id.model_menu);
            itemView.setOnClickListener(this);
            itemView.setOnCreateContextMenuListener(this);
        }

        public void setItemClickListener(ItemClickListener itemClickListener) {
            this.itemClickListener=itemClickListener;
        }

        @Override
        public void onClick(View v) {
            this.itemClickListener.onItemClick(v,getLayoutPosition());
        }

        @Override
        public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
            MenuItem myActionItem = menu.add("delete");
            myActionItem.setOnMenuItemClickListener(this);
        }

        @Override
        public boolean onMenuItemClick(MenuItem item) {
// what do i need to write here?
            Toast.makeText(itemView.getContext(), "Drug deleted successfully", Toast.LENGTH_SHORT).show();
            return false;
        }

    }

Body:
I always put adapter and holder in the same file.

You should do like this:

public class UploadedDrugsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private List<UploadedDrugs> dataList = new ArrayList<>();
    private OnClickUploadedDrugs event;

    public UploadedDrugsAdapter (List<UploadedDrugs> dataList, OnClickUploadedDrugs event) {
        this.dataList = dataList;
        this.event = event;
    }

    public interface OnClickUploadedDrugs{
        void onClickUploadedDrugs(UploadedDrugs uploadedDrugs);
    }

    public void changeDataSet(List<UploadedDrugs> dataSet){
        dataList = dataSet;
        notifyDataSetChanged();
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.your_xml_file, parent, false);

        return new ViewHolderUploadedDrugs(view);
    }

    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        try {
            final UploadedDrugs model = dataList.get(position);
            final ViewHolderUploadedDrugs vh = (ViewHolderUploadedDrugs) holder;

            // configure view values

            //Event
            vh.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(event != null){
                        event.onClickUploadedDrugs(model);
                    }
                }
            });
        }catch (Exception e){
            Log.e(getClass().getSimpleName(), "Erro ao exibir informaçeõs", e);
        }
    }

    @Override
    public int getItemCount() {
        return (null != dataList ? dataList.size() : 0);
    }

    static class ViewHolderUploadedDrugs extends RecyclerView.ViewHolder {

        TextView drugName;
        ImageView drugImage;

        ViewHolderUploadedDrugs(View itemView) {
            super(itemView);
            this.drugName= (TextView) itemView.findViewById(R.id.shopName);
            this.drugImage= (ImageView) itemView.findViewById(R.id.model_menu);
        }
    }

    public List<UploadedDrugs> getDataList() {
        return dataList;
    }

    public void setEvent(OnClickUploadedDrugs event) {
        this.event = event;
    }
}


问:
Selection popping up when clicking the element on phones
Hello and thank you for passing by.

Here's what I mean: https://puu.sh/ymLzt/89944a9ec9.gif

And here´s the source code: https://codepen.io/anon/pen/rYzpEw

Here's the .css for the play button:

```<code>#pButton{
    height: 50px;
    width: 50px;
    border: none;
  z-index: -1;
    background-size: 100% 100%;
    background-repeat: no-repeat;
    background-position: center;
    outline:none;
    display: table;
  margin: 0 auto;
      cursor: url(https://shopify.github.io/draggable/assets/img/cursor-rock.png),pointer;
  padding: none;
}
</code>```

It only happens on phone screens.

Any ideas on what it can be? Thank you.

答:
This is a correct answer, cursor: pointer; is really causing
  highlight. But -webkit-tap-highlight-color: transparent; is more
  universal solution.

Fixed it with this.

The issue was the highlighting of the elements

Body:
Hello and thank you for passing by.

Here's what I mean: https://puu.sh/ymLzt/89944a9ec9.gif

And here´s the source code: https://codepen.io/anon/pen/rYzpEw

Here's the .css for the play button:

#pButton{
    height: 50px;
    width: 50px;
    border: none;
  z-index: -1;
    background-size: 100% 100%;
    background-repeat: no-repeat;
    background-position: center;
    outline:none;
    display: table;
  margin: 0 auto;
      cursor: url(https://shopify.github.io/draggable/assets/img/cursor-rock.png),pointer;
  padding: none;
}

It only happens on phone screens.

Any ideas on what it can be? Thank you.


问:
Symfony Dynamically Adding Entry to Form Leads to TypeError
In my form, I have a collection of forms embedded. The idea is to use jQuery to add or remove an entry (from the collection). The jQuery part works fine. I know for a fact that my entities are fine as well, because I used EasyAdminBundle before to realise this functionality and that was no problem.

The problem is: When I add an entry via jQuery and submit the form, I get the following error:

Type error: Return value of App\Entity\Answer::getIsCorrect() must be of the type boolean, null returned

This is the parent form:

```<code><?php

namespace App\Form\Type;

use App\Entity\Question;
use App\Form\DataTransformer\TagTransformer;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;

class QuestionType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('answers', CollectionType::class, array(
                    'entry_type' => AnswerType::class,
                    'allow_add' => true,
                    'allow_delete' => true,
                    'delete_empty' => true,
                    'entry_options' => ['label' => false],
                    'prototype' => true,
                    'label' => false,
                    'by_reference' => false,
                )
            )
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(
            array(
                'data_class' => Question::class
            )
        );
    }
}
</code>```

This is the collection form:

```<code><?php

namespace App\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use App\Entity\Answer;
use Symfony\Component\Validator\Constraints\Choice;

class AnswerType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add(
                'isCorrect',
                CheckboxType::class,
                ['required' => false]
            )
            ->add(
                'text',
                 TextType::class,
                ['label' => false, 'required' => false]
            );
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => Answer::class
        ));
    }
}
</code>```

Here are some facts:

Symfony 3.3 used

Entities work fine

jQuery works fine

Forms with fixtures can be submitted fine

The whole setup is largely inspired by this tutorial

I read that there could be a problem when allow_add is not true. But that is explicitly set. Removing entries works fine. delete_empty is ignored as well.

My first thought was that there is a problem because the form fields are not duplicated correctly by jQuery, e.g. wrong name attribute used. Especially checkboxes can sometimes be problematic. But even if I only use a text field, the issue persists. As an example:

Generated with Twig:

```<code><input type="checkbox" id="question_answers_2_isCorrect" name="question[answers][2][isCorrect]" value="1">
</code>```

Result from jQuery:

```<code><input type="checkbox" id="question_answers_3_isCorrect" name="question[answers][3][isCorrect]" value="1">
</code>```

Now, here comes the kicker: In the Stack Trace, you can clearly see that the form has the data in the first place, but it gets lost.

```<code>Symfony\Component\Debug\Exception\FatalThrowableError:
Type error: Return value of App\Entity\Answer::getIsCorrect() must be of the type boolean, null returned

  at src/Entity/Answer.php:82
  at App\Entity\Answer->getIsCorrect()
     (vendor/symfony/property-access/PropertyAccessor.php:487)
  at Symfony\Component\PropertyAccess\PropertyAccessor->readProperty(array(object(Answer)), 'isCorrect')
     (vendor/symfony/property-access/PropertyAccessor.php:410)
  at Symfony\Component\PropertyAccess\PropertyAccessor->readPropertiesUntil(array(object(Answer)), object(PropertyPath), 1, true)
     (vendor/symfony/property-access/PropertyAccessor.php:179)
  at Symfony\Component\PropertyAccess\PropertyAccessor->getValue(object(Answer), object(PropertyPath))
     (vendor/symfony/form/Extension/Core/DataMapper/PropertyPathMapper.php:92)
  at Symfony\Component\Form\Extension\Core\DataMapper\PropertyPathMapper->mapFormsToData(object(RecursiveIteratorIterator), object(Answer))
     (vendor/symfony/form/Form.php:630)

// Here the data is suddenly lost

  at Symfony\Component\Form\Form->submit(array(), true)
     (vendor/symfony/form/Form.php:574)
  at Symfony\Component\Form\Form->submit(array(array('text' => 'this gets lost')), true)
     (vendor/symfony/form/Form.php:574)

// Here the data comes in, now see above ↑

at Symfony\Component\Form\Form->submit(array('answers' => array(array('isCorrect' => '1', 'text' => 'foo'), array('text' => 'bar'), array('text' => 'baz'), array('text' => 'this gets lost'))), true)
     (vendor/symfony/form/Extension/HttpFoundation/HttpFoundationRequestHandler.php:113)
  at Symfony\Component\Form\Extension\HttpFoundation\HttpFoundationRequestHandler->handleRequest(object(Form), object(Request))
     (vendor/symfony/form/Form.php:500)
  at Symfony\Component\Form\Form->handleRequest(object(Request))
     (src/Controller/QuestionsController.php:79)
</code>```

Here's the entity Answer:

```<code>class Answer
{
    /**
     * @var
     * @ORM\Column(type="string")
     */
    protected $text;

    /**
     * @var
     * @ORM\Column(type="boolean")
     */
    protected $isCorrect;

    /**
     * @var
     * @ORM\ManyToOne(targetEntity="Question", inversedBy="answers", cascade={"persist"})
     */
    protected $question;

    /**
     * @return mixed
     */
    public function getText() : string
    {
        return $this->text;
    }

    /**
     * @param mixed $text
     */
    public function setText(string $text) : void
    {
        $this->text = $text;
    }

    /**
     * @return mixed
     */
    public function getIsCorrect() : bool
    {
        return $this->isCorrect;
    }

    /**
     * @param bool $isCorrect
     */
    public function setIsCorrect(bool $isCorrect) : void
    {
        $this->isCorrect = $isCorrect;
    }
}
</code>```

答:
This is the culprit

```<code>/**
 * @return mixed
 */
public function getIsCorrect() : bool
{
    return $this->isCorrect;
}
</code>```

Change it to

```<code>/**
 * @return mixed
 */
public function getIsCorrect() : bool
{
    return boolval($this->isCorrect);
}
</code>```

EDIT: ok I'll try to be a little more informative. Teh reason you're getting errors like these is because typehints in your methods are false. For instance your getIsCorrect method says it returns bool but in reality it also returns null when your isCorrect property isn't initialized. Personally I'd recommend  you remove the typehints for good and just keep phpdoc, but if you really need them then try initializing your fields in your entity's constructor and setting a default db value.

Body:
In my form, I have a collection of forms embedded. The idea is to use jQuery to add or remove an entry (from the collection). The jQuery part works fine. I know for a fact that my entities are fine as well, because I used EasyAdminBundle before to realise this functionality and that was no problem.

The problem is: When I add an entry via jQuery and submit the form, I get the following error:

Type error: Return value of App\Entity\Answer::getIsCorrect() must be of the type boolean, null returned

This is the parent form:

<?php

namespace App\Form\Type;

use App\Entity\Question;
use App\Form\DataTransformer\TagTransformer;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;

class QuestionType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('answers', CollectionType::class, array(
                    'entry_type' => AnswerType::class,
                    'allow_add' => true,
                    'allow_delete' => true,
                    'delete_empty' => true,
                    'entry_options' => ['label' => false],
                    'prototype' => true,
                    'label' => false,
                    'by_reference' => false,
                )
            )
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(
            array(
                'data_class' => Question::class
            )
        );
    }
}

This is the collection form:

<?php

namespace App\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use App\Entity\Answer;
use Symfony\Component\Validator\Constraints\Choice;

class AnswerType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add(
                'isCorrect',
                CheckboxType::class,
                ['required' => false]
            )
            ->add(
                'text',
                 TextType::class,
                ['label' => false, 'required' => false]
            );
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => Answer::class
        ));
    }
}

Here are some facts:

Symfony 3.3 used

Entities work fine

jQuery works fine

Forms with fixtures can be submitted fine

The whole setup is largely inspired by this tutorial

I read that there could be a problem when allow_add is not true. But that is explicitly set. Removing entries works fine. delete_empty is ignored as well.

My first thought was that there is a problem because the form fields are not duplicated correctly by jQuery, e.g. wrong name attribute used. Especially checkboxes can sometimes be problematic. But even if I only use a text field, the issue persists. As an example:

Generated with Twig:

<input type="checkbox" id="question_answers_2_isCorrect" name="question[answers][2][isCorrect]" value="1">

Result from jQuery:

<input type="checkbox" id="question_answers_3_isCorrect" name="question[answers][3][isCorrect]" value="1">

Now, here comes the kicker: In the Stack Trace, you can clearly see that the form has the data in the first place, but it gets lost.

Symfony\Component\Debug\Exception\FatalThrowableError:
Type error: Return value of App\Entity\Answer::getIsCorrect() must be of the type boolean, null returned

  at src/Entity/Answer.php:82
  at App\Entity\Answer->getIsCorrect()
     (vendor/symfony/property-access/PropertyAccessor.php:487)
  at Symfony\Component\PropertyAccess\PropertyAccessor->readProperty(array(object(Answer)), 'isCorrect')
     (vendor/symfony/property-access/PropertyAccessor.php:410)
  at Symfony\Component\PropertyAccess\PropertyAccessor->readPropertiesUntil(array(object(Answer)), object(PropertyPath), 1, true)
     (vendor/symfony/property-access/PropertyAccessor.php:179)
  at Symfony\Component\PropertyAccess\PropertyAccessor->getValue(object(Answer), object(PropertyPath))
     (vendor/symfony/form/Extension/Core/DataMapper/PropertyPathMapper.php:92)
  at Symfony\Component\Form\Extension\Core\DataMapper\PropertyPathMapper->mapFormsToData(object(RecursiveIteratorIterator), object(Answer))
     (vendor/symfony/form/Form.php:630)

// Here the data is suddenly lost

  at Symfony\Component\Form\Form->submit(array(), true)
     (vendor/symfony/form/Form.php:574)
  at Symfony\Component\Form\Form->submit(array(array('text' => 'this gets lost')), true)
     (vendor/symfony/form/Form.php:574)

// Here the data comes in, now see above ↑

at Symfony\Component\Form\Form->submit(array('answers' => array(array('isCorrect' => '1', 'text' => 'foo'), array('text' => 'bar'), array('text' => 'baz'), array('text' => 'this gets lost'))), true)
     (vendor/symfony/form/Extension/HttpFoundation/HttpFoundationRequestHandler.php:113)
  at Symfony\Component\Form\Extension\HttpFoundation\HttpFoundationRequestHandler->handleRequest(object(Form), object(Request))
     (vendor/symfony/form/Form.php:500)
  at Symfony\Component\Form\Form->handleRequest(object(Request))
     (src/Controller/QuestionsController.php:79)

Here's the entity Answer:

class Answer
{
    /**
     * @var
     * @ORM\Column(type="string")
     */
    protected $text;

    /**
     * @var
     * @ORM\Column(type="boolean")
     */
    protected $isCorrect;

    /**
     * @var
     * @ORM\ManyToOne(targetEntity="Question", inversedBy="answers", cascade={"persist"})
     */
    protected $question;

    /**
     * @return mixed
     */
    public function getText() : string
    {
        return $this->text;
    }

    /**
     * @param mixed $text
     */
    public function setText(string $text) : void
    {
        $this->text = $text;
    }

    /**
     * @return mixed
     */
    public function getIsCorrect() : bool
    {
        return $this->isCorrect;
    }

    /**
     * @param bool $isCorrect
     */
    public function setIsCorrect(bool $isCorrect) : void
    {
        $this->isCorrect = $isCorrect;
    }
}

Body:
This is the culprit

/**
 * @return mixed
 */
public function getIsCorrect() : bool
{
    return $this->isCorrect;
}

Change it to

/**
 * @return mixed
 */
public function getIsCorrect() : bool
{
    return boolval($this->isCorrect);
}

EDIT: ok I'll try to be a little more informative. Teh reason you're getting errors like these is because typehints in your methods are false. For instance your getIsCorrect method says it returns bool but in reality it also returns null when your isCorrect property isn't initialized. Personally I'd recommend  you remove the typehints for good and just keep phpdoc, but if you really need them then try initializing your fields in your entity's constructor and setting a default db value.


问:
Equal columns in Bootstrap's pagination when using a form input
Consider this example pagination:

```<code><nav aria-label="Pagination" class="text-center">
  <ul class="pagination pagination-sm">
    <li><a href="#">Previous</a></li>
    <li class="disabled">
      <span>Custom content here with <input value="input"></span>
    </li>
    <li><a href="#">Next</a></li>
  </ul>
</nav>
</code>```

I would like to have an input type inside one of the columns. However having anything but text there leads to columns not being of equal height:

What CSS I need to apply to have all columns equal? This example is available on jsFiddle as well.

Update

With .pagination a, .pagination span {height: 40px} I got all columns equally high, however I cannot get the texts inside to appear in one line though.

答:
You can overide with a bit of css

CSS:

```<code>.pagination{display:inline-flex}
.pagination > li > a,
.pagination > li > span{
     height:100%; display:flex; align-items:center
}
</code>```

Bootply: https://www.bootply.com/YTnctq4PIg

Body:
Consider this example pagination:

Previous

      Custom content here with <input value="input">

Next

I would like to have an input type inside one of the columns. However having anything but text there leads to columns not being of equal height:

What CSS I need to apply to have all columns equal? This example is available on jsFiddle as well.

Update

With .pagination a, .pagination span {height: 40px} I got all columns equally high, however I cannot get the texts inside to appear in one line though.

Body:
You can overide with a bit of css

CSS:

.pagination{display:inline-flex}
.pagination > li > a,
.pagination > li > span{
     height:100%; display:flex; align-items:center
}

Bootply: https://www.bootply.com/YTnctq4PIg

ContentLicense: CC BY-SA 4.0


问:
Google sheets, if statement multiple conditions
Trying to make an if statement that will return 4 outcomes based on the contents of the cell

If the cell is "Yes", "No", "NA", "Unknown", to return 0, 1, 2, 3 respectively.

I can use  If(A1="Yes", 0,1)  but not sure how to handle the other conditions

答:
The concept you are asking for in the Google Docs Editors help center is called "nested function". This concept refers to using a function as a parameter of another function.

The syntax for IF is

```<code>IF(logical_expression, value_if_true, value_if_false)
</code>```

You could replace logical_expression, value_if_true and/or value_if_false with another IF. For this specific case, try

```<code>=IF(A1="Yes",0,IF(A1="No",1,IF(A1="NA",2,IF(A1="Unknown",3,NA())))
</code>```

#N/A will be returned if A1 contains an unexpected value.

Reference

Add formulas and functions to a spreadsheet

Body:
The concept you are asking for in the Google Docs Editors help center is called "nested function". This concept refers to using a function as a parameter of another function.

The syntax for IF is

IF(logical_expression, value_if_true, value_if_false)

You could replace logical_expression, value_if_true and/or value_if_false with another IF. For this specific case, try

=IF(A1="Yes",0,IF(A1="No",1,IF(A1="NA",2,IF(A1="Unknown",3,NA())))

#N/A will be returned if A1 contains an unexpected value.

Reference

Add formulas and functions to a spreadsheet


问:
How to simplify Environment.NewLine()?
Hey StackOverflow users,

I'm working on a discord bot in C#. To keep my code clean, I'd like to use a function that adds more lines to a string.

An example of what I want to avoid is:

```<code>Description = $"Hey { username }! {Environment.NewLine + Environment.NewLine}{funMsg[randomNumber]}",
</code>```

What I tried to do is:

```<code>public string inertlines(int i)
    {
        string st = "";
        for (int c = 0; c < i; c++)
        {
            st += Environment.NewLine();
        }
        return st;
    }
</code>```

The visual studio compiler gives an error regarding the NewLine statement. "Non-invocable member 'Environment.NewLine' cannot be used like a method.

I'd really appreciate it if someone could tell me what do to avoid this and/or another method that could replace the Environment.NewLine() methode.

Finally I want to clearify that this is NOT a duplicate. For new programmers this post does explain alot more of a more specific problem. The post that got compared to mine had the same SOLUTION, however, not the same problem. It's even a whole different SUBJECT. On top of that, starters could copy the solution to easialy add extra lines to a string or understand how functions work better, as Environment.NewLine() is a well known and easy to understand methode under newer programmers.

Thanks in advance,
Jelle

答:
The answer turns out to be really simple

```<code>public string insertlines(int i)
    {
        string st = "";
        for (int c = 0; c < i; c++)
        {
//Environment.NewLine shouldn't have "()" in it's own class

            st += Environment.NewLine;
        }
        return st;
    }
</code>```

The usage of this to create white lines in a string would be:

```<code>Console.WriteLine($"I want 2 {insertLines(2)} blanc lines under the 2"});
</code>```

or to simplify that example:

```<code>Console.WriteLine("I want 2 " + insertLines(2) + " blanc lines under the 2");
</code>```

For anyone reading this, please just use "\n" for new lines in a string. I've learned alot more about coding and think my question and answer were not the best, most helpful ones.

Title: How to simplify Environment.NewLine()?

Body:
Hey StackOverflow users,

I'm working on a discord bot in C#. To keep my code clean, I'd like to use a function that adds more lines to a string.

An example of what I want to avoid is:

Description = $"Hey { username }! {Environment.NewLine + Environment.NewLine}{funMsg[randomNumber]}",

What I tried to do is:

public string inertlines(int i)
    {
        string st = "";
        for (int c = 0; c < i; c++)
        {
            st += Environment.NewLine();
        }
        return st;
    }

The visual studio compiler gives an error regarding the NewLine statement. "Non-invocable member 'Environment.NewLine' cannot be used like a method.

I'd really appreciate it if someone could tell me what do to avoid this and/or another method that could replace the Environment.NewLine() methode.

Finally I want to clearify that this is NOT a duplicate. For new programmers this post does explain alot more of a more specific problem. The post that got compared to mine had the same SOLUTION, however, not the same problem. It's even a whole different SUBJECT. On top of that, starters could copy the solution to easialy add extra lines to a string or understand how functions work better, as Environment.NewLine() is a well known and easy to understand methode under newer programmers.

Thanks in advance,
Jelle

Body:
The answer turns out to be really simple

public string insertlines(int i)
    {
        string st = "";
        for (int c = 0; c < i; c++)
        {
//Environment.NewLine shouldn't have "()" in it's own class

            st += Environment.NewLine;
        }
        return st;
    }

The usage of this to create white lines in a string would be:

Console.WriteLine($"I want 2 {insertLines(2)} blanc lines under the 2"});

or to simplify that example:

Console.WriteLine("I want 2 " + insertLines(2) + " blanc lines under the 2");

For anyone reading this, please just use "\n" for new lines in a string. I've learned alot more about coding and think my question and answer were not the best, most helpful ones.


问:
R help - function on multiple data frame columns
I would like to use a function to repeat a set of procedures on four columns in a data frame. Ultimately I need a long data frame containing all the output. Here is my data frame:

```<code>> sample_data
# A tibble: 10 x 7
      REVENUEID AMOUNT  YEAR REPORT_CODE PAYMENT_METHOD INBOUND_CHANNEL  AMOUNT_CAT
          <chr>  <dbl> <chr>       <chr>          <chr>           <chr>      <fctr>
 1 rev-24985629     30  FY18           S          Check            Mail     [25,50)
 2 rev-22812413      1  FY16           Q          Other      Canvassing   [0.01,10)
 3 rev-23508794    100  FY17           Q    Credit card             Web   [100,250)
 4 rev-23506121    300  FY17           S    Credit card            Mail   [250,500)
 5 rev-23550444    100  FY17           S    Credit card             Web   [100,250)
 6 rev-21508672     25  FY14           J          Check            Mail     [25,50)
 7 rev-24981769    500  FY18           S    Credit card             Web [500,1e+03)
 8 rev-23503684     50  FY17           R          Check            Mail     [50,75)
 9 rev-24982087     25  FY18           R          Check            Mail     [25,50)
10 rev-24979834     50  FY18           R    Credit card             Web     [50,75)
</code>```

Here is my code:

```<code>AMOUNT_CAT<- sample_data %>% group_by(AMOUNT_CAT,YEAR) %>% summarize(num=n(),total=sum(AMOUNT)) %>% rename(REPORT_VALUE=AMOUNT_CAT) %>% mutate(REPORT_CATEGORY="AMOUNT_CAT")
INBOUND_CHANNEL<- sample_data %>% group_by(INBOUND_CHANNEL,YEAR) %>% summarize(num=n(),total=sum(AMOUNT)) %>% rename(REPORT_VALUE=INBOUND_CHANNEL) %>% mutate(REPORT_CATEGORY="INBOUND_CHANNEL")
PAYMENT_METHOD<- sample_data %>% group_by(PAYMENT_METHOD,YEAR) %>% summarize(num=n(),total=sum(AMOUNT)) %>% rename(REPORT_VALUE=PAYMENT_METHOD) %>% mutate(REPORT_CATEGORY="PAYMENT_METHOD")
REPORT_CODE<- sample_data %>% group_by(REPORT_CODE,YEAR) %>% summarize(num=n(),total=sum(AMOUNT)) %>% rename(REPORT_VALUE=REPORT_CODE) %>% mutate(REPORT_CATEGORY="REPORT_CODE")
final_product<-bind_rows(REPORT_CODE,PAYMENT_METHOD,INBOUND_CHANNEL,AMOUNT_CAT)
</code>```

Here is the final product of that code:

```<code>       > final_product
        # A tibble: 27 x 5
        # Groups:   REPORT_VALUE [16]
           REPORT_CATEGORY REPORT_VALUE  YEAR   num total

                 <chr>        <chr> <chr> <int> <dbl>
     1     REPORT_CODE            J  FY14     1    25
     2     REPORT_CODE            Q  FY16     1     1
     3     REPORT_CODE            Q  FY17     1   100
     4     REPORT_CODE            R  FY17     1    50
     5     REPORT_CODE            R  FY18     2    75
     6     REPORT_CODE            S  FY17     2   400
     7     REPORT_CODE            S  FY18     2   530
     8  PAYMENT_METHOD        Check  FY14     1    25
     9  PAYMENT_METHOD        Check  FY17     1    50
    10  PAYMENT_METHOD        Check  FY18     2    55
    # ... with 17 more rows
</code>```

Here is my attempt to condense the code to make it smarter and more efficient (it doesn't work):

```<code>cat.list <- c("REPORT_CODE","PAYMENT_METHOD","INBOUND_CHANNEL","AMOUNT_CAT")
repeat_procs <- lapply(cat.list, function(x) x <- sample_data %>% group_by(x,YEAR) %>% summarize(num=n(),total=sum(AMOUNT)) %>% rename(REPORT_VALUE=x) %>% mutate(REPORT_CATEGORY="x")
</code>```

Can someone please advise me on how to write "smarter" code that doesn't repeat as often?

Thanks!

答:
For more "smarter" code, you need to transform the data to "tidy data" form before grouping and summarizing.

data_tidy <-
  tidyr::gather(sample_data, key = "REPORT_CATEGORY", value = "REPORT_VALUE", !! cat.list)

data_tidy
#>       REVENUEID AMOUNT YEAR REPORT_CATEGORY REPORT_VALUE
#> 1  rev-24985629     30 FY18     REPORT_CODE            S
#> 2  rev-22812413      1 FY16     REPORT_CODE            Q
#> 3  rev-23508794    100 FY17     REPORT_CODE            Q
#> 4  rev-23506121    300 FY17     REPORT_CODE            S
#> 5  rev-23550444    100 FY17     REPORT_CODE            S
#> 6  rev-21508672     25 FY14     REPORT_CODE            J
#> 7  rev-24981769    500 FY18     REPORT_CODE            S
#> 8  rev-23503684     50 FY17     REPORT_CODE            R
#> 9  rev-24982087     25 FY18     REPORT_CODE            R
#> 10 rev-24979834     50 FY18     REPORT_CODE            R
#> 11 rev-24985629     30 FY18  PAYMENT_METHOD        Check
#> 12 rev-22812413      1 FY16  PAYMENT_METHOD        Other
#> 13 rev-23508794    100 FY17  PAYMENT_METHOD  Credit card
#> 14 rev-23506121    300 FY17  PAYMENT_METHOD  Credit card
#> 15 rev-23550444    100 FY17  PAYMENT_METHOD  Credit card
#> 16 rev-21508672     25 FY14  PAYMENT_METHOD        Check
#> 17 rev-24981769    500 FY18  PAYMENT_METHOD  Credit card
#> 18 rev-23503684     50 FY17  PAYMENT_METHOD        Check
#> 19 rev-24982087     25 FY18  PAYMENT_METHOD        Check
#> 20 rev-24979834     50 FY18  PAYMENT_METHOD  Credit card
#> 21 rev-24985629     30 FY18 INBOUND_CHANNEL         Mail
#> 22 rev-22812413      1 FY16 INBOUND_CHANNEL   Canvassing
#> 23 rev-23508794    100 FY17 INBOUND_CHANNEL          Web
#> 24 rev-23506121    300 FY17 INBOUND_CHANNEL         Mail
#> 25 rev-23550444    100 FY17 INBOUND_CHANNEL          Web
#> 26 rev-21508672     25 FY14 INBOUND_CHANNEL         Mail
#> 27 rev-24981769    500 FY18 INBOUND_CHANNEL          Web
#> 28 rev-23503684     50 FY17 INBOUND_CHANNEL         Mail
#> 29 rev-24982087     25 FY18 INBOUND_CHANNEL         Mail
#> 30 rev-24979834     50 FY18 INBOUND_CHANNEL          Web
#> 31 rev-24985629     30 FY18      AMOUNT_CAT      [25,50)
#> 32 rev-22812413      1 FY16      AMOUNT_CAT    [0.01,10)
#> 33 rev-23508794    100 FY17      AMOUNT_CAT    [100,250)
#> 34 rev-23506121    300 FY17      AMOUNT_CAT    [250,500)
#> 35 rev-23550444    100 FY17      AMOUNT_CAT    [100,250)
#> 36 rev-21508672     25 FY14      AMOUNT_CAT      [25,50)
#> 37 rev-24981769    500 FY18      AMOUNT_CAT  [500,1e+03)
#> 38 rev-23503684     50 FY17      AMOUNT_CAT      [50,75)
#> 39 rev-24982087     25 FY18      AMOUNT_CAT      [25,50)
#> 40 rev-24979834     50 FY18      AMOUNT_CAT      [50,75)

data_tidy %>%
  group_by(REPORT_CATEGORY, REPORT_VALUE, YEAR) %>%
  summarise(num = n(), total = sum(AMOUNT)) %>%
  ungroup()
#> # A tibble: 27 x 5
#>    REPORT_CATEGORY REPORT_VALUE  YEAR   num total
#>              <chr>        <chr> <chr> <int> <int>
#>  1      AMOUNT_CAT    [0.01,10)  FY16     1     1
#>  2      AMOUNT_CAT    [100,250)  FY17     2   200
#>  3      AMOUNT_CAT      [25,50)  FY14     1    25
#>  4      AMOUNT_CAT      [25,50)  FY18     2    55
#>  5      AMOUNT_CAT    [250,500)  FY17     1   300
#>  6      AMOUNT_CAT      [50,75)  FY17     1    50
#>  7      AMOUNT_CAT      [50,75)  FY18     1    50
#>  8      AMOUNT_CAT  [500,1e+03)  FY18     1   500
#>  9 INBOUND_CHANNEL   Canvassing  FY16     1     1
#> 10 INBOUND_CHANNEL         Mail  FY14     1    25
#> # ... with 17 more rows
```

Body:
I would like to use a function to repeat a set of procedures on four columns in a data frame. Ultimately I need a long data frame containing all the output. Here is my data frame:

> sample_data
# A tibble: 10 x 7
      REVENUEID AMOUNT  YEAR REPORT_CODE PAYMENT_METHOD INBOUND_CHANNEL  AMOUNT_CAT
          <chr>  <dbl> <chr>       <chr>          <chr>           <chr>      <fctr>
 1 rev-24985629     30  FY18           S          Check            Mail     [25,50)
 2 rev-22812413      1  FY16           Q          Other      Canvassing   [0.01,10)
 3 rev-23508794    100  FY17           Q    Credit card             Web   [100,250)
 4 rev-23506121    300  FY17           S    Credit card            Mail   [250,500)
 5 rev-23550444    100  FY17           S    Credit card             Web   [100,250)
 6 rev-21508672     25  FY14           J          Check            Mail     [25,50)
 7 rev-24981769    500  FY18           S    Credit card             Web [500,1e+03)
 8 rev-23503684     50  FY17           R          Check            Mail     [50,75)
 9 rev-24982087     25  FY18           R          Check            Mail     [25,50)
10 rev-24979834     50  FY18           R    Credit card             Web     [50,75)

Here is my code:

AMOUNT_CAT<- sample_data %>% group_by(AMOUNT_CAT,YEAR) %>% summarize(num=n(),total=sum(AMOUNT)) %>% rename(REPORT_VALUE=AMOUNT_CAT) %>% mutate(REPORT_CATEGORY="AMOUNT_CAT")
INBOUND_CHANNEL<- sample_data %>% group_by(INBOUND_CHANNEL,YEAR) %>% summarize(num=n(),total=sum(AMOUNT)) %>% rename(REPORT_VALUE=INBOUND_CHANNEL) %>% mutate(REPORT_CATEGORY="INBOUND_CHANNEL")
PAYMENT_METHOD<- sample_data %>% group_by(PAYMENT_METHOD,YEAR) %>% summarize(num=n(),total=sum(AMOUNT)) %>% rename(REPORT_VALUE=PAYMENT_METHOD) %>% mutate(REPORT_CATEGORY="PAYMENT_METHOD")
REPORT_CODE<- sample_data %>% group_by(REPORT_CODE,YEAR) %>% summarize(num=n(),total=sum(AMOUNT)) %>% rename(REPORT_VALUE=REPORT_CODE) %>% mutate(REPORT_CATEGORY="REPORT_CODE")
final_product<-bind_rows(REPORT_CODE,PAYMENT_METHOD,INBOUND_CHANNEL,AMOUNT_CAT)

Here is the final product of that code:

       > final_product
        # A tibble: 27 x 5
        # Groups:   REPORT_VALUE [16]
           REPORT_CATEGORY REPORT_VALUE  YEAR   num total

                 <chr>        <chr> <chr> <int> <dbl>
     1     REPORT_CODE            J  FY14     1    25
     2     REPORT_CODE            Q  FY16     1     1
     3     REPORT_CODE            Q  FY17     1   100
     4     REPORT_CODE            R  FY17     1    50
     5     REPORT_CODE            R  FY18     2    75
     6     REPORT_CODE            S  FY17     2   400
     7     REPORT_CODE            S  FY18     2   530
     8  PAYMENT_METHOD        Check  FY14     1    25
     9  PAYMENT_METHOD        Check  FY17     1    50
    10  PAYMENT_METHOD        Check  FY18     2    55
    # ... with 17 more rows

Here is my attempt to condense the code to make it smarter and more efficient (it doesn't work):

cat.list <- c("REPORT_CODE","PAYMENT_METHOD","INBOUND_CHANNEL","AMOUNT_CAT")
repeat_procs <- lapply(cat.list, function(x) x <- sample_data %>% group_by(x,YEAR) %>% summarize(num=n(),total=sum(AMOUNT)) %>% rename(REPORT_VALUE=x) %>% mutate(REPORT_CATEGORY="x")

Can someone please advise me on how to write "smarter" code that doesn't repeat as often?

Thanks!


答:
Strings are immutable.  If you're going to concatenate many of them, for effiency's sake, instead try using StringBuilder:</p>

```<code>public string insertlines(string s, int i)
{
    StringBuilder sb = new StringBuilder();
    sb.Append(s);  // create the string
    for (int c = 0; c < i; c++)
    {
        sb.AppendLine(""); // add a line each time
    }
    return sb.ToString();
}
</code>```

Title: How to simplify Environment.NewLine()?

Body:
Strings are immutable.  If you're going to concatenate many of them, for effiency's sake, instead try using StringBuilder:

public string insertlines(string s, int i)
{
    StringBuilder sb = new StringBuilder();
    sb.Append(s);  // create the string
    for (int c = 0; c < i; c++)
    {
        sb.AppendLine(""); // add a line each time
    }
    return sb.ToString();
}


问:
How to parse variables from a parameter file in a K Shell script
I have a shell script I wish to read parameters from an external file, to get files via FTP:

parameters.txt:

```<code>FTP_SERVER=ftpserer.foo.org
FTP_USER_NAME=user
FTP_USER_PASSWORD=pass
FTP_SOURCE_DIRECTORY="/data/secondary/"
FTP_FILE_NAME="core.lst"
</code>```

I cannot find how to read these variables into my FTP_GET.sh script, I have tried using read but it just echoed the vars and doesn't store them as required.

答:
Assuming that 'K Shell' is Korn Shell, and that you are willing to trust the contents of the file, then you can use the dot command '.':

```<code>. parameters.txt
</code>```

This will read and interpret the file in the current shell.  The feature has been in Bourne shell since it was first released, and is in the Korn Shell and Bash too.  The C Shell equivalent is source, which Bash also treats as a synonym for dot.

If you don't trust the file then you can read the values with read, validate the values, and then use eval to set the variables:

```<code> while read line
 do
     # Check - which is HARD!
     eval $line
 done
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a shell script I wish to read parameters from an external file, to get files via FTP:

parameters.txt:

FTP_SERVER=ftpserer.foo.org
FTP_USER_NAME=user
FTP_USER_PASSWORD=pass
FTP_SOURCE_DIRECTORY="/data/secondary/"
FTP_FILE_NAME="core.lst"

I cannot find how to read these variables into my FTP_GET.sh script, I have tried using read but it just echoed the vars and doesn't store them as required.

Body:
Assuming that 'K Shell' is Korn Shell, and that you are willing to trust the contents of the file, then you can use the dot command '.':

. parameters.txt

This will read and interpret the file in the current shell.  The feature has been in Bourne shell since it was first released, and is in the Korn Shell and Bash too.  The C Shell equivalent is source, which Bash also treats as a synonym for dot.

If you don't trust the file then you can read the values with read, validate the values, and then use eval to set the variables:

 while read line
 do
     # Check - which is HARD!
     eval $line
 done


问:
creating multiple recycleviewer programmatically Android
I wanted to create RecyclerView that I can use many times by looping through my Json results.
what I wanted was to create categories of products(RecyclerViews), each containg its products that can be scrolled horizontally like on these  Image.

so I searched around Internet I couldn`t find anything.

Then I decided to do it these way:

create many recyclerView`s (eg. recycler_1, recycler_2)

then loop through my Json while adding adapters(data) into those recycler

Now my problem is that I want to add more categories(with their products) when the user reach the bottom, and I don't know how to add more recyclerViews programmatically or any other alternative.

Here is some of my code:

Here is my Json results

```<code>{
   "products":[
      {
         "category":[
            {
               "category_name":"Audio & TV"
            },
            {
               "inner_products":[
                  {
                     "id":"3442",
                     "product_thumb":"19279c812c9e56a0ca8fea095f36cb22.jpeg",
                     "brand_name":"Others",
                     "product_name":"4ga wiring kit",
                     "saved_amount":"0",
                     "product_price":"269",
                     "supplier_logo":"467909bb980b06aca7588be54fa4cb68.jpeg"
                  },
                  {
                     "id":"3444",
                     "product_thumb":"dd07c851cfaf1830f6b44f7c55298a18.jpeg",
                     "brand_name":"Kenwood",
                     "product_name":"car radio double din ",
                     "saved_amount":"400",
                     "product_price":"2299",
                     "supplier_logo":"467909bb980b06aca7588be54fa4cb68.jpeg"
                  }
               ]
            }
         ]
      },
      {
         "category":[
            {
               "category_name":"building tools"
            },
            {
               "inner_products":[
                  {
                     "id":"124",
                     "product_thumb":"c482e6b5ea0ee76c4e6524b86442bf27.png",
                     "brand_name":"Others",
                     "product_name":"drill bosch blue cordless 18v 4a",
                     "saved_amount":"0",
                     "product_price":"3695",
                     "supplier_logo":"21fa5955772bea6a5a1beae155860e6f.jpeg"
                  },
                  {
                     "id":"123",
                     "product_thumb":"124591fc38e03702774c99fa00515ca7.png",
                     "brand_name":"Others",
                     "product_name":"grinder bosch blue angle 125mm 850w",
                     "saved_amount":"0",
                     "product_price":"799.95",
                     "supplier_logo":"21fa5955772bea6a5a1beae155860e6f.jpeg"
                  }
               ]
            }
         ]
      }
   ]
}
</code>```

And here is how I Loop through the Json

```<code>final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading ");
progressDialog.show();

StringRequest productsStringrequest = new StringRequest(Request.Method.GET, products_url,

        new Response.Listener<String>(){

            @Override
            public void onResponse(String response) {

                progressDialog.dismiss();
                try {
                    JSONObject jsonObject = new JSONObject(response);

                    JSONArray productsArray = jsonObject.getJSONArray("products");

                    for (int i = 0; i < productsArray.length(); i++){

                        int[] procustRecycler = new int[]{R.id.procustRecycler_0, R.id.procustRecycler_1, R.id.procustRecycler_2, R.id.procustRecycler_3, R.id.procustRecycler_4, R.id.procustRecycler_5, R.id.procustRecycler_6, R.id.procustRecycler_7, R.id.procustRecycler_8,  R.id.procustRecycler_9};
                        int[] pr_header = new int[]{R.id.product_header_0, R.id.product_header_1, R.id.product_header_2, R.id.product_header_3, R.id.product_header_4, R.id.product_header_5, R.id.product_header_6, R.id.product_header_7, R.id.product_header_8, R.id.product_header_9 };

                        JSONObject categoryObject = productsArray.getJSONObject(i);
                        JSONArray categoryArray = categoryObject.getJSONArray("category");

                        for (int b = 0; b < categoryArray.length(); b++){

                            JSONObject singleCategoryObject = categoryArray.getJSONObject(0);

                            RecyclerView allProductsRecycler = (RecyclerView) findViewById(procustRecycler[i]);

                            allProductsRecycler.setHasFixedSize(true);
                            allProductsRecycler.setLayoutManager(new LinearLayoutManager(Products.this, LinearLayoutManager.HORIZONTAL, false));
                            List<ProductsItems> products_list = new ArrayList<>();

                            if(b == 0) {
                                TextView product_header = (TextView) findViewById(pr_header[i]);
                                product_header.setText(singleCategoryObject.getString("category_name"));

                                continue;
                            }

                            JSONObject productsCategoryObject  = categoryArray.getJSONObject(b);
                            JSONArray singleProductsArray = productsCategoryObject.getJSONArray("inner_products");

                            for (int c=0; c< singleProductsArray.length(); c++){

                                JSONObject object = singleProductsArray.getJSONObject(c);

                                ProductsItems items = new ProductsItems(
                                        object.getInt("id"),
                                        object.getString("product_name"),
                                        object.getString("product_thumb"),
                                        object.getString("supplier_logo"),
                                        object.getString("brand_name"),
                                        object.getString("product_price"),
                                        object.getString("saved_amount")
                                );
                                products_list.add(items);
                            }

                            RecyclerView.Adapter allProductsAdapter = new ProductsAdapter(products_list, getApplicationContext());
                            allProductsRecycler.setAdapter(allProductsAdapter);

                        }
                    }

                } catch (JSONException e) {

                    System.out.println(e.getMessage());
                    Toast.makeText(Products.this, "Catche error: "+e.getMessage(), Toast.LENGTH_LONG).show();
                }
            }
        },

        new Response.ErrorListener(){

            @Override
            public void onErrorResponse(VolleyError error) {

                progressDialog.dismiss();

                if (error instanceof TimeoutError ) {
                    Toast.makeText(Products.this, "Network time out", Toast.LENGTH_LONG).show();
                } else if (error instanceof AuthFailureError) {
                    Toast.makeText(Products.this, "Login fail", Toast.LENGTH_LONG).show();
                } else if (error instanceof ServerError) {
                    Toast.makeText(Products.this, "Server error", Toast.LENGTH_LONG).show();
                } else if (error instanceof NetworkError) {
                    Toast.makeText(Products.this, "Network error", Toast.LENGTH_LONG).show();
                } else if (error instanceof ParseError) {
                    Toast.makeText(Products.this, "Unknown", Toast.LENGTH_LONG).show();
                }
            }
        }
);

SingleTon.getInstance(getApplicationContext()).addToRequestQue(productsStringrequest);
</code>```

答:
This library is best for your requirement.

SectionRecyclerView

Body:
I wanted to create RecyclerView that I can use many times by looping through my Json results.
what I wanted was to create categories of products(RecyclerViews), each containg its products that can be scrolled horizontally like on these  Image.

so I searched around Internet I couldn`t find anything.

Then I decided to do it these way:

create many recyclerView`s (eg. recycler_1, recycler_2)

then loop through my Json while adding adapters(data) into those recycler

Now my problem is that I want to add more categories(with their products) when the user reach the bottom, and I don't know how to add more recyclerViews programmatically or any other alternative.

Here is some of my code:

Here is my Json results

{
   "products":[
      {
         "category":[
            {
               "category_name":"Audio & TV"
            },
            {
               "inner_products":[
                  {
                     "id":"3442",
                     "product_thumb":"19279c812c9e56a0ca8fea095f36cb22.jpeg",
                     "brand_name":"Others",
                     "product_name":"4ga wiring kit",
                     "saved_amount":"0",
                     "product_price":"269",
                     "supplier_logo":"467909bb980b06aca7588be54fa4cb68.jpeg"
                  },
                  {
                     "id":"3444",
                     "product_thumb":"dd07c851cfaf1830f6b44f7c55298a18.jpeg",
                     "brand_name":"Kenwood",
                     "product_name":"car radio double din ",
                     "saved_amount":"400",
                     "product_price":"2299",
                     "supplier_logo":"467909bb980b06aca7588be54fa4cb68.jpeg"
                  }
               ]
            }
         ]
      },
      {
         "category":[
            {
               "category_name":"building tools"
            },
            {
               "inner_products":[
                  {
                     "id":"124",
                     "product_thumb":"c482e6b5ea0ee76c4e6524b86442bf27.png",
                     "brand_name":"Others",
                     "product_name":"drill bosch blue cordless 18v 4a",
                     "saved_amount":"0",
                     "product_price":"3695",
                     "supplier_logo":"21fa5955772bea6a5a1beae155860e6f.jpeg"
                  },
                  {
                     "id":"123",
                     "product_thumb":"124591fc38e03702774c99fa00515ca7.png",
                     "brand_name":"Others",
                     "product_name":"grinder bosch blue angle 125mm 850w",
                     "saved_amount":"0",
                     "product_price":"799.95",
                     "supplier_logo":"21fa5955772bea6a5a1beae155860e6f.jpeg"
                  }
               ]
            }
         ]
      }
   ]
}

And here is how I Loop through the Json

final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading ");
progressDialog.show();

StringRequest productsStringrequest = new StringRequest(Request.Method.GET, products_url,

        new Response.Listener<String>(){

            @Override
            public void onResponse(String response) {

                progressDialog.dismiss();
                try {
                    JSONObject jsonObject = new JSONObject(response);

                    JSONArray productsArray = jsonObject.getJSONArray("products");

                    for (int i = 0; i < productsArray.length(); i++){

                        int[] procustRecycler = new int[]{R.id.procustRecycler_0, R.id.procustRecycler_1, R.id.procustRecycler_2, R.id.procustRecycler_3, R.id.procustRecycler_4, R.id.procustRecycler_5, R.id.procustRecycler_6, R.id.procustRecycler_7, R.id.procustRecycler_8,  R.id.procustRecycler_9};
                        int[] pr_header = new int[]{R.id.product_header_0, R.id.product_header_1, R.id.product_header_2, R.id.product_header_3, R.id.product_header_4, R.id.product_header_5, R.id.product_header_6, R.id.product_header_7, R.id.product_header_8, R.id.product_header_9 };

                        JSONObject categoryObject = productsArray.getJSONObject(i);
                        JSONArray categoryArray = categoryObject.getJSONArray("category");

                        for (int b = 0; b < categoryArray.length(); b++){

                            JSONObject singleCategoryObject = categoryArray.getJSONObject(0);

                            RecyclerView allProductsRecycler = (RecyclerView) findViewById(procustRecycler[i]);

                            allProductsRecycler.setHasFixedSize(true);
                            allProductsRecycler.setLayoutManager(new LinearLayoutManager(Products.this, LinearLayoutManager.HORIZONTAL, false));
                            List<ProductsItems> products_list = new ArrayList<>();

                            if(b == 0) {
                                TextView product_header = (TextView) findViewById(pr_header[i]);
                                product_header.setText(singleCategoryObject.getString("category_name"));

                                continue;
                            }

                            JSONObject productsCategoryObject  = categoryArray.getJSONObject(b);
                            JSONArray singleProductsArray = productsCategoryObject.getJSONArray("inner_products");

                            for (int c=0; c< singleProductsArray.length(); c++){

                                JSONObject object = singleProductsArray.getJSONObject(c);

                                ProductsItems items = new ProductsItems(
                                        object.getInt("id"),
                                        object.getString("product_name"),
                                        object.getString("product_thumb"),
                                        object.getString("supplier_logo"),
                                        object.getString("brand_name"),
                                        object.getString("product_price"),
                                        object.getString("saved_amount")
                                );
                                products_list.add(items);
                            }

                            RecyclerView.Adapter allProductsAdapter = new ProductsAdapter(products_list, getApplicationContext());
                            allProductsRecycler.setAdapter(allProductsAdapter);

                        }
                    }

                } catch (JSONException e) {

                    System.out.println(e.getMessage());
                    Toast.makeText(Products.this, "Catche error: "+e.getMessage(), Toast.LENGTH_LONG).show();
                }
            }
        },

        new Response.ErrorListener(){

            @Override
            public void onErrorResponse(VolleyError error) {

                progressDialog.dismiss();

                if (error instanceof TimeoutError ) {
                    Toast.makeText(Products.this, "Network time out", Toast.LENGTH_LONG).show();
                } else if (error instanceof AuthFailureError) {
                    Toast.makeText(Products.this, "Login fail", Toast.LENGTH_LONG).show();
                } else if (error instanceof ServerError) {
                    Toast.makeText(Products.this, "Server error", Toast.LENGTH_LONG).show();
                } else if (error instanceof NetworkError) {
                    Toast.makeText(Products.this, "Network error", Toast.LENGTH_LONG).show();
                } else if (error instanceof ParseError) {
                    Toast.makeText(Products.this, "Unknown", Toast.LENGTH_LONG).show();
                }
            }
        }
);

SingleTon.getInstance(getApplicationContext()).addToRequestQue(productsStringrequest);


问:
Why does an instance method have this type in Swift?
Given this code:

```<code>struct Foo {
    func f() {}
}

let f = Foo.f // (Foo) -> () -> ()
</code>```

Why does f have the type (Foo) -> () -> () and not (Foo) -> ()? Wouldn’t it make sense for instance methods like Foo.f to be directly interchangeable with free functions of type (Foo) -> …?

答:
Why does f have the type (Foo) -> () -> () and not (Foo) -> ()?

That's just currently how unapplied instance method references are implemented; they're curried functions that follow the model of "give me an instance, and I'll give you back a partially-applied instance method" (partially applied with that instance).

However this is problematic in some areas, firstly because it's generally more useful for them to be of the form (Self, Args...) -> Ret, but also more importantly because it because it leads to issues around mutating methods. These end up looking like (inout Self) -> (Args...) -> Ret with the current system, which is problematic because the window of mutation for inout only lasts for the duration of the call.

This means the following currently compiles, but is actually undefined behaviour:

```<code>struct S {
  var i: Int

  mutating func increment() {
    i += 1
  }
}

var s = S(i: 0)
let unappliedIncrement = S.increment
let increment = unappliedIncrement(&s)
increment() // undefined behaviour
</code>```

These are the main motivations behind SE-0042, which will change unapplied instance method references from being of the form (Self) -> (Args...) -> Ret to being of the form
 (Self, Args...) -> Ret (and with inout, Self will be inout Self – allowing the mutation of the instance without UB).

This proposal is yet to be implemented, but once it is, assuming empty parameter lists get flattened out (so you don't end up with a trailing Void parameter), Foo.f will indeed be of type
 (Foo) -> Void.

Body:
Given this code:

struct Foo {
    func f() {}
}

let f = Foo.f // (Foo) -> () -> ()

Why does f have the type (Foo) -> () -> () and not (Foo) -> ()? Wouldn’t it make sense for instance methods like Foo.f to be directly interchangeable with free functions of type (Foo) -> …?

Body:
Why does f have the type (Foo) -> () -> () and not (Foo) -> ()?

That's just currently how unapplied instance method references are implemented; they're curried functions that follow the model of "give me an instance, and I'll give you back a partially-applied instance method" (partially applied with that instance).

However this is problematic in some areas, firstly because it's generally more useful for them to be of the form (Self, Args...) -> Ret, but also more importantly because it because it leads to issues around mutating methods. These end up looking like (inout Self) -> (Args...) -> Ret with the current system, which is problematic because the window of mutation for inout only lasts for the duration of the call.

This means the following currently compiles, but is actually undefined behaviour:

struct S {
  var i: Int

  mutating func increment() {
    i += 1
  }
}

var s = S(i: 0)
let unappliedIncrement = S.increment
let increment = unappliedIncrement(&s)
increment() // undefined behaviour

These are the main motivations behind SE-0042, which will change unapplied instance method references from being of the form (Self) -> (Args...) -> Ret to being of the form
 (Self, Args...) -> Ret (and with inout, Self will be inout Self – allowing the mutation of the instance without UB).

This proposal is yet to be implemented, but once it is, assuming empty parameter lists get flattened out (so you don't end up with a trailing Void parameter), Foo.f will indeed be of type
 (Foo) -> Void.


问:
Text field from Vuetify has no underline
I am trying to use vuetify's text field. It looks like this:

After applying focus it looks like this:

I have read this this, but my app IS wrapped in v-app. Is there anything else I could try?

HINT:
Dark theme doesn't work for me as well,but for example, I can use classes like "red", "text--red", to apply colors.

Proof, that there is v-app involved below:

EDIT:
I tried to wrap it with v-content as well, but it didn't help.

```<code><v-app>
  <v-content>
    <router-view></router-view>
  </v-content>
</v-app>
</code>```

答:
I fixed it by removing

```<code><link href="https://unpkg.com/vuetify/dist/vuetify.min.css" rel="stylesheet">
</code>```

from index.html, and adding

```<code>import '../node_modules/vuetify/dist/vuetify.min.css';
</code>```

to main.js file.

Dunno why it worked though.

Body:
I am trying to use vuetify's text field. It looks like this:

After applying focus it looks like this:

I have read this this, but my app IS wrapped in v-app. Is there anything else I could try?

HINT:
Dark theme doesn't work for me as well,but for example, I can use classes like "red", "text--red", to apply colors.

Proof, that there is v-app involved below:

EDIT:
I tried to wrap it with v-content as well, but it didn't help.

<v-app>
  <v-content>
    <router-view></router-view>
  </v-content>
</v-app>

Body:
I fixed it by removing

<link href="https://unpkg.com/vuetify/dist/vuetify.min.css" rel="stylesheet">

from index.html, and adding

import '../node_modules/vuetify/dist/vuetify.min.css';

to main.js file.

Dunno why it worked though.


问:
Only scroll UIScrollView, if the label in it is bigger than the View respectively
I have a little problem with the UIScrollView. It scrolls way to far. Is it possible to enable it only, if the label in it is bigger than the ScrollView?

Pictures (sorry, they are quite huge):

The Label, that is on the ScrollView, is in the ScrollView

答:
You should try using a UITextView instead of a scrollview. It looks like you only need text. A textview does NOT have to be editable. You can disable the editable check box in the storyboard. Take a look at my screenshot.

If you do want the scrollview method to work, you will have to add a bottom constraint to the label in your scrollview. It will tell the content view of your scrollview the size of the content within the scrollview.


问:
Using new Groovy Grape capability results in "unable to resolve class" error
I've tried to use the new Groovy Grape capability in Groovy 1.6-beta-2 but I get an error message;

```<code>unable to resolve class com.jidesoft.swing.JideSplitButton
</code>```

from the Groovy Console (/opt/groovy/groovy-1.6-beta-2/bin/groovyConsole) when running the stock example;

```<code>import com.jidesoft.swing.JideSplitButton
@Grab(group='com.jidesoft', module='jide-oss', version='[2.2.1,)')
public class TestClassAnnotation {
    public static String testMethod () {
        return JideSplitButton.class.name
    }
}
</code>```

I even tried running the grape command line tool to ensure the library is imported.  Like this;

```<code> $ /opt/groovy/groovy-1.6-beta-2/bin/grape install com.jidesoft jide-oss
</code>```

which does install the library just fine.  How do I get the code to run/compile correctly from the groovyConsole?

答:
Different example using latest RC-2 (note: Grab annotates createEmptyInts):</p>

```<code>// create and use a primitive array
import org.apache.commons.collections.primitives.ArrayIntList

@Grab(group='commons-primitives', module='commons-primitives', version='1.0')
def createEmptyInts() { new ArrayIntList() }

def ints = createEmptyInts()
ints.add(0, 42)
assert ints.size() == 1
assert ints.get(0) == 42
</code>```

OwnerDisplayName: Bob Herrmann

Body:
I've tried to use the new Groovy Grape capability in Groovy 1.6-beta-2 but I get an error message;

unable to resolve class com.jidesoft.swing.JideSplitButton

from the Groovy Console (/opt/groovy/groovy-1.6-beta-2/bin/groovyConsole) when running the stock example;

import com.jidesoft.swing.JideSplitButton
@Grab(group='com.jidesoft', module='jide-oss', version='[2.2.1,)')
public class TestClassAnnotation {
    public static String testMethod () {
        return JideSplitButton.class.name
    }
}

I even tried running the grape command line tool to ensure the library is imported.  Like this;

 $ /opt/groovy/groovy-1.6-beta-2/bin/grape install com.jidesoft jide-oss

which does install the library just fine.  How do I get the code to run/compile correctly from the groovyConsole?

LastEditorDisplayName: Bob Herrmann

Body:
Different example using latest RC-2 (note: Grab annotates createEmptyInts):

// create and use a primitive array
import org.apache.commons.collections.primitives.ArrayIntList

@Grab(group='commons-primitives', module='commons-primitives', version='1.0')
def createEmptyInts() { new ArrayIntList() }

def ints = createEmptyInts()
ints.add(0, 42)
assert ints.size() == 1
assert ints.get(0) == 42

OwnerDisplayName: Paul King

LastEditorDisplayName: Paul King


问:
Combinatoric 'N choose R' in java math?
Is there a built in method in a java library that can compute 'N choose R' for any N, R?</p>

答:
The following routine will compute the n-choose-k, using the recursive definition and memoization. The routine is extremely fast and accurate:

```<code>inline unsigned long long n_choose_k(const unsigned long long& n,
                                     const unsigned long long& k)
{
   if (n  < k) return 0;
   if (0 == n) return 0;
   if (0 == k) return 1;
   if (n == k) return 1;
   if (1 == k) return n;
   typedef unsigned long long value_type;
   value_type* table = new value_type[static_cast<std::size_t>(n * n)];
   std::fill_n(table,n * n,0);
   class n_choose_k_impl
   {
   public:

      n_choose_k_impl(value_type* table,const value_type& dimension)
      : table_(table),
        dimension_(dimension)
      {}

      inline value_type& lookup(const value_type& n, const value_type& k)
      {
         return table_[dimension_ * n + k];
      }

      inline value_type compute(const value_type& n, const value_type& k)
      {
         if ((0 == k) || (k == n))
            return 1;
         value_type v1 = lookup(n - 1,k - 1);
         if (0 == v1)
            v1 = lookup(n - 1,k - 1) = compute(n - 1,k - 1);
         value_type v2 = lookup(n - 1,k);
         if (0 == v2)
            v2 = lookup(n - 1,k) = compute(n - 1,k);
         return v1 + v2;
      }

      value_type* table_;
      value_type dimension_;
   };
   value_type result = n_choose_k_impl(table,n).compute(n,k);
   delete [] table;
   return result;
}
</code>```

Title: Combinatoric 'N choose R' in java math?

Body:
The following routine will compute the n-choose-k, using the recursive definition and memoization. The routine is extremely fast and accurate:

inline unsigned long long n_choose_k(const unsigned long long& n,
                                     const unsigned long long& k)
{
   if (n  < k) return 0;
   if (0 == n) return 0;
   if (0 == k) return 1;
   if (n == k) return 1;
   if (1 == k) return n;
   typedef unsigned long long value_type;
   value_type* table = new value_type[static_cast<std::size_t>(n * n)];
   std::fill_n(table,n * n,0);
   class n_choose_k_impl
   {
   public:

      n_choose_k_impl(value_type* table,const value_type& dimension)
      : table_(table),
        dimension_(dimension)
      {}

      inline value_type& lookup(const value_type& n, const value_type& k)
      {
         return table_[dimension_ * n + k];
      }

      inline value_type compute(const value_type& n, const value_type& k)
      {
         if ((0 == k) || (k == n))
            return 1;
         value_type v1 = lookup(n - 1,k - 1);
         if (0 == v1)
            v1 = lookup(n - 1,k - 1) = compute(n - 1,k - 1);
         value_type v2 = lookup(n - 1,k);
         if (0 == v2)
            v2 = lookup(n - 1,k) = compute(n - 1,k);
         return v1 + v2;
      }

      value_type* table_;
      value_type dimension_;
   };
   value_type result = n_choose_k_impl(table,n).compute(n,k);
   delete [] table;
   return result;
}

OwnerDisplayName: Matthieu N.

LastEditorDisplayName: Matthieu N.


问:
How do I create a supplier of a class with limitations regarding constructor arguments?
I have a class called Human (accepts name(string) and height(int) in the constructor) and need too create a supplier of this class that will create an object but I want the object's name to let's say be between 5-10 characters, and the height should be between 110-250. Is it possible to do so in Java?</p>

答:
A constructor can't directly return null, but you could use something called a factory method.  A factory method would look something like this:

```<code>public static Human createHuman(String name, int height)
{
    if (height < 110 || height > 250)
        return null;
    if (name == null || name.length() < 5 || name.length() > 10)
        return null;
    else
        return new Human(name, height);
}

private Human (String name, int height)  // note that this is private
{
    this.name = name;
    this.height = height;
}
</code>```

You could call it like this:

```<code>Human.createHuman("Steve", 117);
</code>```

(Or in your case, perhaps like this:)

```<code>Supplier<Human> i = ()-> {return Human.createHuman(someName, someHeight)};
</code>```

Body:
A constructor can't directly return null, but you could use something called a factory method.  A factory method would look something like this:

public static Human createHuman(String name, int height)
{
    if (height < 110 || height > 250)
        return null;
    if (name == null || name.length() < 5 || name.length() > 10)
        return null;
    else
        return new Human(name, height);
}

private Human (String name, int height)  // note that this is private
{
    this.name = name;
    this.height = height;
}

You could call it like this:

Human.createHuman("Steve", 117);

(Or in your case, perhaps like this:)

Supplier<Human> i = ()-> {return Human.createHuman(someName, someHeight)};