问:
first spring batch job being overriden with details of second job
I have a spring mvc application with spring batch integrated. My spring batch jobs get executed via cron triggers.

I have two batch jobs definied in my xml. The second batch jobs works fine but when I execute the first batch job it executed the second.

I think I am registering my jobs incorrectly. Can someone help me with what might be wrong.

thanks

2nd job definition (job-bulletin-bar-msg-update.xml)...

```<code><job id="job-bulletin-bar-msg-update" xmlns="http://www.springframework.org/schema/batch">
    <step id="step1">
        <tasklet>
            <chunk
                reader="bulletinBarUpdateJdbcCursorItemReader"
                writer="bulletinBarUpdateItemWriter"
                commit-interval="1000" />
        </tasklet>
    </step>
</job>
</code>```

1st job definition (job-daily-tran-counts.xml)...

```<code><job id="job-daily-tran-counts" xmlns="http://www.springframework.org/schema/batch">
    <step id="step1">
        <tasklet>
            <chunk
                reader="dailyTranCountJdbcCursorItemReader"
                writer="dailyTranCountItemWriter"
                commit-interval="1000" />
        </tasklet>
    </step>
</job>
</code>```

Adding job to scheduler and registry....

```<code><beans profile="pre,prod">
    <!-- jobs -->
    <import resource="./jobs/job-daily-tran-counts.xml" />
    <import resource="./jobs/job-bulletin-bar-msg-update.xml" />

    <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="jobDetails">
           <list>
              <ref bean="dailyTranCountJobDetail" />
              <ref bean="bulletinBarMsgUpdateJobDetail" />
           </list>
        </property>
        <property name="triggers">
           <list>
              <ref bean="dailyTranCountCronTrigger" />
              <ref bean="bulletinBarMsgUpdateCronTrigger" />
           </list>
        </property>
    </bean>

    <!-- scheduling properties -->
    <util:properties id="batchProps" location="classpath:batch.properties" />
    <context:property-placeholder properties-ref="batchProps" />

    <!-- triggers -->
    <bean id="dailyTranCountCronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
        <property name="jobDetail" ref="dailyTranCountJobDetail" />
        <property name="cronExpression" value="#{batchProps['cron.dailyTranCounts']}" />
    </bean>

    <bean id="bulletinBarMsgUpdateCronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
        <property name="jobDetail" ref="bulletinBarMsgUpdateJobDetail" />
        <property name="cronExpression" value="#{batchProps['cron.bulletinBarUpdateMsg']}" />
    </bean>

    <!-- job detail -->
    <bean id="dailyTranCountJobDetail" class="org.springframework.scheduling.quartz.JobDetailBean">
        <property name="jobClass" value="com.myer.reporting.batch.JobLauncherDetails" />
        <property name="group" value="quartz-batch" />
        <property name="jobDataAsMap">
            <map>
                <entry key="jobName" value="job-daily-tran-counts" />
                <entry key="jobLocator" value-ref="jobRegistry" />
                <entry key="jobLauncher" value-ref="jobLauncher" />
            </map>
        </property>
    </bean>

    <bean id="bulletinBarMsgUpdateJobDetail" class="org.springframework.scheduling.quartz.JobDetailBean">
        <property name="jobClass" value="com.myer.reporting.batch.JobLauncherDetails" />
        <property name="group" value="quartz-batch" />
        <property name="jobDataAsMap">
            <map>
                <entry key="jobName" value="job-bulletin-bar-msg-update" />
                <entry key="jobLocator" value-ref="jobRegistry" />
                <entry key="jobLauncher" value-ref="jobLauncher" />
            </map>
        </property>
    </bean>

</beans>
</code>```

Here is my job launcher details class. I just copied it from somewhere else...

```<code>public class JobLauncherDetails extends QuartzJobBean {

    static final String JOB_NAME = "jobName";

    private JobLocator jobLocator;

    private JobLauncher jobLauncher;

    public void setJobLocator(JobLocator jobLocator) {
        this.jobLocator = jobLocator;
    }

    public void setJobLauncher(JobLauncher jobLauncher) {
        this.jobLauncher = jobLauncher;
    }

    @SuppressWarnings("unchecked")
    protected void executeInternal(JobExecutionContext context) {

        Map<String, Object> jobDataMap = context.getMergedJobDataMap();

        String jobName = (String) jobDataMap.get(JOB_NAME);

        JobParameters jobParameters = getJobParametersFromJobMap(jobDataMap);

        try {
            jobLauncher.run(jobLocator.getJob(jobName), jobParameters);
        } catch (JobExecutionException e) {
            e.printStackTrace();
        }
    }

    //get params from jobDataAsMap property, job-quartz.xml
    private JobParameters getJobParametersFromJobMap(Map<String, Object> jobDataMap) {

        JobParametersBuilder builder = new JobParametersBuilder();

        for (Entry<String, Object> entry : jobDataMap.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            if (value instanceof String && !key.equals(JOB_NAME)) {
                builder.addString(key, (String) value);
            } else if (value instanceof Float || value instanceof Double) {
                builder.addDouble(key, ((Number) value).doubleValue());
            } else if (value instanceof Integer || value instanceof Long) {
                builder.addLong(key, ((Number) value).longValue());
            } else if (value instanceof Date) {
                builder.addDate(key, (Date) value);
            } else {
                // JobDataMap contains values which are not job parameters
                // (ignoring)
            }
        }

        //need unique job parameter to rerun the same job
        builder.addDate("run date", new Date());

        return builder.toJobParameters();

    }

}
</code>```

Here is my batch.properties...

```<code>#http://quartz-scheduler.org/documentation/quartz-1.x/tutorials/crontrigger
cron.dailyTranCounts=0 15 07 * * ? *
cron.bulletinBarUpdateMsg=0 30 07 * * ? *
</code>```

Some more info. To try and find out more I put a log on org.springframework.batch.core.launch.support.SimpleJobLauncher.

When I had only the first job enabled in my spring config the log shows that job-daily-tran-counts takes roughly 2.5 minutes to execute...

```<code>[INFO] 2014-03-19 07:15:00,187 org.springframework.batch.core.launch.support.SimpleJobLauncher run - Job: [FlowJob: [name=job-daily-tran-counts]] launched with the following parameters: [{run date=1395173700052}]
[INFO] 2014-03-19 07:17:43,934 org.springframework.batch.core.launch.support.SimpleJobLauncher run - Job: [FlowJob: [name=job-daily-tran-counts]] completed with the following parameters: [{run date=1395173700052}] and the following status: [COMPLETED]
</code>```

When I had only the both jobs enabled in my spring config the log shows that job-daily-tran-counts takes roughly only 8 milliseconds when it should take longer. i.e. It is doing nothing...

```<code>[INFO] 2014-04-15 07:15:00,225 org.springframework.batch.core.launch.support.SimpleJobLauncher run - Job: [FlowJob: [name=job-daily-tran-counts]] launched with the following parameters: [{run date=1397510100128}]
[INFO] 2014-04-15 07:15:08,977 org.springframework.batch.core.launch.support.SimpleJobLauncher run - Job: [FlowJob: [name=job-daily-tran-counts]] completed with the following parameters: [{run date=1397510100128}] and the following status: [COMPLETED]
[INFO] 2014-04-15 07:30:00,009 org.springframework.batch.core.launch.support.SimpleJobLauncher run - Job: [FlowJob: [name=job-bulletin-bar-msg-update]] launched with the following parameters: [{run date=1397511000007}]
[INFO] 2014-04-15 07:30:05,217 org.springframework.batch.core.launch.support.SimpleJobLauncher run - Job: [FlowJob: [name=job-bulletin-bar-msg-update]] completed with the following parameters: [{run date=1397511000007}] and the following status: [COMPLETED]
</code>```

答:
I have the same problem, had to rename all steps.

read somewhere about
@EnableBatchProcessing(modular=true)

It might keep the jobs in seperate 'context'

Body:
I have a spring mvc application with spring batch integrated. My spring batch jobs get executed via cron triggers.

I have two batch jobs definied in my xml. The second batch jobs works fine but when I execute the first batch job it executed the second.

I think I am registering my jobs incorrectly. Can someone help me with what might be wrong.

thanks

2nd job definition (job-bulletin-bar-msg-update.xml)...

<job id="job-bulletin-bar-msg-update" xmlns="http://www.springframework.org/schema/batch">
    <step id="step1">
        <tasklet>
            <chunk
                reader="bulletinBarUpdateJdbcCursorItemReader"
                writer="bulletinBarUpdateItemWriter"
                commit-interval="1000" />
        </tasklet>
    </step>
</job>

1st job definition (job-daily-tran-counts.xml)...

<job id="job-daily-tran-counts" xmlns="http://www.springframework.org/schema/batch">
    <step id="step1">
        <tasklet>
            <chunk
                reader="dailyTranCountJdbcCursorItemReader"
                writer="dailyTranCountItemWriter"
                commit-interval="1000" />
        </tasklet>
    </step>
</job>

Adding job to scheduler and registry....

<beans profile="pre,prod">

    <import resource="./jobs/job-daily-tran-counts.xml" />
    <import resource="./jobs/job-bulletin-bar-msg-update.xml" />

    <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="jobDetails">
           <list>
              <ref bean="dailyTranCountJobDetail" />
              <ref bean="bulletinBarMsgUpdateJobDetail" />
           </list>
        </property>
        <property name="triggers">
           <list>
              <ref bean="dailyTranCountCronTrigger" />
              <ref bean="bulletinBarMsgUpdateCronTrigger" />
           </list>
        </property>
    </bean>

    <util:properties id="batchProps" location="classpath:batch.properties" />
    <context:property-placeholder properties-ref="batchProps" />

    <bean id="dailyTranCountCronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
        <property name="jobDetail" ref="dailyTranCountJobDetail" />
        <property name="cronExpression" value="#{batchProps['cron.dailyTranCounts']}" />
    </bean>

    <bean id="bulletinBarMsgUpdateCronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
        <property name="jobDetail" ref="bulletinBarMsgUpdateJobDetail" />
        <property name="cronExpression" value="#{batchProps['cron.bulletinBarUpdateMsg']}" />
    </bean>

    <bean id="dailyTranCountJobDetail" class="org.springframework.scheduling.quartz.JobDetailBean">
        <property name="jobClass" value="com.myer.reporting.batch.JobLauncherDetails" />
        <property name="group" value="quartz-batch" />
        <property name="jobDataAsMap">
            <map>
                <entry key="jobName" value="job-daily-tran-counts" />
                <entry key="jobLocator" value-ref="jobRegistry" />
                <entry key="jobLauncher" value-ref="jobLauncher" />
            </map>
        </property>
    </bean>

    <bean id="bulletinBarMsgUpdateJobDetail" class="org.springframework.scheduling.quartz.JobDetailBean">
        <property name="jobClass" value="com.myer.reporting.batch.JobLauncherDetails" />
        <property name="group" value="quartz-batch" />
        <property name="jobDataAsMap">
            <map>
                <entry key="jobName" value="job-bulletin-bar-msg-update" />
                <entry key="jobLocator" value-ref="jobRegistry" />
                <entry key="jobLauncher" value-ref="jobLauncher" />
            </map>
        </property>
    </bean>

</beans>

Here is my job launcher details class. I just copied it from somewhere else...

public class JobLauncherDetails extends QuartzJobBean {

    static final String JOB_NAME = "jobName";

    private JobLocator jobLocator;

    private JobLauncher jobLauncher;

    public void setJobLocator(JobLocator jobLocator) {
        this.jobLocator = jobLocator;
    }

    public void setJobLauncher(JobLauncher jobLauncher) {
        this.jobLauncher = jobLauncher;
    }

    @SuppressWarnings("unchecked")
    protected void executeInternal(JobExecutionContext context) {

        Map<String, Object> jobDataMap = context.getMergedJobDataMap();

        String jobName = (String) jobDataMap.get(JOB_NAME);

        JobParameters jobParameters = getJobParametersFromJobMap(jobDataMap);

        try {
            jobLauncher.run(jobLocator.getJob(jobName), jobParameters);
        } catch (JobExecutionException e) {
            e.printStackTrace();
        }
    }

    //get params from jobDataAsMap property, job-quartz.xml
    private JobParameters getJobParametersFromJobMap(Map<String, Object> jobDataMap) {

        JobParametersBuilder builder = new JobParametersBuilder();

        for (Entry<String, Object> entry : jobDataMap.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            if (value instanceof String && !key.equals(JOB_NAME)) {
                builder.addString(key, (String) value);
            } else if (value instanceof Float || value instanceof Double) {
                builder.addDouble(key, ((Number) value).doubleValue());
            } else if (value instanceof Integer || value instanceof Long) {
                builder.addLong(key, ((Number) value).longValue());
            } else if (value instanceof Date) {
                builder.addDate(key, (Date) value);
            } else {
                // JobDataMap contains values which are not job parameters
                // (ignoring)
            }
        }

        //need unique job parameter to rerun the same job
        builder.addDate("run date", new Date());

        return builder.toJobParameters();

    }

}

Here is my batch.properties...

#http://quartz-scheduler.org/documentation/quartz-1.x/tutorials/crontrigger
cron.dailyTranCounts=0 15 07 * * ? *
cron.bulletinBarUpdateMsg=0 30 07 * * ? *

Some more info. To try and find out more I put a log on org.springframework.batch.core.launch.support.SimpleJobLauncher.

When I had only the first job enabled in my spring config the log shows that job-daily-tran-counts takes roughly 2.5 minutes to execute...

[INFO] 2014-03-19 07:15:00,187 org.springframework.batch.core.launch.support.SimpleJobLauncher run - Job: [FlowJob: [name=job-daily-tran-counts]] launched with the following parameters: [{run date=1395173700052}]
[INFO] 2014-03-19 07:17:43,934 org.springframework.batch.core.launch.support.SimpleJobLauncher run - Job: [FlowJob: [name=job-daily-tran-counts]] completed with the following parameters: [{run date=1395173700052}] and the following status: [COMPLETED]

When I had only the both jobs enabled in my spring config the log shows that job-daily-tran-counts takes roughly only 8 milliseconds when it should take longer. i.e. It is doing nothing...

[INFO] 2014-04-15 07:15:00,225 org.springframework.batch.core.launch.support.SimpleJobLauncher run - Job: [FlowJob: [name=job-daily-tran-counts]] launched with the following parameters: [{run date=1397510100128}]
[INFO] 2014-04-15 07:15:08,977 org.springframework.batch.core.launch.support.SimpleJobLauncher run - Job: [FlowJob: [name=job-daily-tran-counts]] completed with the following parameters: [{run date=1397510100128}] and the following status: [COMPLETED]
[INFO] 2014-04-15 07:30:00,009 org.springframework.batch.core.launch.support.SimpleJobLauncher run - Job: [FlowJob: [name=job-bulletin-bar-msg-update]] launched with the following parameters: [{run date=1397511000007}]
[INFO] 2014-04-15 07:30:05,217 org.springframework.batch.core.launch.support.SimpleJobLauncher run - Job: [FlowJob: [name=job-bulletin-bar-msg-update]] completed with the following parameters: [{run date=1397511000007}] and the following status: [COMPLETED]


来源: stackexchange

问:
Dynamic jQuery PHP form doesn't send POST data to PHP var
much time is passed since last time here.

Hope you are all well and thanks in advance for your help.

So I'm working on a simple update, delete, add PHP page that modify MySQL database.

In this "admin" pages I have created a long form and inside I put a table that shows actual results extracted from database (there you can modify or delete singole voices) followed by another table that allow you to add new elements inside db.

I wanted to have a dynamic form for second table in order to make it a little bit more elegant so I added jQuery code for that purpose.

The two problems I'm finding and I'm not able to solve are:

(1) in one column of form/table cell I used two "radio" inputs to indicate availability, or not, of a products but, if I create an array of elements with the name "availableNew[ ]", all the radio elements have the same name so, when I add the new row to the form, radio voice selection switch from one input to another on different rows as it happens when you use many radio inputs with the same name (all radio inputs are seen as alternatives, not as different couple of inputs "yes/no" located on different rows) - sorry for horrible way of explaining problem but I was unable to find a clearer way to explain it;

(2) jQuery code used to add/delete new rows works great, but when I "submit" the form - with POST_[ ] command - page send only those input that weren't added with script (on the other hand I receive the data coming from the 1st row of the form).

To be more clear: I have created the first row of the table/form as a php echoed table/form, so only to add elements from the second row I uses jQuery script.
Than, when I send/post data to PHP, I receive only the first value of the array (corresponding to the first row of the table/form) but not the others (corresponding to the jQuery added rows).

So here are parts of the code I'm using:

1st part (Jquery code)

```<code><script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>

<script>
    $(document).ready(function(){
        $("#add-row").click(function(){

                        var dataNew = $("#dataNew").val();
                        var data = $("#data").val();
                        var counter = $("#countN").val();
                        counter++;

                        var markup = "<tr><td class='count'>" + counter + "<input type='hidden' id='countN' name='numN[]' value='" + counter + "'></td><td class='data'>" + dataNew + "<input type='hidden' id='data' name='todayN[]' value=" + data + "></td><td class='prod'><input type='text' id='prod' name='prodN[]' placeholder='Nuovo prodotto'></td><td class='var'><input type='text' id='var' name='varN[]' placeholder='Varietà'></td><td class='img'><input type='text' id='img' name='imgN[]' placeholder='Inserisci url della foto'></td><td class='available'><label class='choice' for='avaYnew'><input type='radio' id='avaYnew' name='availableN[]' value='yes' > Sì</label><label class='choice' for='avaNnew'><input type='radio' id='avaNnew' name='availableN[]' value='no' > No</label></td><td class='rows'><input type='button' class='delete-row' id='delete-row' value='Rimuovi'></td></tr>";

                        alert(markup);

                        $("#addProds").append(markup);
        });

                $("#delete-row").live('click', function(event) {
                $(this).parent().parent().remove();
                });
    });
</script>
</code>```

2nd part (PHP echo form/table code)

```<code><?php
            echo "<div>";
            echo "<form action=" . htmlspecialchars($_SERVER['PHP_SELF']) . " method='POST'>";

      //MOSTRA I RISULTATI
      $sqlMag = "SELECT * FROM elencoprodotti WHERE DATA = (SELECT MAX(DATA) FROM elencoprodotti) ORDER BY DATA DESC, PRODOTTO ASC";
      $resultMag = $conn->query($sqlMag);

      $count = 0;

      if (!empty($resultMag) && $resultMag->num_rows > 0) {

                echo "<br>Prodotti presenti nel database (ultimo aggiornamento al " . date("d.m.Y", strtotime($rowTit[0]))."):</div>";
                echo "<table>";
                echo "<thead><tr>";
                echo "<th>DB-ID</th>";
                echo "<th>N.</th>";
                echo "<th>Data</th>";
                echo "<th>Prodotto</th>";
                echo "<th>Varietà</th>";
                echo "<th>Foto</th>";
                echo "<th>Disponibilità</th>";
                echo "<th>Cancella</th>";
                echo "</tr></thead>";

      // output data of each row
            while($rowMag = $resultMag->fetch_assoc()) {
                $count++;

                        $AvailYes = $AvailNo = '';

                        if ((($rowMag["AVAILABLE"])) == "yes") {
                            $AvailYes = "checked";
                            $AvailNo = "";
                        } else if ((($rowMag["AVAILABLE"])) == "no") {
                            $AvailYes = "";
                            $AvailNo = "checked";
                        }

                echo "<tr>
                        <td class='id'>" . stripslashes($rowMag["ID"]) . "<input type='hidden' id='id' name='id-" .  stripslashes($count) . "' value=" . stripslashes($rowMag["ID"]) . "></td>
                        <td class='count'>" . stripslashes($count) . "<input type='hidden' id='count' name='num-" .  stripslashes($count) . "' value=" . stripslashes($count) . "></td>
                        <td class='data'>" . date("d-m-Y", strtotime(stripslashes($rowMag["DATA"]))) . "<input type='hidden' id='data' name='today-" . stripslashes($count) . "' value=" . $data . "></td>
                        <td class='prod'><input type='text' id='prod' name='prod-" . stripslashes($count) . "' value=" . stripslashes($rowMag["PRODOTTO"]) . "></td>
                        <td class='var'><input type='text' id='var' name='var-" . stripslashes($count) . "' value=" . stripslashes($rowMag["VARIETA"]) . "></td>
                        <td class='img'><a id='single_image' href=" . stripslashes(base64_decode($rowMag['FOTO'])) . " title=".stripslashes($rowMag["PRODOTTO"])." ".stripslashes($rowMag["VARIETA"]).">
                            <img id='imageprod' alt=".stripslashes($rowMag["PRODOTTO"])." ".stripslashes($rowMag["VARIETA"])." src=" .stripslashes(base64_decode($rowMag['FOTO'])). "></a>
                            <br><input type='hidden' id='img' name='img-" . stripslashes($count) . "' value=" . stripslashes(base64_decode($rowMag['FOTO'])) . "></td>
                        <td class='available'>
                        <label class='choice' for='avaY'><input type='radio' id='avaY' name='available-" . stripslashes($count) . "' value='yes' $AvailYes> Sì</label>
                        <label class='choice' for='avaN'><input type='radio' id='avaN' name='available-" . stripslashes($count) . "' value='no' $AvailNo> No</label>
                        </td>
                        <td class='delete'>
                        <label class='choice' for='del'><input type='checkbox' id='del' name='del-" . stripslashes($count) . "' value='canc'> rimuovi</label></td>
                        </tr>";
              }
          echo "</table>";
                echo "<input type='hidden' id='count' name='maxrows' value=" . stripslashes($count) . ">";
                echo "<br>";

                $insN = 1;
                echo "<input type='hidden' id='insN' name='insN' value=" . stripslashes($insN) . ">";
                //$insN++;
                echo "<div>";
                echo "<br>Inserisci nuovi prodotti nel database:</div>";
                echo "<table id='addProds'>";
                echo "<thead><tr>";
                echo "<th>N.</th><th>Data</th><th>Prodotto</th><th>Varietà</th><th>Foto</th><th>Disponibilità</th><th>+/-</th>";
                echo "</tr></thead>";
                echo "<tr>";
                echo "<td class='count'>" . stripslashes($insN) . "<input type='hidden' id='count' name='numN[]' value=" . stripslashes($insN) . "></td>
                <td class='data'>" . date("d-m-Y", strtotime(stripslashes($data))) . "<input type='hidden' id='data' name='todayN[]' value=" . $data . "><input type='hidden' id='dataNew' name='todayNew[]' value=" . date("d-m-Y", strtotime(stripslashes($data))) . "></td>
                <td class='prod'><input type='text' id='prod' name='prodN[]' placeholder='Nuovo prodotto' value=''></td>
                <td class='var'><input type='text' id='var' name='varN[]' placeholder='Varietà' value=''></td>
                <td class='img'><input type='text' id='img' name='imgN[]' placeholder='Inserisci url della foto' value=''></td>
                <td class='available'>
                <label class='choice' for='avaYnew'><input type='radio' id='avaYnew' name='availableN[]' value='yes' > Sì</label>
                <label class='choice' for='avaNnew'><input type='radio' id='avaNnew' name='availableN[]' value='no' > No</label>
                </td>
                <td class='rows'><input type='button' class='add-row' id='add-row' value='Aggiungi riga'></td>
                </tr>
                </table>";
                echo "<input type='hidden' id='countN' name='insN' value=" . stripslashes($insN) . ">";
                //echo "<input type='hidden' id='countTotN' name='maxNewrows' value=" . stripslashes($insN) . ">";

                echo "<br><div class='button-section'><input type='submit' class='mod' name='Sign Up' value='Modifica' /></div>";
                echo "</form>";
          } else {
                    echo "<p>Nessun risultato presente nel database - <a href='...viewdbadmin.php'>aggiorna la pagina</a>.</p></div>";
                    echo "</form>";
                }

    mysqli_close($conn);
        echo "</div>";
?>
</code>```

3rd part (PHP receive data and loop throw the array to insert it into the database)

```<code><?php
        //da qui INSERT DATA
        if (!empty($_POST["prodN"])) {

            echo "<br>*************************** QUINDI prodN[] NON E' EMPTY **************************************<br>";
            // FAI UN LOOP TRA TUTTE LE RIGHE NEW

            $numR = $_POST['numN'];
            var_dump($numR);
            echo "<br>";
            //echo "<br>*************************** numR = $numR **************************************<br>";
            $dataR = $_POST['todayN'];
            var_dump($dataR);
            echo "<br>";
            //echo "<br>*************************** todayN = $dataR **************************************<br>";
            $prodR = $_POST['prodN'];
            var_dump($prodR);
            echo "<br>";
            //echo "<br>*************************** prodR = $prodR **************************************<br>";
            $varR = $_POST['varN'];
            var_dump($varR);
            echo "<br>";
            //echo "<br>*************************** varR = $varR **************************************<br>";
            $imgR = $_POST['imgN'];
            var_dump($imgR);
            echo "<br>";
            //echo "<br>*************************** imgR = $imgR **************************************<br>";
            $availableR = ($_POST['availableN']);
            var_dump($availableR);
            echo "<br>";
            echo "<br>*************************** availableR = $availableR **************************************<br>";
            for ($r=0; $r<count($prodR); $r++) {
            if ($numR[$r] != "" && $dataR[$r] != "" && $prodR[$r] != "" && $varR[$r] != "" && $imgR[$r] != "" && $availableR[$r] != "") {
                    //insert function
                    require_once('datainsert.php');
                    insertProds($conn, $numR[$r], $dataR[$r], $prodR[$r], $varR[$r], $imgR[$r], $availableR[$r]);
                    }
                }
//END
        }
?>

</code>```

I'm totally sure it's not an elegant code the one I've written, but works great for the purpose I need, so pls be kind because I'm not a professional programmer and I'm doing this as a challenge for my parents.

Thanks in advance for your time and help.

UPDATE1

While I'm waiting an answer I've tried two possibile different solution.

The 1st was to simply move all the code at the bottom of the page (my thought were "maybe I'm a problem of position", but what guess what? It didn't make any difference.

The 2nd was to try another code involving jQuery and Ajax POST method and so I've used this code:

```<code><script>
     $(document).ready(function(){
                var i = 1;
                $("#add-row").click(function(){
                        i++;

                        var dataNew = $("#dataNew").val();
                        var data = $("#data").val();
                        //var counter = $("#countN").val();
                        //alert("counter è:"+counter);
                        //counter++;

                        var markup = '<tr id="row' + i + '"><td class="count">' + i + '<input type="hidden" id="countN" name="numN[]" value=' + i + '></td><td class="data">' + dataNew + '<input type="hidden" id="data" name="todayN[]" value=' + data + '></td><td class="prod"><input type="text" id="prod" name="prodN[]" placeholder="Nuovo prodotto"></td><td class="var"><input type="text" id="var" name="varN[]" placeholder="Varietà"></td><td class="img"><input type="text" id="img" name="imgN[]" placeholder="Inserisci url della foto"></td><td class="available"><label class="choice" for="avaYnew"><input type="radio" id="avaYnew" name="availableN[]" value="yes" > Sì</label><label class="choice" for="avaNnew"><input type="radio" id="avaNnew" name="availableN[]" value="no" > No</label></td><td class="rows"><input type="button" name="delete-row" class="delete-row" id='+ i +' value="Rimuovi"></td></tr>';

                        alert(markup);
                        $("#addProds").append(markup);

                        //$("#countTotN").val(counter);
                        //var countTotN = $("#countTotN").val();
                        //$("#countN").val(counter);
         });

                $(document).on("click", ".delete-row", function() {
                    var button_id = $(this).attr("id");
                    altert(button_id);
                    $('#row' + button_id + '').remove();
                });

                $('#submit').click(function() {
                    $.ajax({
                        url:"viewdbadmin.php']",
                        method:"POST",
                        data:$('#items').serialize(),
                        success:function(data) {
                            alert(data);
                            $('#items')[0].reset();
                        }
                });
     });
    });
 </script>
</code>```

As a result, PHP kept working great, but jQuery appended data kept on being excluded from arrays containing data sent to PHP.
Infact I keep on receiving only the 1st data I insert in my form for new products (the one from the 1st row of the table) but any data from appended .

Thanks again, I hope someone will seems because I'm testing this part of code since a week but I'm not able to find a solution.

Sorry I've added an answer to ask how could I be more useful to receive your help.
How can I?
Thanks.

答:
SOLUTION

Dunno why, but it wasn't working because inside  there was this row just before the table:

```<code>echo "<br>Prodotti presenti nel database (ultimo aggiornamento al " . date("d.m.Y", strtotime($rowTit[0]))."):</div>";
</code>```

This part of table was used to show last date used for update.
Moving this row outside  solved the problem.

So the code now is (I hope it might help someone else):

```<code>      $sqlTit = "SELECT DATA FROM elencoprodotti WHERE DATA = (SELECT MAX(DATA) FROM elencoprodotti) ORDER BY DATA DESC LIMIT 1";
      $resultTit = $conn->query($sqlTit);

      if (!$resultTit) {
          echo 'Could not run query: ' . mysqli_error($conn);
          exit;
      }
            $rowTit = mysqli_fetch_row($resultTit);
            $lastUpd = date("d.m.Y", strtotime($rowTit[0]));

            echo "<div>";

            if (empty($lastUpd)) {
                echo "<br>Ultimo aggiornamento prodotti:<font color='red'> non disponibile</font></div>";
            } else {
                echo "<br>Prodotti presenti nel database (ultimo aggiornamento al " . $lastUpd ."):</div>";
            }

            echo "<form action=" . htmlspecialchars($_SERVER['PHP_SELF']) . " method='POST'>";

      //MOSTRA I RISULTATI
      $sqlMag = "SELECT * FROM elencoprodotti WHERE DATA = (SELECT MAX(DATA) FROM elencoprodotti) ORDER BY DATA DESC, PRODOTTO ASC";
      $resultMag = $conn->query($sqlMag);

      $count = 0;

      if (!empty($resultMag) && $resultMag->num_rows > 0) {

                echo "<table>";
</code>```

ContentLicense: CC BY-SA 4.0

Body:
much time is passed since last time here.

Hope you are all well and thanks in advance for your help.

So I'm working on a simple update, delete, add PHP page that modify MySQL database.

In this "admin" pages I have created a long form and inside I put a table that shows actual results extracted from database (there you can modify or delete singole voices) followed by another table that allow you to add new elements inside db.

I wanted to have a dynamic form for second table in order to make it a little bit more elegant so I added jQuery code for that purpose.

The two problems I'm finding and I'm not able to solve are:

(1) in one column of form/table cell I used two "radio" inputs to indicate availability, or not, of a products but, if I create an array of elements with the name "availableNew[ ]", all the radio elements have the same name so, when I add the new row to the form, radio voice selection switch from one input to another on different rows as it happens when you use many radio inputs with the same name (all radio inputs are seen as alternatives, not as different couple of inputs "yes/no" located on different rows) - sorry for horrible way of explaining problem but I was unable to find a clearer way to explain it;

(2) jQuery code used to add/delete new rows works great, but when I "submit" the form - with POST_[ ] command - page send only those input that weren't added with script (on the other hand I receive the data coming from the 1st row of the form).

To be more clear: I have created the first row of the table/form as a php echoed table/form, so only to add elements from the second row I uses jQuery script.
Than, when I send/post data to PHP, I receive only the first value of the array (corresponding to the first row of the table/form) but not the others (corresponding to the jQuery added rows).

So here are parts of the code I'm using:

1st part (Jquery code)

2nd part (PHP echo form/table code)

<?php
            echo "
";
            echo "<form action=" . htmlspecialchars($_SERVER['PHP_SELF']) . " method='POST'>";

      //MOSTRA I RISULTATI
      $sqlMag = "SELECT * FROM elencoprodotti WHERE DATA = (SELECT MAX(DATA) FROM elencoprodotti) ORDER BY DATA DESC, PRODOTTO ASC";
      $resultMag = $conn->query($sqlMag);

      $count = 0;

      if (!empty($resultMag) && $resultMag->num_rows > 0) {

                echo "
Prodotti presenti nel database (ultimo aggiornamento al " . date("d.m.Y", strtotime($rowTit[0]))."):
";
                echo "
";
                echo "

";
                echo "DB-ID	";
                echo "N.	";
                echo "Data	";
                echo "Prodotto	";
                echo "Varietà	";
                echo "Foto	";
                echo "Disponibilità	";
                echo "Cancella	";
                echo "

";

      // output data of each row
            while($rowMag = $resultMag->fetch_assoc()) {
                $count++;

                        $AvailYes = $AvailNo = '';

                        if ((($rowMag["AVAILABLE"])) == "yes") {
                            $AvailYes = "checked";
                            $AvailNo = "";
                        } else if ((($rowMag["AVAILABLE"])) == "no") {
                            $AvailYes = "";
                            $AvailNo = "checked";
                        }

                echo "

                        " . stripslashes($rowMag["ID"]) . "<input type='hidden' id='id' name='id-" .  stripslashes($count) . "' value=" . stripslashes($rowMag["ID"]) . ">
                        " . stripslashes($count) . "<input type='hidden' id='count' name='num-" .  stripslashes($count) . "' value=" . stripslashes($count) . ">
                        " . date("d-m-Y", strtotime(stripslashes($rowMag["DATA"]))) . "<input type='hidden' id='data' name='today-" . stripslashes($count) . "' value=" . $data . ">
                        <input type='text' id='prod' name='prod-" . stripslashes($count) . "' value=" . stripslashes($rowMag["PRODOTTO"]) . ">
                        <input type='text' id='var' name='var-" . stripslashes($count) . "' value=" . stripslashes($rowMag["VARIETA"]) . ">

<input type='hidden' id='img' name='img-" . stripslashes($count) . "' value=" . stripslashes(base64_decode($rowMag['FOTO'])) . ">

                        <input type='radio' id='avaY' name='available-" . stripslashes($count) . "' value='yes' $AvailYes> Sì
                        <input type='radio' id='avaN' name='available-" . stripslashes($count) . "' value='no' $AvailNo> No

                        <input type='checkbox' id='del' name='del-" . stripslashes($count) . "' value='canc'> rimuovi

";
              }
          echo "
";
                echo "<input type='hidden' id='count' name='maxrows' value=" . stripslashes($count) . ">";
                echo "
";

                $insN = 1;
                echo "<input type='hidden' id='insN' name='insN' value=" . stripslashes($insN) . ">";
                //$insN++;
                echo "
";
                echo "
Inserisci nuovi prodotti nel database:
";
                echo "
";
                echo "

";
                echo "N.	Data	Prodotto	Varietà	Foto	Disponibilità	+/-	";
                echo "

";
                echo "
";
                echo "" . stripslashes($insN) . "<input type='hidden' id='count' name='numN[]' value=" . stripslashes($insN) . ">
                " . date("d-m-Y", strtotime(stripslashes($data))) . "<input type='hidden' id='data' name='todayN[]' value=" . $data . "><input type='hidden' id='dataNew' name='todayNew[]' value=" . date("d-m-Y", strtotime(stripslashes($data))) . ">
                <input type='text' id='prod' name='prodN[]' placeholder='Nuovo prodotto' value=''>
                <input type='text' id='var' name='varN[]' placeholder='Varietà' value=''>
                <input type='text' id='img' name='imgN[]' placeholder='Inserisci url della foto' value=''>

                <input type='radio' id='avaYnew' name='availableN[]' value='yes' > Sì
                <input type='radio' id='avaNnew' name='availableN[]' value='no' > No

                <input type='button' class='add-row' id='add-row' value='Aggiungi riga'>

";
                echo "<input type='hidden' id='countN' name='insN' value=" . stripslashes($insN) . ">";
                //echo "<input type='hidden' id='countTotN' name='maxNewrows' value=" . stripslashes($insN) . ">";

                echo "

<input type='submit' class='mod' name='Sign Up' value='Modifica' />
";
                echo "</form>";
          } else {
                    echo "
Nessun risultato presente nel database - aggiorna la pagina.

";
                    echo "</form>";
                }

    mysqli_close($conn);
        echo "
";
?>

3rd part (PHP receive data and loop throw the array to insert it into the database)

<?php
        //da qui INSERT DATA
        if (!empty($_POST["prodN"])) {

            echo "
*************************** QUINDI prodN[] NON E' EMPTY **************************************
";
            // FAI UN LOOP TRA TUTTE LE RIGHE NEW

            $numR = $_POST['numN'];
            var_dump($numR);
            echo "
";
            //echo "
*************************** numR = $numR **************************************
";
            $dataR = $_POST['todayN'];
            var_dump($dataR);
            echo "
";
            //echo "
*************************** todayN = $dataR **************************************
";
            $prodR = $_POST['prodN'];
            var_dump($prodR);
            echo "
";
            //echo "
*************************** prodR = $prodR **************************************
";
            $varR = $_POST['varN'];
            var_dump($varR);
            echo "
";
            //echo "
*************************** varR = $varR **************************************
";
            $imgR = $_POST['imgN'];
            var_dump($imgR);
            echo "
";
            //echo "
*************************** imgR = $imgR **************************************
";
            $availableR = ($_POST['availableN']);
            var_dump($availableR);
            echo "
";
            echo "
*************************** availableR = $availableR **************************************
";
            for ($r=0; $r<count($prodR); $r++) {
            if ($numR[$r] != "" && $dataR[$r] != "" && $prodR[$r] != "" && $varR[$r] != "" && $imgR[$r] != "" && $availableR[$r] != "") {
                    //insert function
                    require_once('datainsert.php');
                    insertProds($conn, $numR[$r], $dataR[$r], $prodR[$r], $varR[$r], $imgR[$r], $availableR[$r]);
                    }
                }
//END
        }
?>

I'm totally sure it's not an elegant code the one I've written, but works great for the purpose I need, so pls be kind because I'm not a professional programmer and I'm doing this as a challenge for my parents.

Thanks in advance for your time and help.

UPDATE1

While I'm waiting an answer I've tried two possibile different solution.

The 1st was to simply move all the code at the bottom of the page (my thought were "maybe I'm a problem of position", but what guess what? It didn't make any difference.

The 2nd was to try another code involving jQuery and Ajax POST method and so I've used this code:

As a result, PHP kept working great, but jQuery appended data kept on being excluded from arrays containing data sent to PHP.
Infact I keep on receiving only the 1st data I insert in my form for new products (the one from the 1st row of the table) but any data from appended .

Thanks again, I hope someone will seems because I'm testing this part of code since a week but I'm not able to find a solution.

Sorry I've added an answer to ask how could I be more useful to receive your help.
How can I?
Thanks.

Body:
SOLUTION

Dunno why, but it wasn't working because inside  there was this row just before the table:

echo "<br>Prodotti presenti nel database (ultimo aggiornamento al " . date("d.m.Y", strtotime($rowTit[0]))."):</div>";

This part of table was used to show last date used for update.
Moving this row outside  solved the problem.

So the code now is (I hope it might help someone else):

      $sqlTit = "SELECT DATA FROM elencoprodotti WHERE DATA = (SELECT MAX(DATA) FROM elencoprodotti) ORDER BY DATA DESC LIMIT 1";
      $resultTit = $conn->query($sqlTit);

      if (!$resultTit) {
          echo 'Could not run query: ' . mysqli_error($conn);
          exit;
      }
            $rowTit = mysqli_fetch_row($resultTit);
            $lastUpd = date("d.m.Y", strtotime($rowTit[0]));

            echo "<div>";

            if (empty($lastUpd)) {
                echo "<br>Ultimo aggiornamento prodotti:<font color='red'> non disponibile</font></div>";
            } else {
                echo "<br>Prodotti presenti nel database (ultimo aggiornamento al " . $lastUpd ."):</div>";
            }

            echo "<form action=" . htmlspecialchars($_SERVER['PHP_SELF']) . " method='POST'>";

      //MOSTRA I RISULTATI
      $sqlMag = "SELECT * FROM elencoprodotti WHERE DATA = (SELECT MAX(DATA) FROM elencoprodotti) ORDER BY DATA DESC, PRODOTTO ASC";
      $resultMag = $conn->query($sqlMag);

      $count = 0;

      if (!empty($resultMag) && $resultMag->num_rows > 0) {

                echo "<table>";


问:
Does dart support operator overloading? (not to be confused with overriding)
This sounds like an exact duplicate of: Does dart support operator overloading

But the name is misleading, the question is about how to override existing operators (the == operator).

As far as I understand, overloading a function means having multiple implementations that vary only in their parameters, but not in the name of the function:

```<code>int max(int a, int b);
double max(double a, double b);
</code>```

By contrast, overriding means rewriting an existing implementation. Since the original function is replaced, there are no name clashes. This is common in OOP where you extend a base class and override its methods.

The docs say that there are overridable operators. So I see that you can implement custom operators. At the same time, dart does not support overloading methods. So, does dart support overloading operators?

Would it be possible to write the following code:

```<code>class Matrix{
  Matrix operator+(int b){//...};
  Matrix operator+(Matrix b({//...};
}
</code>```

答:
You've essentially answered your own question.

there are overridable operators. So I see that you can implement custom operators. At the same time, dart does not support overloading methods. So, does dart support overloading operators?

The Dart language specification says:

10.1.1 Operators

Operators are instance methods with special names.

Dart does not support overloading methods (or functions), operators are equivalent to methods, ergo, Dart does not support operator overloading.

Body:
This sounds like an exact duplicate of: Does dart support operator overloading

But the name is misleading, the question is about how to override existing operators (the == operator).

As far as I understand, overloading a function means having multiple implementations that vary only in their parameters, but not in the name of the function:

int max(int a, int b);
double max(double a, double b);

By contrast, overriding means rewriting an existing implementation. Since the original function is replaced, there are no name clashes. This is common in OOP where you extend a base class and override its methods.

The docs say that there are overridable operators. So I see that you can implement custom operators. At the same time, dart does not support overloading methods. So, does dart support overloading operators?

Would it be possible to write the following code:

class Matrix{
  Matrix operator+(int b){//...};
  Matrix operator+(Matrix b({//...};
}


问:
SQL query to pull out form entries where each value is a separate row
I have a models for a user built form as follows:

```<code>Form
  id
  title

FormField
  id
  type
  name
  label

FormEntry
  id
  form_id
  date

FormFieldEntry
  id
  form_entry_id
  form_field_id
  value
</code>```

I am trying to formulate a sql query on Form that will have the FormField labels as column names and the FormFieldEntry's as the values.

答:
The only way to accomplish what you seek is to use dynamic SQL. You must assemble the SQL statement string in code by querying for the column names and send it to the database. The resulting SQL statement you build might look something like:</p>

```<code>Select FFE.form_entry_id
    , Min( Case When FF.name = 'Foo' Then FFE.value End ) As `Foo`
    , Min( Case When FF.name = 'Bar' Then FFE.value End ) As `Bar`
    , ...
From FormFieldEntry As FFE
    Join FormField As FF
        On FF.id = FFE.form_field_id
Group By FFE.form_entry_id
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a models for a user built form as follows:

Form
  id
  title

FormField
  id
  type
  name
  label

FormEntry
  id
  form_id
  date

FormFieldEntry
  id
  form_entry_id
  form_field_id
  value

I am trying to formulate a sql query on Form that will have the FormField labels as column names and the FormFieldEntry's as the values.

Body:
The only way to accomplish what you seek is to use dynamic SQL. You must assemble the SQL statement string in code by querying for the column names and send it to the database. The resulting SQL statement you build might look something like:

Select FFE.form_entry_id
    , Min( Case When FF.name = 'Foo' Then FFE.value End ) As `Foo`
    , Min( Case When FF.name = 'Bar' Then FFE.value End ) As `Bar`
    , ...
From FormFieldEntry As FFE
    Join FormField As FF
        On FF.id = FFE.form_field_id
Group By FFE.form_entry_id


问:
How can we change the (a1|a2|a3 b1|b2|b3) to ((a1,a2,a3),(b1,b2,b3)) in spark scala
Convert the (a1|a2|a3 b1|b2|b3) to ((a1,a2,a3),(b1,b2,b3)) in spark scala.</p>

答:
Split your String to form a Seq

Convert Seq to DataFrame

Append the String with the appropriate prefix ( and postfix )

Map row => String

Collect the Dataframe as list

Concatenate the list with , and prefix ( and postfix )

```<code>import org.apache.spark.sql.functions._

object ParseAString {

  def main(args: Array[String]): Unit = {
    val spark = Constant.getSparkSess
    import spark.implicits._
    val inputStr = "a1|a2|a3 b1|b2|b3".split(" ").toSeq.toDF

    val result = inputStr
      .select( concat(lit("("),regexp_replace($"value","\\|",","),lit(")") ) )
      .map(row => {
        row.getString(0)
      })
      .collect().mkString(",")
    println(s"(${result})")

  }

}

</code>```

Body:
Split your String to form a Seq

Convert Seq to DataFrame

Append the String with the appropriate prefix ( and postfix )

Map row => String

Collect the Dataframe as list

Concatenate the list with , and prefix ( and postfix )

import org.apache.spark.sql.functions._

object ParseAString {

  def main(args: Array[String]): Unit = {
    val spark = Constant.getSparkSess
    import spark.implicits._
    val inputStr = "a1|a2|a3 b1|b2|b3".split(" ").toSeq.toDF

    val result = inputStr
      .select( concat(lit("("),regexp_replace($"value","\\|",","),lit(")") ) )
      .map(row => {
        row.getString(0)
      })
      .collect().mkString(",")
    println(s"(${result})")

  }

}


问:
Get Row value as Column Header
I have two tables as below. I want to join these two tables and need to set the column values of second table as column header as shown  below. How can I achieve this?

Table1

```<code>ID       NAME
---------------
1        AAA
2        BBB
</code>```

table2

```<code>ID         QUESTION         ANSWER
----------------------------------
1              Q1             YES
1              Q2             NO
1              Q3             YES
1              Q4             NO
1              Q5             YES
2              Q1             YES
2              Q2             YES
2              Q3             YES
2              Q4             YES
2              Q5             YES
</code>```

The output table should be

```<code>   ID      NAME       Q1     Q2      Q3     Q4      Q5
   ----------------------------------------------------
   1       AAA        YES    NO     YES     NO      YES
   2       BBB        YES    YES    YES     YES     YES
</code>```

答:
You must use Pivot to write this query:

```<code>Sample Data:

DECLARE @Table1 TABLE( id int, name nvarchar(10));
DECLARE @Table2 TABLE( id int, Question nvarchar(10),Answer nvarchar(10))

insert into @Table1 (id,[name])values(1,'AAA')
insert into @Table1 (id,[name])values(2,'BBB')

insert into @Table2 (id,Question,Answer)values(1,'Q1','YES')
insert into @Table2 (id,Question,Answer)values(1,'Q2','NO')
insert into @Table2 (id,Question,Answer)values(1,'Q3','YES')
insert into @Table2 (id,Question,Answer)values(1,'Q4','NO')
insert into @Table2 (id,Question,Answer)values(1,'Q5','YES')
insert into @Table2 (id,Question,Answer)values(2,'Q1','YES')
insert into @Table2 (id,Question,Answer)values(2,'Q2','YES')
insert into @Table2 (id,Question,Answer)values(2,'Q3','YES')
insert into @Table2 (id,Question,Answer)values(2,'Q4','YES')
insert into @Table2 (id,Question,Answer)values(2,'Q5','YES')

select * from @Table1 t1
inner join (
select * from(
select
t2.id
,t2.Question
,t2.Answer
from @Table2 t2
)temp
pivot
    (
    MAX(Answer)
    for question in ([Q1],[Q2],[Q3],[Q4],[Q5])
    ) as PivotTable
)TemporaryTable on t1.id=TemporaryTable.id
</code>```

if your Questions are Dynamic, you can write like this

```<code>Declare @cols nvarchar(MAX);
Declare @query nvarchar(MAX);
    set @cols=( select STRING_AGG('['+Question+']',',') from @Table2);
    set @query='
    select * from @Table1 t1
    inner join (
    select * from(
    select
    t2.id
    ,t2.Question
    ,t2.Answer
    from @Table2 t2
    )temp
    pivot
        (
        MAX(Answer)
        for question in ('+@cols+')
        ) as PivotTable
    )TemporaryTable on t1.id=TemporaryTable.id
    '
    exec sp_executesql  @query
</code>```

Title: Get Row value as Column Header

Body:
I have two tables as below. I want to join these two tables and need to set the column values of second table as column header as shown  below. How can I achieve this?

Table1

ID       NAME
---------------
1        AAA
2        BBB

table2

ID         QUESTION         ANSWER
----------------------------------
1              Q1             YES
1              Q2             NO
1              Q3             YES
1              Q4             NO
1              Q5             YES
2              Q1             YES
2              Q2             YES
2              Q3             YES
2              Q4             YES
2              Q5             YES

The output table should be

   ID      NAME       Q1     Q2      Q3     Q4      Q5
   ----------------------------------------------------
   1       AAA        YES    NO     YES     NO      YES
   2       BBB        YES    YES    YES     YES     YES

Body:
You must use Pivot to write this query:

Sample Data:

DECLARE @Table1 TABLE( id int, name nvarchar(10));
DECLARE @Table2 TABLE( id int, Question nvarchar(10),Answer nvarchar(10))

insert into @Table1 (id,[name])values(1,'AAA')
insert into @Table1 (id,[name])values(2,'BBB')

insert into @Table2 (id,Question,Answer)values(1,'Q1','YES')
insert into @Table2 (id,Question,Answer)values(1,'Q2','NO')
insert into @Table2 (id,Question,Answer)values(1,'Q3','YES')
insert into @Table2 (id,Question,Answer)values(1,'Q4','NO')
insert into @Table2 (id,Question,Answer)values(1,'Q5','YES')
insert into @Table2 (id,Question,Answer)values(2,'Q1','YES')
insert into @Table2 (id,Question,Answer)values(2,'Q2','YES')
insert into @Table2 (id,Question,Answer)values(2,'Q3','YES')
insert into @Table2 (id,Question,Answer)values(2,'Q4','YES')
insert into @Table2 (id,Question,Answer)values(2,'Q5','YES')

select * from @Table1 t1
inner join (
select * from(
select
t2.id
,t2.Question
,t2.Answer
from @Table2 t2
)temp
pivot
    (
    MAX(Answer)
    for question in ([Q1],[Q2],[Q3],[Q4],[Q5])
    ) as PivotTable
)TemporaryTable on t1.id=TemporaryTable.id

if your Questions are Dynamic, you can write like this

Declare @cols nvarchar(MAX);
Declare @query nvarchar(MAX);
    set @cols=( select STRING_AGG('['+Question+']',',') from @Table2);
    set @query='
    select * from @Table1 t1
    inner join (
    select * from(
    select
    t2.id
    ,t2.Question
    ,t2.Answer
    from @Table2 t2
    )temp
    pivot
        (
        MAX(Answer)
        for question in ('+@cols+')
        ) as PivotTable
    )TemporaryTable on t1.id=TemporaryTable.id
    '
    exec sp_executesql  @query


问:
Value is overriding with last if always
I tried to use multiple if-then-else blocks but it gave "else without if" problem then I changed it into the following code but it's giving always last if value, it does not exit at the first "safe" value.

```<code>Range("AD" & i - 1).Select
Range("AD" & i - 1).Value = 0.3
If Range("AN" & i - 1) = "Safe" Then
Range("AD" & i - 1).Value = 0.3
ElseIf Range("AN" & i - 1) = "Not Safe" Then Range("AD" & i - 1).Value = 0.35
End If
If Range("AN" & i - 1) = "Safe" Then
Range("AD" & i - 1).Value = 0.35
ElseIf Range("AN" & i - 1) = "Not Safe" Then Range("AD" & i - 1).Value = 0.4
End If
If Range("AN" & i - 1) = "Safe" Then
Range("AD" & i - 1).Value = 0.4
ElseIf Range("AN" & i - 1) = "Not Safe" Then Range("AD" & i - 1).Value = 0.45
End If
If Range("AN" & i - 1) = "Safe" Then
Range("AD" & i - 1).Value = 0.45
ElseIf Range("AN" & i - 1) = "Not Safe" Then Range("AD" & i - 1).Value = 0.5
End If
</code>```

Following code is alternative to last one

```<code>Range("AD" & i - 1).Value = 0.3
If Range("AN" & i - 1) = "Safe" Then
Range("AD" & i - 1).Value = 0.3
ElseIf Range("AN" & i - 1) = "Not Safe" Then Range("AD" & i - 1).Value = 0.35
ElseIf Range("AN" & i - 1) = "Safe" Then Range("AD" & i - 1).Value = 0.35
ElseIf Range("AN" & i - 1) = "Not Safe" Then Range("AD" & i - 1).Value = 0.4
ElseIf Range("AN" & i - 1) = "Safe" Then Range("AD" & i - 1).Value = 0.4
ElseIf Range("AN" & i - 1) = "Not Safe" Then Range("AD" & i - 1).Value = 0.45
ElseIf Range("AN" & i - 1) = "Safe" Then Range("AD" & i - 1).Value = 0.45
End If
</code>```

but this is exiting after giving the value 0.35 only and not looking for the next lines

答:
This is your original code indented:

```<code>Sub Test()

    Range("AD" & i - 1).Select
    Range("AD" & i - 1).Value = 0.3

    If Range("AN" & i - 1) = "Safe" Then
        Range("AD" & i - 1).Value = 0.3
    ElseIf Range("AN" & i - 1) = "Not Safe" Then
        Range("AD" & i - 1).Value = 0.35
    End If

    If Range("AN" & i - 1) = "Safe" Then
        Range("AD" & i - 1).Value = 0.35
    ElseIf Range("AN" & i - 1) = "Not Safe" Then
        Range("AD" & i - 1).Value = 0.4
    End If

    If Range("AN" & i - 1) = "Safe" Then
        Range("AD" & i - 1).Value = 0.4
    ElseIf Range("AN" & i - 1) = "Not Safe" Then
        Range("AD" & i - 1).Value = 0.45
    End If

    If Range("AN" & i - 1) = "Safe" Then
        Range("AD" & i - 1).Value = 0.45
    ElseIf Range("AN" & i - 1) = "Not Safe" Then
        Range("AD" & i - 1).Value = 0.5
    End If

End Sub
</code>```

This code can be converted to this one:

```<code>Sub Test2()

    Range("AD" & i - 1) = 0.3
    If Range("AN" & i - 1) = "Safe" Then
        Range("AD" & i - 1).Value = 0.3
        Range("AD" & i - 1).Value = 0.35
        Range("AD" & i - 1).Value = 0.4
        Range("AD" & i - 1).Value = 0.45
    ElseIf Range("AN" & i - 1) = "Not Safe" Then
        Range("AD" & i - 1).Value = 0.35
        Range("AD" & i - 1).Value = 0.4
        Range("AD" & i - 1).Value = 0.45
        Range("AD" & i - 1).Value = 0.5
    End If

End Sub
</code>```

As you can see, you are only checking the value for Range("AN" & i - 1) and you are only checking if its safe or not. So what would the converted code do?
If it's safe will:

```<code>Range("AD" & i - 1).Value = 0.3
Range("AD" & i - 1).Value = 0.35
Range("AD" & i - 1).Value = 0.4
Range("AD" & i - 1).Value = 0.45
</code>```

Which means the value for Range("AD" & i - 1) will be the last one because VBA will run line by line.

The same will happen if it's not safe.

So you need to check for different conditions, or check in different cells or give value to different cells.

Edit: As for the OP's comment and goal this should do the trick:

```<code>Sub Test2()

    'Here we have the values that we will input to turn the cell AN Safe
    'If needed you can change (1 to 4) to (1 to x) yo increment or decrement the values
    Dim Values(1 To 4) As Single

    'here we populate the array with the values:
    Values(1) = 0.35
    Values(2) = 0.4
    Values(3) = 0.45
    Values(4) = 0.5

    'A Range variable to loop through the cells in column AD from row 13 to the last
    Dim C As Range
    Dim i As Long
    With ThisWorkbook.Sheets("Med Drain - 246 to 264 Km")
        For Each C In .Range("AD13", .Cells(.Rows.Count, "AD").End(xlUp))
            'Here we check if AN is safe or empty to ignore the row if true
            If .Cells(C.Row, "AN") = vbNullString Or .Cells(C.Row, "AN") = "Safe" Then GoTo SkipRow
            'Now we loop through the values inside the Values array and change the AD cell value
            For i = LBound(Values) To UBound(Values)
                'Change AD Value for the first in our array
                C = Values(i)
                'Recalculate the formulas
                .Calculate
                'If AN is now Safe then we exit this inner loop
                If .Cells(C.Row, "AN") = "Safe" Then Exit For
            Next i
SkipRow:
        Next C
    End With

End Sub
</code>```

Title: Value is overriding with last if always

Body:
I tried to use multiple if-then-else blocks but it gave "else without if" problem then I changed it into the following code but it's giving always last if value, it does not exit at the first "safe" value.

Range("AD" & i - 1).Select
Range("AD" & i - 1).Value = 0.3
If Range("AN" & i - 1) = "Safe" Then
Range("AD" & i - 1).Value = 0.3
ElseIf Range("AN" & i - 1) = "Not Safe" Then Range("AD" & i - 1).Value = 0.35
End If
If Range("AN" & i - 1) = "Safe" Then
Range("AD" & i - 1).Value = 0.35
ElseIf Range("AN" & i - 1) = "Not Safe" Then Range("AD" & i - 1).Value = 0.4
End If
If Range("AN" & i - 1) = "Safe" Then
Range("AD" & i - 1).Value = 0.4
ElseIf Range("AN" & i - 1) = "Not Safe" Then Range("AD" & i - 1).Value = 0.45
End If
If Range("AN" & i - 1) = "Safe" Then
Range("AD" & i - 1).Value = 0.45
ElseIf Range("AN" & i - 1) = "Not Safe" Then Range("AD" & i - 1).Value = 0.5
End If

Following code is alternative to last one

Range("AD" & i - 1).Value = 0.3
If Range("AN" & i - 1) = "Safe" Then
Range("AD" & i - 1).Value = 0.3
ElseIf Range("AN" & i - 1) = "Not Safe" Then Range("AD" & i - 1).Value = 0.35
ElseIf Range("AN" & i - 1) = "Safe" Then Range("AD" & i - 1).Value = 0.35
ElseIf Range("AN" & i - 1) = "Not Safe" Then Range("AD" & i - 1).Value = 0.4
ElseIf Range("AN" & i - 1) = "Safe" Then Range("AD" & i - 1).Value = 0.4
ElseIf Range("AN" & i - 1) = "Not Safe" Then Range("AD" & i - 1).Value = 0.45
ElseIf Range("AN" & i - 1) = "Safe" Then Range("AD" & i - 1).Value = 0.45
End If

but this is exiting after giving the value 0.35 only and not looking for the next lines

Body:
This is your original code indented:

Sub Test()

    Range("AD" & i - 1).Select
    Range("AD" & i - 1).Value = 0.3

    If Range("AN" & i - 1) = "Safe" Then
        Range("AD" & i - 1).Value = 0.3
    ElseIf Range("AN" & i - 1) = "Not Safe" Then
        Range("AD" & i - 1).Value = 0.35
    End If

    If Range("AN" & i - 1) = "Safe" Then
        Range("AD" & i - 1).Value = 0.35
    ElseIf Range("AN" & i - 1) = "Not Safe" Then
        Range("AD" & i - 1).Value = 0.4
    End If

    If Range("AN" & i - 1) = "Safe" Then
        Range("AD" & i - 1).Value = 0.4
    ElseIf Range("AN" & i - 1) = "Not Safe" Then
        Range("AD" & i - 1).Value = 0.45
    End If

    If Range("AN" & i - 1) = "Safe" Then
        Range("AD" & i - 1).Value = 0.45
    ElseIf Range("AN" & i - 1) = "Not Safe" Then
        Range("AD" & i - 1).Value = 0.5
    End If

End Sub

This code can be converted to this one:

Sub Test2()

    Range("AD" & i - 1) = 0.3
    If Range("AN" & i - 1) = "Safe" Then
        Range("AD" & i - 1).Value = 0.3
        Range("AD" & i - 1).Value = 0.35
        Range("AD" & i - 1).Value = 0.4
        Range("AD" & i - 1).Value = 0.45
    ElseIf Range("AN" & i - 1) = "Not Safe" Then
        Range("AD" & i - 1).Value = 0.35
        Range("AD" & i - 1).Value = 0.4
        Range("AD" & i - 1).Value = 0.45
        Range("AD" & i - 1).Value = 0.5
    End If

End Sub

As you can see, you are only checking the value for Range("AN" & i - 1) and you are only checking if its safe or not. So what would the converted code do?
If it's safe will:

Range("AD" & i - 1).Value = 0.3
Range("AD" & i - 1).Value = 0.35
Range("AD" & i - 1).Value = 0.4
Range("AD" & i - 1).Value = 0.45

Which means the value for Range("AD" & i - 1) will be the last one because VBA will run line by line.

The same will happen if it's not safe.

So you need to check for different conditions, or check in different cells or give value to different cells.

Edit: As for the OP's comment and goal this should do the trick:

Sub Test2()

    'Here we have the values that we will input to turn the cell AN Safe
    'If needed you can change (1 to 4) to (1 to x) yo increment or decrement the values
    Dim Values(1 To 4) As Single

    'here we populate the array with the values:
    Values(1) = 0.35
    Values(2) = 0.4
    Values(3) = 0.45
    Values(4) = 0.5

    'A Range variable to loop through the cells in column AD from row 13 to the last
    Dim C As Range
    Dim i As Long
    With ThisWorkbook.Sheets("Med Drain - 246 to 264 Km")
        For Each C In .Range("AD13", .Cells(.Rows.Count, "AD").End(xlUp))
            'Here we check if AN is safe or empty to ignore the row if true
            If .Cells(C.Row, "AN") = vbNullString Or .Cells(C.Row, "AN") = "Safe" Then GoTo SkipRow
            'Now we loop through the values inside the Values array and change the AD cell value
            For i = LBound(Values) To UBound(Values)
                'Change AD Value for the first in our array
                C = Values(i)
                'Recalculate the formulas
                .Calculate
                'If AN is now Safe then we exit this inner loop
                If .Cells(C.Row, "AN") = "Safe" Then Exit For
            Next i
SkipRow:
        Next C
    End With

End Sub


问:
Unknown custom element in Vuetify
I am new to Vuetify and vue. I am using vue and vuetify but due some reason I am not able open my page.The error I am getting when I run my project:

[Vue warn]: Unknown custom element:  - did you register the
  component correctly? For recursive components, make sure to provide
  the "name" option.

found in

--->  at resources/js/components/appContainer.vue

My code:

```<code>appContainer.vue

<template>
  <v-app id="inspire">
    <v-navigation-drawer
      v-model="drawer"
      app
    >
      <v-list dense>
        <v-list-item link>
          <v-list-item-action>
            <v-icon>mdi-home</v-icon>
          </v-list-item-action>
          <v-list-item-content>
            <v-list-item-title>Home</v-list-item-title>
          </v-list-item-content>
        </v-list-item>
        <v-list-item link>
          <v-list-item-action>
            <v-icon>mdi-contact-mail</v-icon>
          </v-list-item-action>
          <v-list-item-content>
            <v-list-item-title>Contact</v-list-item-title>
          </v-list-item-content>
        </v-list-item>
      </v-list>
    </v-navigation-drawer>

    <v-app-bar
      app
      color="indigo"
      dark
    >
      <v-app-bar-nav-icon @click.stop="drawer = !drawer"></v-app-bar-nav-icon>
      <v-toolbar-title>Application</v-toolbar-title>
    </v-app-bar>

    <v-content>
      <v-container
        class="fill-height"
        fluid
      >
        <v-row
          align="center"
          justify="center"
        >
          <v-col class="text-center">
            <v-tooltip left>
              <template v-slot:activator="{ on }">
                <v-btn
                  :href="source"
                  icon
                  large
                  target="_blank"
                  v-on="on"
                >
                  <v-icon large>mdi-code-tags</v-icon>
                </v-btn>
              </template>
              <span>Source</span>
            </v-tooltip>
          </v-col>
        </v-row>
      </v-container>
    </v-content>
    <v-footer
      color="indigo"
      app
    >
      <span class="white--text">© 2019</span>
    </v-footer>
  </v-app>
</template>

<script>
  export default {
    props: {
      source: String,
    },
    data: () => ({
      drawer: null,
    }),
  }
</script>
</code>```

app.js

```<code>require('./bootstrap');

window.Vue = require('vue');

import Vue from 'vue'

import Vuetify from './plugins/vuetify'

Vue.use(Vuetify);

Vue.component('app-container', require('./components/appContainer.vue').default);

const app = new Vue({
    Vuetify,
    Vue,
    el: '#app',
});
</code>```

spa.blade.php

```<code><!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'Laravel') }}</title>

    <!-- Scripts -->
    <script src="{{ asset('js/app.js') }}" defer></script>

    <!-- Fonts -->
    <link rel="dns-prefetch" href="//fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@mdi/font@5.x/css/materialdesignicons.min.css" rel="stylesheet">

    <!-- Styles -->
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
    <div id="app">
        <app-container></app-container>

    </div>
</body>
</html>
</code>```

vuetify.js

```<code>import Vue from 'vue'
import Vuetify from 'vuetify/lib'

Vue.use(Vuetify)

const opts = {}

export default new Vuetify(opts)
</code>```

答:
Try to change the drawer from null to false:</p>

```<code>data: () => ({
    drawer: false,
}),
</code>```

Title: Unknown custom element in Vuetify

Body:
I am new to Vuetify and vue. I am using vue and vuetify but due some reason I am not able open my page.The error I am getting when I run my project:

[Vue warn]: Unknown custom element:  - did you register the
  component correctly? For recursive components, make sure to provide
  the "name" option.

found in

--->  at resources/js/components/appContainer.vue

My code:

appContainer.vue

<template>
  <v-app id="inspire">
    <v-navigation-drawer
      v-model="drawer"
      app
    >
      <v-list dense>
        <v-list-item link>
          <v-list-item-action>
            <v-icon>mdi-home</v-icon>
          </v-list-item-action>
          <v-list-item-content>
            <v-list-item-title>Home</v-list-item-title>
          </v-list-item-content>
        </v-list-item>
        <v-list-item link>
          <v-list-item-action>
            <v-icon>mdi-contact-mail</v-icon>
          </v-list-item-action>
          <v-list-item-content>
            <v-list-item-title>Contact</v-list-item-title>
          </v-list-item-content>
        </v-list-item>
      </v-list>
    </v-navigation-drawer>

    <v-app-bar
      app
      color="indigo"
      dark
    >
      <v-app-bar-nav-icon @click.stop="drawer = !drawer"></v-app-bar-nav-icon>
      <v-toolbar-title>Application</v-toolbar-title>
    </v-app-bar>

    <v-content>
      <v-container
        class="fill-height"
        fluid
      >
        <v-row
          align="center"
          justify="center"
        >
          <v-col class="text-center">
            <v-tooltip left>
              <template v-slot:activator="{ on }">
                <v-btn
                  :href="source"
                  icon
                  large
                  target="_blank"
                  v-on="on"
                >
                  <v-icon large>mdi-code-tags</v-icon>
                </v-btn>
              </template>
              Source
            </v-tooltip>
          </v-col>
        </v-row>
      </v-container>
    </v-content>
    <v-footer
      color="indigo"
      app
    >
      © 2019
    </v-footer>
  </v-app>
</template>

app.js

require('./bootstrap');

window.Vue = require('vue');

import Vue from 'vue'

import Vuetify from './plugins/vuetify'

Vue.use(Vuetify);

Vue.component('app-container', require('./components/appContainer.vue').default);

const app = new Vue({
    Vuetify,
    Vue,
    el: '#app',
});

spa.blade.php

<!doctype html>
getLocale()) }}">

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'Laravel') }}</title>

    <link rel="dns-prefetch" href="//fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@mdi/font@5.x/css/materialdesignicons.min.css" rel="stylesheet">

    <link href="{{ asset('css/app.css') }}" rel="stylesheet">

        <app-container></app-container>

vuetify.js

import Vue from 'vue'
import Vuetify from 'vuetify/lib'

Vue.use(Vuetify)

const opts = {}

export default new Vuetify(opts)

Body:
Try to change the drawer from null to false:

data: () => ({
    drawer: false,
}),


问:
How to convert tf.contrib to Tensorflow 2.0
So I'm trying to implement object detection using Tensorflow and a part of my code uses tf.contrib. The problem is tf.contrib is not supported in Tensorflow 2.0.

I've tried using the tf_upgrade_v2 script but I get the following message:

ERROR: Using member tf.contrib.slim in deprecated module tf.contrib. tf.contrib.slim cannot be converted automatically. tf.contrib will not be distributed with TensorFlow 2.0, please consider an alternative in non-contrib TensorFlow, a community-maintained repository such as tensorflow/addons, or fork the required code.

import functools
import tensorflow as tf
from object_detection.core import box_predictor
from object_detection.utils import shape_utils
from object_detection.utils import static_shape

slim = tf.contrib.slim
```

答:
Since all the projects in tf.contrib were not officially supported by Tensorflow and it had designated owners for maintaining it.

 All the contributions and features were meant to merge into core Tensorflow.

From the Tensorflow 2.0 version all the contrib projects had one of three options for its future: move to core; move to a separate repository; or delete, most of which have been reviewed with the respective project owners.

This link provides the details and status for all the projects under tf.contrib.

If the library you are using is moved to the core or separate repository, the TensorFlow's automatic code migration from 1.x to 2.x will not work for tf.contrib projects.  You need to change your code manually for these parts, which is suggested going forward.

I can see in the table that tf.contrib.slim is moved to tensorflow/models , you can follow this link for the usage in detail.


问:
To create a class called Calculator which contains methods for arithmetic operations
The question is
Create a class called Calculator which contains methods for arithmetic operations such as Addition, Subtraction ,Multiplication and Division. Division method should return the Quotient and Remainder(hint:use out parameter).

Follow the method signatures as given below:

public int Addition(int a, int b)

public int Subtraction(int a, int b)

public int Multiplication(int a, int b)

public double Division(int a, int b, out double remainder).  //The method should  return the Quotient and Remainder  should be  passed through the out parameter.

The methods should return the appropriate result.

Create a class Program with Main Method . Prompt for 2 operands and operator from the user, Call the appropriate method for operation and display the results.

Note:

Don't create any new namespace.

Create classes with pubic access specifier

Sample Input

Enter the operator

+

Enter the operands

12

10

Sample Output

Result of 12 + 10 is 22

Sample Input

Enter the operator

/

Enter the operands

11

2

Sample Output

Result of 11 / 2 is 5

Remainder =1

Sample Input

Enter the operator

&

Enter the operands

12

10

Sample Output

Invalid Operator

My code is:

```<code>using System;

public class Program
{
    public static void Main(string[] args)
    {
        Console.WriteLine("Enter the operator");
        string sign = Console.ReadLine();
        Console.WriteLine("Enter the operands");
        int a = Convert.ToInt32(Console.ReadLine());
        int b = Convert.ToInt32(Console.ReadLine());
        Calculator cal = new Calculator();
        switch (sign)
        {
            case "+":
                Console.WriteLine("Result of " + a + " + " + b + " is " + cal.Addition(a,b));
                break;
            case "-":
                Console.WriteLine("Result of " + a + " - " + b + " is " + cal.Subtraction(a,b));
                break;
            case "*":
                Console.WriteLine("Result of " + a + " * " + b + " is " + cal.Multiplication(a,b));
                break;
            case "/":
                double[] ans = cal.Division(a,b, out remainder);
                Console.WriteLine("Result of " + a + " / " + b + " is " + ans[0]);
                Console.WriteLine("Remainder =" + (int)ans[1]);
                break;
            default:
                Console.WriteLine("Invalid Operator");
                break;
        }
    }

}
internal class Calculator
{
    public virtual int Addition(int a, int b)
    {
        return a + b;
    }
    public virtual int Subtraction(int a, int b)
    {
        return a - b;
    }
    public virtual int Multiplication(int a, int b)
    {
        return a * b;
    }
    public virtual double[] Division(int a, int b,out double remainder)
    {
        return new double[]{a / b, a % b};
    }
}
</code>```

Error:

Proposed grade: 0 / 100
Result Description
 COMPILE TIME ERROR``
Comment :=>> CalculatorProgram.cs(25,42): error CS0103: The name remainder' does not exist in the current context
CalculatorProgram.cs(50,59): error CS0177: The out parameterremainder' must be assigned to before control leaves the current method
Grade :=>> 0

答:
Your problem is here:

```<code>public virtual double[] Division(int a, int b,out double remainder)
</code>```

Lets see what this signature tells us:

Its called Division so it will probably divide two numbers. What type of division is not altogether clear.

Integer arguments a and b are probably the numbers used in the division. But its not clear which is the dividend and which is the divisor. a is probably the former and b is probably the later. RULE: if there are a lot of probably's in the way to use a given method, then something is not right. Consider naming a and b to something that identifies them clearly.

The method accepts a double variable passed by reference remainder that must be set before the method Division returns (that's what out means). The value is the remainder of the division operation. But wait, the remainder of the division of two integers is always an integer, why declare it as a double?

The method returns a double array. Ok, that doesn't make much sense. The division of two numbers is a number, so this method should return a double, not an array of doubles. But wait... that doesn't make sense either. If you are returning through the out parameter the remainder of the division of two natural numbers, then we are performing an Euclidean division and therefore the returned value should be the quotient of the division.

The method is marked as virtual. There is no apparent reason why this method sould be virtual so don't declare it as such. Always remember; making a non virtual method later on virtual is much easier than making a virtual method later on non virtual.

With all that, our signature would look like:

```<code> public int EuclideanDivision(int dividend, int divisor, out int remainder)
</code>```

And the implementation is straighforward:

```<code>remainder = .... //remember, the out argument must be initialized before the method returns!
var quotient = ....
return quotient;
</code>```

That said, it seems the problem states you should use the following signature, which doesn't change the solution:

```<code>public double EuclideanDivision(int dividend, int divisor, out double remainder)
</code>```

You can probably earn extra points in your homework pointing out that this signature is improvable.

Body:
The question is
Create a class called Calculator which contains methods for arithmetic operations such as Addition, Subtraction ,Multiplication and Division. Division method should return the Quotient and Remainder(hint:use out parameter).

Follow the method signatures as given below:

public int Addition(int a, int b)

public int Subtraction(int a, int b)

public int Multiplication(int a, int b)

public double Division(int a, int b, out double remainder).  //The method should  return the Quotient and Remainder  should be  passed through the out parameter.

The methods should return the appropriate result.

Create a class Program with Main Method . Prompt for 2 operands and operator from the user, Call the appropriate method for operation and display the results.

Note:

Don't create any new namespace.

Create classes with pubic access specifier

Sample Input

Enter the operator

+

Enter the operands

12

10

Sample Output

Result of 12 + 10 is 22

Sample Input

Enter the operator

/

Enter the operands

11

2

Sample Output

Result of 11 / 2 is 5

Remainder =1

Sample Input

Enter the operator

&

Enter the operands

12

10

Sample Output

Invalid Operator

My code is:

using System;

public class Program
{
    public static void Main(string[] args)
    {
        Console.WriteLine("Enter the operator");
        string sign = Console.ReadLine();
        Console.WriteLine("Enter the operands");
        int a = Convert.ToInt32(Console.ReadLine());
        int b = Convert.ToInt32(Console.ReadLine());
        Calculator cal = new Calculator();
        switch (sign)
        {
            case "+":
                Console.WriteLine("Result of " + a + " + " + b + " is " + cal.Addition(a,b));
                break;
            case "-":
                Console.WriteLine("Result of " + a + " - " + b + " is " + cal.Subtraction(a,b));
                break;
            case "*":
                Console.WriteLine("Result of " + a + " * " + b + " is " + cal.Multiplication(a,b));
                break;
            case "/":
                double[] ans = cal.Division(a,b, out remainder);
                Console.WriteLine("Result of " + a + " / " + b + " is " + ans[0]);
                Console.WriteLine("Remainder =" + (int)ans[1]);
                break;
            default:
                Console.WriteLine("Invalid Operator");
                break;
        }
    }

}
internal class Calculator
{
    public virtual int Addition(int a, int b)
    {
        return a + b;
    }
    public virtual int Subtraction(int a, int b)
    {
        return a - b;
    }
    public virtual int Multiplication(int a, int b)
    {
        return a * b;
    }
    public virtual double[] Division(int a, int b,out double remainder)
    {
        return new double[]{a / b, a % b};
    }
}

Error:

Proposed grade: 0 / 100
Result Description
 COMPILE TIME ERROR``
Comment :=>> CalculatorProgram.cs(25,42): error CS0103: The name remainder' does not exist in the current context
CalculatorProgram.cs(50,59): error CS0177: The out parameterremainder' must be assigned to before control leaves the current method
Grade :=>> 0

Body:
Your problem is here:

public virtual double[] Division(int a, int b,out double remainder)

Lets see what this signature tells us:

Its called Division so it will probably divide two numbers. What type of division is not altogether clear.

Integer arguments a and b are probably the numbers used in the division. But its not clear which is the dividend and which is the divisor. a is probably the former and b is probably the later. RULE: if there are a lot of probably's in the way to use a given method, then something is not right. Consider naming a and b to something that identifies them clearly.

The method accepts a double variable passed by reference remainder that must be set before the method Division returns (that's what out means). The value is the remainder of the division operation. But wait, the remainder of the division of two integers is always an integer, why declare it as a double?

The method returns a double array. Ok, that doesn't make much sense. The division of two numbers is a number, so this method should return a double, not an array of doubles. But wait... that doesn't make sense either. If you are returning through the out parameter the remainder of the division of two natural numbers, then we are performing an Euclidean division and therefore the returned value should be the quotient of the division.

The method is marked as virtual. There is no apparent reason why this method sould be virtual so don't declare it as such. Always remember; making a non virtual method later on virtual is much easier than making a virtual method later on non virtual.

With all that, our signature would look like:

 public int EuclideanDivision(int dividend, int divisor, out int remainder)

And the implementation is straighforward:

remainder = .... //remember, the out argument must be initialized before the method returns!
var quotient = ....
return quotient;

That said, it seems the problem states you should use the following signature, which doesn't change the solution:

public double EuclideanDivision(int dividend, int divisor, out double remainder)

You can probably earn extra points in your homework pointing out that this signature is improvable.


问:
How to get the return value of xcodebuild?
I'm using xcodebuild inside a bash script on a continuous integration server.

I would like to know when a build as failed in the script, so I can exit prematurely from it and mark the build as failed.

xcodebuild displays a BUILD FAILED message to the console, but I don't succeed in getting a return value.

How can I achieve this?

Thanks in advance

答:
Generally, you can always check the exist value for the last run process in Unix bash by:

```<code>$ echo $?
</code>```

where $? is a built-in placeholder of the exist value of last executed command. For more details about other bash's built-in variables see here.

So, first run your command you want to investigate its return code, then run echo as above.

Body:
Generally, you can always check the exist value for the last run process in Unix bash by:

$ echo $?

where $? is a built-in placeholder of the exist value of last executed command. For more details about other bash's built-in variables see here.

So, first run your command you want to investigate its return code, then run echo as above.


问:
How can I delete all texts in my data using dplyr?
If my data looks like this:

```<code>q2_3  q2_4  q2_5
<chr> <chr> <chr>
1    1A    2B   3C
2    4D    5E   6F
</code>```

How can I delete only texts?

I want only numbers to remain!

答:
Also you can use parse_number() from readr package (which will extract first number from values):

```<code>library(readr)

data <- data.frame(q2_3 = c("1A", "4D"),
                   q2_4 = c("2B", "5E"),
                   q2_5 = c("3C", "6F"))

data[] <- lapply(data, parse_number)
</code>```

results in

```<code>> print(data)
  q2_3 q2_4 q2_5
1    1    2    3
2    4    5    6
</code>```

Body:
If my data looks like this:

q2_3  q2_4  q2_5
<chr> <chr> <chr>
1    1A    2B   3C
2    4D    5E   6F

How can I delete only texts?

I want only numbers to remain!

Body:
Also you can use parse_number() from readr package (which will extract first number from values):

library(readr)

data <- data.frame(q2_3 = c("1A", "4D"),
                   q2_4 = c("2B", "5E"),
                   q2_5 = c("3C", "6F"))

data[] <- lapply(data, parse_number)

results in

> print(data)
  q2_3 q2_4 q2_5
1    1    2    3
2    4    5    6


问:
what is the use of ! sign in some ruby methods

Possible Duplicate:

  Why are exclamation marks used in Ruby methods?

Hi All,

In ruby/rails I have seen some methods ended up with ! sign like

```<code>before_filter :authenticated!
</code>```

just wonder what does mean by authenticated!, '!' sign

thanks in advance

cheers

sameera

答:
if you ask most rails guys, they will say the bang version (!) means the method will throw an exception.

What I prefer is Greg Browns definition in Ruby Best Practices, which is that a bang is to indicate that there are two versions of a very similar method, but the bang one you need to pay more attention to

Body:
Possible Duplicate:

  Why are exclamation marks used in Ruby methods?

Hi All,

In ruby/rails I have seen some methods ended up with ! sign like

before_filter :authenticated!

just wonder what does mean by authenticated!, '!' sign

thanks in advance

cheers

sameera


问:
How to disable Quick Help in Xcode 11.5
I installed Xcode 11.5 and "Quick Help" keep popping up whenever I made a selection. This is really irritating as I need to dismiss it before I can continue. All the answers that I can find online are about re-enabling it, but how to disable it? I prefer to use it only when needed, not automatically pop-up every time. Thanks.</p>

答:
As it turned out, the issue was not entirely in Xcode. I installed Catalina OS followed by Xcode 11.5 and the symptom above appeared. After switching on/off some settings in System Preference, the "Quick Help on text selection" issue was resolved.

I disabled "Force Click and haptic feedback" under Trackpad. Guess it was the "press firmly" when selecting the text that triggered the Quick Help.

Title: How to disable Quick Help in Xcode 11.5


问:
Button inside the CollectionView repeating the first cell information
i am creating images app from my Wordpress website's json using swift , i have created CollectionView and every cell displaying images and working fine but i want to add show comment in every cell for each post, its showing the exact comments for every post/cell but when i click on it it shows the comments of very first post of collection view. this is my code to show comments and for clickable button.

```<code> func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! homeViewCell

    let url = dataArray[indexPath.row]["thumbnail_images"]["medium"]["url"].stringValue
    cell.imageArticle.sd_setImage(with: NSURL(string: url) as URL?, placeholderImage:UIImage(named: "empty.png"))
     cell.nametag.text = String(htmlEncodedString:dataArray[indexPath.row]["tags"][0]["title"].stringValue)
    cell.nametagg.text =  String(htmlEncodedString:dataArray[indexPath.row]["categories"][0]["title"].stringValue)

    cell.fbButton.addTarget(self, action: #selector(homeController.fbClick), for: .touchUpInside)

    cell.commentButton.addTarget(self, action: #selector(homeController.comment), for: .touchUpInside)
    cell.commentButton.setTitle("\(dataArray[indexPath.row]["comment_count"].stringValue) comments", for: .normal)
    cell.leaveComment.addTarget(self, action: #selector(homeController.leavecomment), for: .touchUpInside)

   cell.contentline.text = String(htmlEncodedString:dataArray[indexPath.row]["excerpt"].stringValue)

 return cell
}
</code>```

and this is the code for button click

```<code>@objc func comment(_ sender: Any) {

  let vc = CommentViewController()
    vc.dataArray = dataArray[indexPath.row]["comments"].array
    self.navigationController!.pushViewController(vc, animated: true)

}
</code>```

i hope you understand my question, thanks

答:
You've declared the indexPath as a global variable and it's value is NSIndexPath(row: 0, section: 0) as you said.

in comments(_:) function you've used indexPath.row but this row is 0 so it is first post's comments.

You don't need to set tapgesture to cell's button.

In homeViewCell you should create IBAction for the button and call closure when it triggered ->

class homeViewCell: UICollectionViewCell {

    public var didTapComment: (() -> Void)?

    @IBAction func didTapCommentButton(_ sender: UIButton) {
        didTapComment?()
    }
}
```

<hr>

<p>Set <code>didTapComment</code>'s action in <code>cellForItemAt</code> like this -></p>

<pre class="lang-swift prettyprint-override"><code>func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! homeViewCell

    cell.didTapComment = { [weak self] in
        let vc = CommentViewController()
        vc.dataArray = dataArray[indexPath.row]["comments"].array
        self?.navigationController!.pushViewController(vc, animated: true)
    }

    let url = dataArray[indexPath.row]["thumbnail_images"]["medium"]["url"].stringValue

    cell.imageArticle.sd_setImage(with: NSURL(string: url) as URL?, placeholderImage:UIImage(named: "empty.png"))
    cell.nametag.text = String(htmlEncodedString:dataArray[indexPath.row]["tags"][0]["title"].stringValue)
    cell.nametagg.text =  String(htmlEncodedString:dataArray[indexPath.row]["categories"][0]["title"].stringValue)

    cell.fbButton.addTarget(self, action: #selector(homeController.fbClick), for: .touchUpInside)

    cell.commentButton.setTitle("\(dataArray[indexPath.row]["comment_count"].stringValue) comments", for: .normal)
    cell.leaveComment.addTarget(self, action: #selector(homeController.leavecomment), for: .touchUpInside)

    cell.contentline.text = String(htmlEncodedString:dataArray[indexPath.row]["excerpt"].stringValue)

    return cell
 }
}
</code>```

Remove followings;

cell.commentButton.addTarget(self, action: #selector(homeController.comment), for: .touchUpInside) line from cellForItemAt

@objc func comment(_ sender: Any) function

let indexPath = NSIndexPath(row: 0, section: 0)

Body:
i am creating images app from my Wordpress website's json using swift , i have created CollectionView and every cell displaying images and working fine but i want to add show comment in every cell for each post, its showing the exact comments for every post/cell but when i click on it it shows the comments of very first post of collection view. this is my code to show comments and for clickable button.

 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! homeViewCell

    let url = dataArray[indexPath.row]["thumbnail_images"]["medium"]["url"].stringValue
    cell.imageArticle.sd_setImage(with: NSURL(string: url) as URL?, placeholderImage:UIImage(named: "empty.png"))
     cell.nametag.text = String(htmlEncodedString:dataArray[indexPath.row]["tags"][0]["title"].stringValue)
    cell.nametagg.text =  String(htmlEncodedString:dataArray[indexPath.row]["categories"][0]["title"].stringValue)

    cell.fbButton.addTarget(self, action: #selector(homeController.fbClick), for: .touchUpInside)

    cell.commentButton.addTarget(self, action: #selector(homeController.comment), for: .touchUpInside)
    cell.commentButton.setTitle("\(dataArray[indexPath.row]["comment_count"].stringValue) comments", for: .normal)
    cell.leaveComment.addTarget(self, action: #selector(homeController.leavecomment), for: .touchUpInside)

   cell.contentline.text = String(htmlEncodedString:dataArray[indexPath.row]["excerpt"].stringValue)

 return cell
}

and this is the code for button click

@objc func comment(_ sender: Any) {

  let vc = CommentViewController()
    vc.dataArray = dataArray[indexPath.row]["comments"].array
    self.navigationController!.pushViewController(vc, animated: true)

}

i hope you understand my question, thanks

Body:
You've declared the indexPath as a global variable and it's value is NSIndexPath(row: 0, section: 0) as you said.

in comments(_:) function you've used indexPath.row but this row is 0 so it is first post's comments.

You don't need to set tapgesture to cell's button.

In homeViewCell you should create IBAction for the button and call closure when it triggered ->

class homeViewCell: UICollectionViewCell {

    public var didTapComment: (() -> Void)?

    @IBAction func didTapCommentButton(_ sender: UIButton) {
        didTapComment?()
    }
}

Set didTapComment's action in cellForItemAt like this ->

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! homeViewCell

    cell.didTapComment = { [weak self] in
        let vc = CommentViewController()
        vc.dataArray = dataArray[indexPath.row]["comments"].array
        self?.navigationController!.pushViewController(vc, animated: true)
    }

    let url = dataArray[indexPath.row]["thumbnail_images"]["medium"]["url"].stringValue

    cell.imageArticle.sd_setImage(with: NSURL(string: url) as URL?, placeholderImage:UIImage(named: "empty.png"))
    cell.nametag.text = String(htmlEncodedString:dataArray[indexPath.row]["tags"][0]["title"].stringValue)
    cell.nametagg.text =  String(htmlEncodedString:dataArray[indexPath.row]["categories"][0]["title"].stringValue)

    cell.fbButton.addTarget(self, action: #selector(homeController.fbClick), for: .touchUpInside)

    cell.commentButton.setTitle("\(dataArray[indexPath.row]["comment_count"].stringValue) comments", for: .normal)
    cell.leaveComment.addTarget(self, action: #selector(homeController.leavecomment), for: .touchUpInside)

    cell.contentline.text = String(htmlEncodedString:dataArray[indexPath.row]["excerpt"].stringValue)

    return cell
 }
}

Remove followings;

cell.commentButton.addTarget(self, action: #selector(homeController.comment), for: .touchUpInside) line from cellForItemAt

@objc func comment(_ sender: Any) function

let indexPath = NSIndexPath(row: 0, section: 0)